// Admin panel — store management with tag editing & conditional rules preview
const { useState: useAdminState, useMemo: useAdminMemo } = React;

function Admin({ stores, setStores, questions }) {
  const [selectedId, setSelectedId] = useAdminState(stores[0]?.id);
  const [filter, setFilter] = useAdminState('');
  const [tab, setTab] = useAdminState('stores'); // stores | rules | questions

  const selected = stores.find(s => s.id === selectedId);
  const filtered = stores.filter(s =>
    !filter || s.name.toLowerCase().includes(filter.toLowerCase()) ||
    s.category.toLowerCase().includes(filter.toLowerCase()) ||
    s.area.toLowerCase().includes(filter.toLowerCase())
  );

  const updateStore = (updates) => {
    setStores(stores.map(s => s.id === selectedId ? { ...s, ...updates } : s));
  };

  const toggleTag = (tag) => {
    if (!selected) return;
    const has = selected.tags.includes(tag);
    updateStore({ tags: has ? selected.tags.filter(t => t !== tag) : [...selected.tags, tag] });
  };

  const addStore = () => {
    const id = 'store-' + Date.now();
    const newStore = {
      id, name: '新規店舗', category: '未分類', area: '東京', price: '¥0〜',
      desc: '説明をここに入力します。', tags: [], placeholder: '商品写真',
      accent: '#6b5a42',
    };
    setStores([...stores, newStore]);
    setSelectedId(id);
  };

  const deleteStore = () => {
    if (!selected) return;
    if (!confirm(`「${selected.name}」を削除しますか？`)) return;
    const next = stores.filter(s => s.id !== selectedId);
    setStores(next);
    setSelectedId(next[0]?.id);
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr', minHeight: 'calc(100vh - 81px)' }}>
      {/* Sidebar list */}
      <aside style={{
        background: 'var(--cream-3)',
        borderRight: '1px solid var(--line)',
        padding: '24px 18px',
        overflowY: 'auto', maxHeight: 'calc(100vh - 81px)',
      }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 18 }}>
          {[
            { id: 'stores', label: '店舗' },
            { id: 'rules', label: 'ルール' },
            { id: 'questions', label: '質問' },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} className="mono" style={{
              flex: 1, appearance: 'none',
              padding: '8px 10px',
              border: '1px solid var(--line)',
              background: tab === t.id ? 'var(--ink)' : 'transparent',
              color: tab === t.id ? 'var(--cream)' : 'var(--ink)',
              fontSize: 10, letterSpacing: '0.1em',
              cursor: 'pointer', borderRadius: 4,
            }}>{t.label}</button>
          ))}
        </div>

        {tab === 'stores' && (
          <>
            <input
              value={filter}
              onChange={e => setFilter(e.target.value)}
              placeholder="店名・地域で検索"
              style={{
                width: '100%', padding: '10px 12px',
                border: '1px solid var(--line)', background: 'var(--paper)',
                borderRadius: 6, fontSize: 13, fontFamily: 'inherit',
                color: 'var(--ink)',
                marginBottom: 12,
              }}
            />
            <button onClick={addStore} className="btn" style={{ width: '100%', justifyContent: 'center', marginBottom: 16 }}>
              + 店舗を追加
            </button>
            <div className="mono" style={{ fontSize: 10, opacity: 0.5, letterSpacing: '0.14em', marginBottom: 8 }}>
              {filtered.length} STORES
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {filtered.map(s => (
                <button key={s.id}
                  onClick={() => setSelectedId(s.id)}
                  style={{
                    appearance: 'none', cursor: 'pointer',
                    textAlign: 'left',
                    padding: '10px 12px',
                    background: selectedId === s.id ? 'var(--ink)' : 'transparent',
                    color: selectedId === s.id ? 'var(--cream)' : 'var(--ink)',
                    border: 'none', borderRadius: 6,
                    display: 'flex', alignItems: 'center', gap: 10,
                    fontFamily: 'inherit',
                  }}>
                  <span style={{
                    width: 8, height: 8, borderRadius: 2, flexShrink: 0,
                    background: s.accent,
                  }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="serif" style={{ fontSize: 14, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</div>
                    <div className="mono" style={{ fontSize: 10, opacity: 0.6, marginTop: 2 }}>
                      {s.category} — {s.tags.length} tags
                    </div>
                  </div>
                </button>
              ))}
            </div>
          </>
        )}

        {tab === 'rules' && <RulesSidebar />}
        {tab === 'questions' && <QuestionsSidebar questions={questions} />}
      </aside>

      {/* Detail */}
      <main style={{ padding: '32px 48px', overflowY: 'auto', maxHeight: 'calc(100vh - 81px)' }}>
        {tab === 'stores' && selected && (
          <StoreEditor
            store={selected}
            onUpdate={updateStore}
            onDelete={deleteStore}
            onToggleTag={toggleTag}
            questions={questions}
          />
        )}
        {tab === 'rules' && <RulesEditor questions={questions} stores={stores} />}
        {tab === 'questions' && <QuestionsEditor questions={questions} />}
      </main>
    </div>
  );
}

function StoreEditor({ store, onUpdate, onDelete, onToggleTag, questions }) {
  return (
    <div style={{ maxWidth: 960 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 24 }}>
        <div>
          <div className="mono" style={{ fontSize: 10, opacity: 0.5, letterSpacing: '0.14em', marginBottom: 6 }}>
            STORE / {store.id.toUpperCase()}
          </div>
          <h2 className="serif" style={{ fontSize: 36, fontWeight: 600, margin: 0, letterSpacing: '-0.01em' }}>
            店舗の編集
          </h2>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn ghost" onClick={onDelete} style={{ color: '#a4453f' }}>削除</button>
          <button className="btn">保存</button>
        </div>
      </div>

      <div className="rule" style={{ marginBottom: 32 }}/>

      {/* Basic fields */}
      <Section title="基本情報">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
          <Field label="店名">
            <input value={store.name} onChange={e => onUpdate({ name: e.target.value })} className="adm-input" />
          </Field>
          <Field label="カテゴリ">
            <input value={store.category} onChange={e => onUpdate({ category: e.target.value })} className="adm-input" />
          </Field>
          <Field label="エリア">
            <input value={store.area} onChange={e => onUpdate({ area: e.target.value })} className="adm-input" />
          </Field>
          <Field label="価格帯">
            <input value={store.price} onChange={e => onUpdate({ price: e.target.value })} className="adm-input" />
          </Field>
        </div>
        <Field label="紹介文">
          <textarea
            value={store.desc}
            onChange={e => onUpdate({ desc: e.target.value })}
            rows={3}
            className="adm-input"
            style={{ resize: 'vertical', fontFamily: 'Shippori Mincho, serif' }}
          />
        </Field>
      </Section>

      {/* Tags by question */}
      <Section title="タグ・条件分岐">
        <p className="serif" style={{ fontSize: 14, color: 'var(--ink-soft)', margin: '0 0 18px' }}>
          この店舗を候補に出す条件を、質問ごとに選択してください。タグの数だけマッチ度が上がります。
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {questions.map(q => (
            <div key={q.id} style={{ padding: '14px 0', borderBottom: '1px solid var(--line-soft)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
                <span className="serif" style={{ fontSize: 15, fontWeight: 500 }}>
                  {q.text.split('\n')[0].replace(/[?？]$/, '')}
                </span>
                <span className="mono" style={{ fontSize: 10, opacity: 0.5, letterSpacing: '0.12em' }}>
                  {q.options.filter(o => store.tags.includes(o.value)).length} / {q.options.length}
                </span>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {q.options.map(opt => {
                  const active = store.tags.includes(opt.value);
                  return (
                    <button key={opt.value}
                      onClick={() => onToggleTag(opt.value)}
                      className={`chip${active ? ' active' : ''}`}
                      style={{ fontSize: 12, padding: '6px 12px' }}>
                      {opt.label}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </Section>

      <Section title="ビジュアル">
        <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 24 }}>
          <Placeholder label={store.placeholder} accent={store.accent} ratio="1/1" />
          <div>
            <Field label="画像説明テキスト(プレースホルダー)">
              <input value={store.placeholder} onChange={e => onUpdate({ placeholder: e.target.value })} className="adm-input" />
            </Field>
            <Field label="アクセントカラー" style={{ marginTop: 12 }}>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <input type="color" value={store.accent}
                  onChange={e => onUpdate({ accent: e.target.value })}
                  style={{ width: 40, height: 36, border: '1px solid var(--line)', background: 'transparent', cursor: 'pointer' }} />
                <input value={store.accent} onChange={e => onUpdate({ accent: e.target.value })} className="adm-input mono" style={{ width: 120 }} />
              </div>
            </Field>
          </div>
        </div>
      </Section>

      <style>{`
        .adm-input {
          width: 100%;
          padding: 9px 12px;
          background: var(--paper);
          border: 1px solid var(--line);
          border-radius: 6px;
          font-family: inherit;
          font-size: 14px;
          color: var(--ink);
        }
        .adm-input:focus {
          outline: none;
          border-color: var(--ink);
        }
      `}</style>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <section style={{ marginBottom: 36 }}>
      <h3 className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', opacity: 0.6, margin: '0 0 14px', fontWeight: 600 }}>
        {title}
      </h3>
      {children}
    </section>
  );
}

function Field({ label, children, style }) {
  return (
    <label style={{ display: 'block', ...style }}>
      <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginBottom: 6, letterSpacing: '0.04em' }}>{label}</div>
      {children}
    </label>
  );
}

function RulesSidebar() {
  return (
    <div>
      <div className="mono" style={{ fontSize: 10, opacity: 0.5, letterSpacing: '0.14em', marginBottom: 8 }}>
        RULE GROUPS
      </div>
      {['予算 × 日数', 'シーン × 関係性', 'エリア × 配送', 'NGアレルギー'].map((r, i) => (
        <div key={r} style={{
          padding: '10px 12px',
          marginBottom: 4,
          border: '1px solid var(--line)',
          borderRadius: 6,
          background: 'var(--paper)',
          fontSize: 13,
          fontFamily: 'Shippori Mincho, serif',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>{r}</span>
            <span className="mono" style={{ fontSize: 10, opacity: 0.5 }}>{(i + 2) * 3}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function RulesEditor({ questions, stores }) {
  return (
    <div style={{ maxWidth: 960 }}>
      <div className="mono" style={{ fontSize: 10, opacity: 0.5, letterSpacing: '0.14em', marginBottom: 6 }}>
        ADVANCED — CONDITIONAL RULES
      </div>
      <h2 className="serif" style={{ fontSize: 36, fontWeight: 600, margin: '0 0 8px' }}>
        条件分岐ルール
      </h2>
      <p className="serif" style={{ fontSize: 15, color: 'var(--ink-soft)', margin: '0 0 32px', maxWidth: 600, lineHeight: 1.7 }}>
        質問の組み合わせで、特定の店舗の重み付けを上げたり除外したりするルールを設定します。
      </p>

      <div className="rule" style={{ marginBottom: 24 }}/>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {[
          { name: '予算 × 日数', when: '予算 が「〜3,000円」 かつ 日数 が「今日」', then: '近隣の即日対応店舗を優先(+3点)' },
          { name: '関係性 × シーン', when: '関係性 が「上司」 かつ シーン が「お礼」', then: '日本酒・焼き菓子カテゴリを優先(+2点)' },
          { name: 'アレルギー除外', when: '好み が「甘いもの」を含まない', then: '焼き菓子・チョコレート系を除外' },
          { name: 'オンライン優先', when: '日数 が「1ヶ月以内」 かつ 場所 が「オンライン配送」', then: 'EC対応店舗のみ表示' },
        ].map((rule, i) => (
          <article key={i} style={{
            padding: '20px 24px',
            border: '1px solid var(--line)',
            borderRadius: 8,
            background: 'var(--paper)',
            display: 'grid',
            gridTemplateColumns: '40px 1fr auto',
            gap: 18, alignItems: 'center',
          }}>
            <span className="serif" style={{ fontSize: 28, fontStyle: 'italic', color: 'var(--ink-soft)' }}>
              {String(i + 1).padStart(2, '0')}
            </span>
            <div>
              <div className="serif" style={{ fontSize: 17, fontWeight: 600, marginBottom: 4 }}>{rule.name}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginBottom: 4 }}>
                <span className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', marginRight: 6 }}>IF</span>
                {rule.when}
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>
                <span className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', marginRight: 6 }}>THEN</span>
                {rule.then}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <button className="btn ghost" style={{ padding: '6px 12px', fontSize: 12 }}>編集</button>
            </div>
          </article>
        ))}
      </div>

      <button className="btn" style={{ marginTop: 24 }}>+ ルールを追加</button>
    </div>
  );
}

function QuestionsSidebar({ questions }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 10, opacity: 0.5, letterSpacing: '0.14em', marginBottom: 8 }}>
        {questions.length} QUESTIONS
      </div>
      {questions.map((q, i) => (
        <div key={q.id} style={{
          padding: '10px 12px', marginBottom: 4,
          border: '1px solid var(--line)', borderRadius: 6, background: 'var(--paper)',
        }}>
          <div className="mono" style={{ fontSize: 9, opacity: 0.5, marginBottom: 2 }}>
            Q{String(i + 1).padStart(2, '0')} / {q.type}
          </div>
          <div className="serif" style={{ fontSize: 13 }}>
            {q.text.split('\n')[0].replace(/[?？]$/, '')}
          </div>
        </div>
      ))}
    </div>
  );
}

function QuestionsEditor({ questions }) {
  return (
    <div style={{ maxWidth: 960 }}>
      <div className="mono" style={{ fontSize: 10, opacity: 0.5, letterSpacing: '0.14em', marginBottom: 6 }}>
        QUESTION FLOW
      </div>
      <h2 className="serif" style={{ fontSize: 36, fontWeight: 600, margin: '0 0 8px' }}>質問フロー</h2>
      <p className="serif" style={{ fontSize: 15, color: 'var(--ink-soft)', margin: '0 0 32px', maxWidth: 600 }}>
        ユーザーに尋ねる質問の順序と内容を編集します。ドラッグ&ドロップで並び替え可能(モック)。
      </p>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {questions.map((q, i) => (
          <article key={q.id} style={{
            display: 'grid', gridTemplateColumns: '48px 1fr 100px auto',
            gap: 18, alignItems: 'center',
            padding: '18px 22px',
            border: '1px solid var(--line)', borderRadius: 8, background: 'var(--paper)',
          }}>
            <span className="mono" style={{ fontSize: 11, opacity: 0.5, cursor: 'grab' }}>⋮⋮ {String(i + 1).padStart(2, '0')}</span>
            <div>
              <div className="serif" style={{ fontSize: 16, fontWeight: 500, marginBottom: 4 }}>
                {q.text.split('\n')[0]}
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                {q.options.slice(0, 5).map(o => (
                  <span key={o.value} className="mono" style={{
                    fontSize: 10, padding: '2px 8px', background: 'var(--cream-3)',
                    border: '1px solid var(--line-soft)', borderRadius: 999,
                  }}>{o.label}</span>
                ))}
                {q.options.length > 5 && (
                  <span className="mono" style={{ fontSize: 10, opacity: 0.5, padding: '2px 4px' }}>
                    +{q.options.length - 5}
                  </span>
                )}
              </div>
            </div>
            <span className="mono" style={{ fontSize: 10, opacity: 0.6, letterSpacing: '0.1em' }}>
              {q.type === 'multi' ? 'MULTI' : 'SINGLE'}
            </span>
            <button className="btn ghost" style={{ padding: '6px 12px', fontSize: 12 }}>編集</button>
          </article>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Admin });
