// Main app — view router + Tweaks
const { useState: useAppState, useEffect: useAppEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "cream",
  "resultLayout": "ranking",
  "useIllustration": false,
  "flowOrder": "default",
  "showSidePanel": true
}/*EDITMODE-END*/;

function HomeView({ onStart }) {
  return (
    <div style={{ padding: '64px 64px 120px', maxWidth: 1280, margin: '0 auto' }}>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.22em', opacity: 0.6, marginBottom: 24 }}>
        ISSUE 03 — 監修：クリーム太郎 — @cream_taro
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 64, alignItems: 'center' }}>
        <div>
          <h1 className="serif" style={{
            fontSize: 110, fontWeight: 700, lineHeight: 0.92,
            margin: '0 0 32px', letterSpacing: '-0.02em',
          }}>
            贈り物を、<br/>
            <span style={{ fontStyle: 'italic', fontWeight: 400 }}>一緒に</span><br/>
            えらぼう。
          </h1>
          <p className="serif" style={{ fontSize: 19, lineHeight: 1.9, color: 'var(--ink-2)', maxWidth: 520, margin: '0 0 40px' }}>
            8つの質問にひとつずつ答えていただき、<br/>
            あなたの大切な人に向けた5軒のお店をクリーム太郎が案内します。
          </p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
            <button className="btn" onClick={onStart} style={{ padding: '14px 28px', fontSize: 15 }}>
              質問をはじめる →
            </button>
            <div className="hand" style={{ fontSize: 24, color: 'var(--ink-soft)' }}>
              所要 3〜5分
            </div>
          </div>

          <div className="rule-soft" style={{ margin: '48px 0 32px', maxWidth: 520 }}/>

          <div style={{ display: 'flex', gap: 48, maxWidth: 520 }}>
            <Stat n="01" t="質問に答える" d="チャット形式で1問ずつ" />
            <Stat n="02" t="条件で絞り込み" d="予算・場所・日数まで" />
            <Stat n="03" t="5軒からご提案" d="お店のリンクと一緒に" />
          </div>
        </div>

        <div style={{ position: 'relative' }}>
          <Placeholder
            label="メインヴィジュアル：太郎さんと贈り物"
            ratio="4/5"
            style={{ borderRadius: 0 }}
          />
          {/* hand-written note */}
          <div style={{
            position: 'absolute',
            bottom: -36, left: -36,
            background: 'var(--paper)',
            border: '1px solid var(--line)',
            padding: '20px 22px',
            transform: 'rotate(-3deg)',
            maxWidth: 280,
            boxShadow: '6px 6px 0 rgba(42,31,21,0.08)',
          }}>
            <div className="hand" style={{ fontSize: 22, lineHeight: 1.55 }}>
              『誰かのことを思う時間が、<br/>
              いちばんの贈り物。』
            </div>
            <div className="mono" style={{ fontSize: 10, marginTop: 10, opacity: 0.6, letterSpacing: '0.16em' }}>
              — 太郎より
            </div>
          </div>
          {/* page no */}
          <div className="mono" style={{
            position: 'absolute', top: -20, right: -8,
            fontSize: 11, letterSpacing: '0.16em', opacity: 0.5,
          }}>
            P. 003
          </div>
        </div>
      </div>

      {/* Featured categories strip */}
      <section style={{ marginTop: 120 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 24 }}>
          <h2 className="serif" style={{ fontSize: 36, fontWeight: 600, margin: 0 }}>
            今月の<span style={{ fontStyle: 'italic' }}>気になる</span>。
          </h2>
          <span className="mono" style={{ fontSize: 11, opacity: 0.6, letterSpacing: '0.14em' }}>
            EDITOR'S SELECT — 6
          </span>
        </div>
        <div className="rule" style={{ marginBottom: 32 }}/>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 32 }}>
          {window.STORES.slice(0, 3).map((s, i) => (
            <article key={s.id}>
              <Placeholder label={s.placeholder} accent={s.accent} ratio="4/5" style={{ marginBottom: 14 }} />
              <div className="mono" style={{ fontSize: 10, opacity: 0.6, letterSpacing: '0.12em', marginBottom: 4 }}>
                {String(i + 1).padStart(2, '0')} — {s.category}
              </div>
              <h3 className="serif" style={{ fontSize: 22, fontWeight: 600, margin: '0 0 6px' }}>{s.name}</h3>
              <p className="serif" style={{ fontSize: 13, lineHeight: 1.7, color: 'var(--ink-2)', margin: 0 }}>
                {s.desc}
              </p>
            </article>
          ))}
        </div>
      </section>
    </div>
  );
}

function Stat({ n, t, d }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 10, opacity: 0.5, marginBottom: 6, letterSpacing: '0.16em' }}>{n}</div>
      <div className="serif" style={{ fontSize: 16, fontWeight: 600, marginBottom: 2 }}>{t}</div>
      <div style={{ fontSize: 12, color: 'var(--ink-soft)' }}>{d}</div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useAppState('home'); // home | chat | results | admin
  const [answers, setAnswers] = useAppState({});
  const [stores, setStores] = useAppState(window.STORES);
  const [questions] = useAppState(window.QUESTIONS);

  useAppEffect(() => {
    document.body.setAttribute('data-theme', t.theme);
  }, [t.theme]);

  // Reorder questions per tweak
  const orderedQuestions = React.useMemo(() => {
    if (t.flowOrder === 'budget-first') {
      const budget = questions.find(q => q.id === 'budget');
      const days = questions.find(q => q.id === 'days');
      const rest = questions.filter(q => q.id !== 'budget' && q.id !== 'days');
      return [budget, days, ...rest].filter(Boolean);
    }
    if (t.flowOrder === 'short') {
      // shorter flow: only 5 essential questions
      const keep = ['relation', 'scene', 'budget', 'place', 'days'];
      return keep.map(id => questions.find(q => q.id === id)).filter(Boolean);
    }
    return questions;
  }, [questions, t.flowOrder]);

  const reset = () => { setAnswers({}); };

  const handleComplete = (finalAnswers) => {
    setAnswers(finalAnswers);
    setView('results');
  };

  return (
    <>
      <BrandHeader view={view} setView={(v) => { setView(v); if (v === 'home') reset(); }} onReset={reset} />

      {view === 'home' && (
        <HomeView onStart={() => { reset(); setView('chat'); }} />
      )}
      {view === 'chat' && (
        <ChatFlow
          questions={orderedQuestions}
          answers={answers}
          setAnswers={setAnswers}
          onComplete={handleComplete}
          useIllustration={t.useIllustration}
        />
      )}
      {view === 'results' && (
        <Results
          answers={answers}
          stores={stores}
          questions={orderedQuestions}
          onRestart={() => { reset(); setView('chat'); }}
          useIllustration={t.useIllustration}
          layout={t.resultLayout}
        />
      )}
      {view === 'admin' && (
        <Admin
          stores={stores}
          setStores={setStores}
          questions={questions}
        />
      )}

      <TweaksPanel>
        <TweakSection label="テーマ" />
        <TweakColor label="カラー"
          value={t.theme === 'cream' ? '#f3e8cf' : t.theme === 'butter' ? '#f1d999' : t.theme === 'milk' ? '#f4eee0' : '#e6d4b4'}
          options={[
            ['#f3e8cf', '#2a1f15', '#b86a6e'],
            ['#f1d999', '#3a2410', '#d9a85b'],
            ['#f4eee0', '#2a2418', '#6b5a3f'],
            ['#e6d4b4', '#221710', '#7a4f2a'],
          ]}
          onChange={(pal) => {
            const map = { '#f3e8cf': 'cream', '#f1d999': 'butter', '#f4eee0': 'milk', '#e6d4b4': 'cocoa' };
            setTweak('theme', map[pal[0]] || 'cream');
          }}
        />
        <TweakToggle label="イラスト表示"
          value={t.useIllustration}
          onChange={(v) => setTweak('useIllustration', v)} />

        <TweakSection label="質問フロー" />
        <TweakSelect label="順序"
          value={t.flowOrder}
          options={[
            { value: 'default', label: '標準(8問)' },
            { value: 'budget-first', label: '予算優先(8問)' },
            { value: 'short', label: '短縮(5問)' },
          ]}
          onChange={(v) => setTweak('flowOrder', v)} />

        <TweakSection label="結果画面" />
        <TweakRadio label="レイアウト"
          value={t.resultLayout}
          options={[
            { value: 'ranking', label: 'ランキング' },
            { value: 'editorial', label: '雑誌風' },
            { value: 'list', label: 'リスト' },
          ]}
          onChange={(v) => setTweak('resultLayout', v)} />

        <TweakSection label="ナビゲーション" />
        <TweakButton label="質問をはじめる" onClick={() => { reset(); setView('chat'); }} />
        <TweakButton label="サンプル結果を表示" onClick={() => {
          setAnswers({
            relation: 'partner', age: '30s', scene: 'birthday',
            taste: ['sweets', 'coffee'], budget: '5to10',
            place: 'tokyo-west', days: 'week', wrapping: 'yes',
          });
          setView('results');
        }} />
        <TweakButton label="管理画面を開く" onClick={() => setView('admin')} />
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
