// 2. 事前アンケートフォーム (参加者用) — 完全インタラクティブ

function ScreenSurvey({ theme, initialStep = 0 }) {
  const s = useStore();
  const [step, setStep] = React.useState(initialStep);
  const [draft, setDraft] = React.useState({
    name: '', avatar: '', area: '', age: '', count: '',
    themes: [], action: '', talk: '', spot: '', message: '',
  });
  const TOTAL = 4;

  const toggle = (k, v) => {
    setDraft(d => {
      const arr = d[k] || [];
      return { ...d, [k]: arr.includes(v) ? arr.filter(x => x !== v) : [...arr, v] };
    });
  };
  const set = (k, v) => setDraft(d => ({ ...d, [k]: v }));

  const submit = () => {
    s.add(draft);
    setStep(TOTAL); // 完了画面
  };

  return (
    <Phone theme={theme}>
      <StatusBar theme={theme} />

      {/* ヘッダー */}
      <div style={{
        padding: '12px 20px 16px',
        background: theme.surface,
        borderBottom: `1px solid ${theme.border}`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <BrandMark theme={theme} size="sm" />
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: theme.text, lineHeight: 1.2 }}>
              事前アンケート
            </div>
            <div style={{ fontSize: 11, color: theme.textMuted }}>
              交流を活性化するための情報です
            </div>
          </div>
        </div>
        {/* ステップインジケータ */}
        {step < TOTAL && (
          <div style={{ display: 'flex', gap: 4 }}>
            {Array.from({ length: TOTAL }).map((_, i) => (
              <div key={i} style={{
                flex: 1, height: 4, borderRadius: 99,
                background: i <= step ? theme.primary : theme.chipBg,
                transition: 'background .25s',
              }}></div>
            ))}
          </div>
        )}
      </div>

      <div style={{ padding: '20px 16px 80px' }}>
        {step === 0 && <Step0 theme={theme} draft={draft} set={set} />}
        {step === 1 && <Step1 theme={theme} draft={draft} set={set} toggle={toggle} />}
        {step === 2 && <Step2 theme={theme} draft={draft} set={set} />}
        {step === 3 && <Step3 theme={theme} draft={draft} set={set} />}
        {step === TOTAL && <StepDone theme={theme} draft={draft} />}
      </div>

      {/* 下部ナビ */}
      {step < TOTAL && (
        <div style={{
          position: 'sticky', bottom: 0, padding: '12px 16px',
          background: theme.surface, borderTop: `1px solid ${theme.border}`,
          display: 'flex', gap: 8,
        }}>
          {step > 0 && (
            <Btn theme={theme} variant="plain" size="md" onClick={() => setStep(s => s - 1)}>戻る</Btn>
          )}
          <Btn theme={theme} fullWidth size="md"
            onClick={() => step < TOTAL - 1 ? setStep(s => s + 1) : submit()}>
            {step < TOTAL - 1 ? '次へ進む' : '回答を送信'}
          </Btn>
        </div>
      )}
    </Phone>
  );
}

function Field({ theme, label, sublabel, required, children }) {
  return (
    <div style={{ marginBottom: 20 }}>
      <label style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 8 }}>
        <span style={{ fontSize: 14, fontWeight: 700, color: theme.text }}>{label}</span>
        {required && (
          <span style={{ fontSize: 10, padding: '1px 5px', background: theme.primary,
            color: '#fff', borderRadius: 3, fontWeight: 700 }}>必須</span>
        )}
        {sublabel && (
          <span style={{ fontSize: 11, color: theme.textSub }}>{sublabel}</span>
        )}
      </label>
      {children}
    </div>
  );
}

function TextInput({ theme, value, onChange, placeholder, multiline }) {
  const Tag = multiline ? 'textarea' : 'input';
  return (
    <Tag value={value || ''} onChange={e => onChange(e.target.value)} placeholder={placeholder}
      rows={multiline ? 3 : undefined}
      style={{
        width: '100%', padding: '12px 14px',
        borderRadius: theme.radius, border: `1.5px solid ${theme.border}`,
        background: theme.surface, color: theme.text,
        fontSize: 14, fontFamily: theme.bodyFont,
        outline: 'none', resize: 'vertical',
        boxSizing: 'border-box',
      }}
      onFocus={e => e.target.style.borderColor = theme.primary}
      onBlur={e => e.target.style.borderColor = theme.border}
    />
  );
}

function RadioGroup({ theme, value, onChange, options }) {
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
      {options.map(o => (
        <Chip key={o.value || o} theme={theme}
          active={value === (o.value || o)}
          onClick={() => onChange(o.value || o)}>
          {o.label || o}
        </Chip>
      ))}
    </div>
  );
}

// Step 0: 基本情報
function Step0({ theme, draft, set }) {
  return (
    <div>
      <h2 style={{ margin: '0 0 16px', fontFamily: theme.headingFont, fontSize: 19, fontWeight: 800, color: theme.text }}>
        まずはあなたのこと
      </h2>

      <Field theme={theme} label="ニックネーム" required sublabel="本名・ハンドル名どちらでも">
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          {draft.name && <Avatar theme={theme} name={draft.name} size={48} />}
          <div style={{ flex: 1 }}>
            <TextInput theme={theme} value={draft.name} onChange={v => set('name', v)} placeholder="例: たけし" />
          </div>
        </div>
        <div style={{ fontSize: 11, color: theme.textSub, marginTop: 6 }}>
          名前の頂文字がプロフィールアイコンになります
        </div>
      </Field>

      <Field theme={theme} label="お住まいエリア" required>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {MIE_AREAS.map(a => (
            <Chip key={a.id} theme={theme}
              active={draft.area === a.id}
              onClick={() => set('area', a.id)}>{a.label}</Chip>
          ))}
        </div>
      </Field>

      <Field theme={theme} label="年代" sublabel="任意・近い世代と話したい方向け">
        <RadioGroup theme={theme} value={draft.age} onChange={v => set('age', v)} options={AGE_RANGES} />
      </Field>

      <Field theme={theme} label="オフ会参加回数">
        <RadioGroup theme={theme} value={draft.count} onChange={v => set('count', v)}
          options={ATTEND_COUNT.map(c => ({ value: c.id, label: c.label }))} />
      </Field>
    </div>
  );
}

// Step 1: 興味のあるテーマ
function Step1({ theme, draft, toggle }) {
  return (
    <div>
      <h2 style={{ margin: '0 0 6px', fontFamily: theme.headingFont, fontSize: 19, fontWeight: 800 }}>
        興味のあるテーマ
      </h2>
      <p style={{ margin: '0 0 16px', fontSize: 12.5, color: theme.textMuted }}>
        複数選択OK（3つくらいまでがおすすめ）
      </p>

      {Object.entries(INTEREST_THEMES).map(([group, items]) => (
        <Field key={group} theme={theme} label={group}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {items.map(t => (
              <Chip key={t.id} theme={theme} color={t.color}
                active={draft.themes.includes(t.id)}
                onClick={() => toggle('themes', t.id)}>
                {t.label}
              </Chip>
            ))}
          </div>
        </Field>
      ))}

      <Card theme={theme} style={{ background: theme.primarySoft, border: 'none', marginTop: 8 }}>
        <div style={{ fontSize: 12.5, color: theme.text, lineHeight: 1.6 }}>
          <strong>選んだタグ: {draft.themes.length}個</strong><br/>
          このタグで同じ興味の人を見つけやすくなります。
        </div>
      </Card>
    </div>
  );
}

// Step 2: 行動と話したいこと
function Step2({ theme, draft, set }) {
  return (
    <div>
      <h2 style={{ margin: '0 0 16px', fontFamily: theme.headingFont, fontSize: 19, fontWeight: 800 }}>
        最近のあなた
      </h2>

      <Field theme={theme} label="最近やった小さい行動" required
        sublabel="自慢じゃなく、ささやかでOK">
        <TextInput theme={theme} multiline value={draft.action} onChange={v => set('action', v)}
          placeholder="例: サブスクを3つ解約した / 毎朝の散歩を1週間続けた" />
      </Field>

      <Field theme={theme} label="今日話してみたい / 聞きたいこと"
        sublabel="名札にも載ります">
        <TextInput theme={theme} multiline value={draft.talk} onChange={v => set('talk', v)}
          placeholder="例: ブログ収益化のSEO / 子育てしながらの副業" />
      </Field>
    </div>
  );
}

// Step 3: 三重ローカル & メッセージ
function Step3({ theme, draft, set }) {
  return (
    <div>
      <h2 style={{ margin: '0 0 16px', fontFamily: theme.headingFont, fontSize: 19, fontWeight: 800 }}>
        最後にもうひとつ
      </h2>

      <Field theme={theme} label="好きな三重スポット・グルメ"
        sublabel="アイスブレイクの話題に">
        <TextInput theme={theme} value={draft.spot} onChange={v => set('spot', v)}
          placeholder="例: 津餃子 / おかげ横丁 / なばなの里" />
      </Field>

      <Field theme={theme} label="意気込み・ひとことメッセージ">
        <TextInput theme={theme} multiline value={draft.message} onChange={v => set('message', v)}
          placeholder="例: 初参加です。よろしくお願いします！" />
      </Field>

      <Card theme={theme} style={{ background: theme.surfaceAlt }}>
        <div style={{ fontSize: 12, color: theme.textMuted, lineHeight: 1.7 }}>
          回答内容は当日の参加者一覧に掲載されます。<br/>
          後から編集も可能です。
        </div>
      </Card>
    </div>
  );
}

// 完了画面
function StepDone({ theme, draft }) {
  return (
    <div style={{ textAlign: 'center', padding: '24px 8px' }}>
      <div style={{
        width: 64, height: 64, borderRadius: '50%',
        background: theme.primary, color: '#fff',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 32, marginBottom: 16,
      }}>✓</div>
      <h2 style={{ margin: '0 0 8px', fontFamily: theme.headingFont, fontSize: 22, fontWeight: 800 }}>
        回答完了！
      </h2>
      <p style={{ margin: '0 0 24px', fontSize: 13, color: theme.textMuted, lineHeight: 1.7 }}>
        ありがとうございます、{draft.name || 'あなた'}さん。<br/>
        当日お会いできるのを楽しみにしています。
      </p>
      <Card theme={theme} style={{ textAlign: 'left' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
          <Avatar theme={theme} name={draft.name} size={48} />
          <div>
            <div style={{ fontSize: 16, fontWeight: 800, color: theme.text }}>{draft.name || '匿名'}</div>
            <div style={{ fontSize: 11, color: theme.textMuted }}>
              {MIE_AREAS.find(a => a.id === draft.area)?.label || 'エリア未設定'}
              {draft.age && ` · ${draft.age}`}
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {draft.themes.map(t => {
            const tag = THEME_BY_ID[t];
            return tag ? <Chip key={t} theme={theme} color={tag.color} active size="sm">{tag.label}</Chip> : null;
          })}
        </div>
      </Card>
      <Btn theme={theme} fullWidth size="md" variant="plain" style={{ marginTop: 16 }}>
        参加者一覧を見る
      </Btn>
    </div>
  );
}

Object.assign(window, { ScreenSurvey });
