// demo.jsx — "직접 해보세요" 인터랙티브 데모 (AI 호출 0, 정적 매핑)
// 시나리오 구조 = 시뮬 규격 동형: situation / choices / reasons / reflection_map / reveal
const CD = window.KEITTA_COLORS;

const DEMO_SCENARIOS = [
  {
    id: 'growth_streak',
    situation: '어느 성장주. 3일 연속 상한가로 12,800원 → 24,500원.\n커뮤니티는 "지금 놓치면 바보". 하지만 실적·계약 뉴스는 없습니다.',
    stats: [ ['3일 수익률', '+91%'], ['거래량', '8.4배'], ['관련 뉴스', '없음'] ],
    reasons: [
      { key: 'more_up', label: '더 오를 것 같아서', reflect: '"더 오를 것 같다"는 느낌은 방향이지 근거가 아니에요.' },
      { key: 'everyone', label: '다들 사니까', reflect: '"다들 사니까" — 남의 확신은 나의 근거가 될 수 없어요.' },
      { key: 'no_reason', label: '오른 이유를 모르겠어서', reflect: '오른 이유를 모른다면, 내릴 이유도 모른다는 뜻이에요.', good: true },
      { key: 'small_bet', label: '잃어도 되는 만큼만', reflect: '잃어도 되는 크기를 먼저 정한 건, 리스크를 본 판단이에요.', good: true },
    ],
    reveal: { name: '2020년 어느 바이오주', after: '그 후 60일: −41%', counter: '반대로 같은 패턴에서 +38% 더 간 사례도 있습니다' },
  },
  {
    id: 'crash_hold',
    situation: '보유 중인 종목이 하루 만에 −18%. 특별한 개별 악재는 없고,\n시장 전체가 약세. 커뮤니티엔 "지금이라도 던져라" 글이 쏟아집니다.',
    stats: [ ['당일', '−18%'], ['평가손', '−240만'], ['개별 악재', '없음'] ],
    reasons: [
      { key: 'more_down', label: '더 빠질 것 같아서', reflect: '"더 빠질 것 같다"는 공포이지, 악재 분석이 아니에요.' },
      { key: 'cant_watch', label: '지켜보기 힘들어서', reflect: '못 견디겠다는 감정은 진짜예요 — 다만 그게 매도 근거는 아니에요.' },
      { key: 'others_sell', label: '다들 파니까', reflect: '"다들 파니까" — 커뮤니티의 공포는 바닥 신호일 때도 많아요.' },
      { key: 'check_reason', label: '살 때 근거가 깨졌는지 보려고', reflect: '매수 근거가 유효한지 먼저 확인하는 건, 과정을 지킨 판단이에요.', good: true },
    ],
    reveal: { name: '2020년 3월, 어느 우량주', after: '그 후 60일: +52%', counter: '물론 그대로 회복 못 한 종목도 있었습니다' },
  },
  {
    id: 'expert_call',
    situation: '구독자 많은 전문가가 "이 종목은 무조건 2배"라고 단언합니다.\n과거 추천도 몇 번 적중했다고. 영상 속 근거를 직접 확인하진 않았습니다.',
    stats: [ ['목표가', '+120%'], ['전문가 추천', '있음'], ['직접 검증', '안 함'] ],
    reasons: [
      { key: 'expert', label: '전문가가 확신하니까', reflect: '전문가의 확신도 편향의 이유가 될 수 있어요 — 적중률은 대개 50~60%.' },
      { key: 'past_hit', label: '예전에 적중한 적 있어서', reflect: '몇 번의 적중은 실력을 가리기엔 표본이 너무 작아요.' },
      { key: 'sounds_right', label: '말이 그럴듯해서', reflect: '설득력과 정확성은 다른 거예요. 스토리가 매력적일수록 데이터를 봐야 해요.' },
      { key: 'will_check', label: '근거를 직접 확인하려고', reflect: '남의 결론을 내 데이터로 검증하려는 건, 과정을 지킨 판단이에요.', good: true },
    ],
    reveal: { name: '2021년 어느 테마주', after: '그 후 60일: −29%', counter: '같은 해 전문가 추천이 크게 적중한 경우도 있었습니다' },
  },
  {
    id: 'value_trap',
    situation: '어느 종목이 고점 대비 −60%. PER은 업종 평균의 절반.\n"이 가격이면 무조건 싸다"는 생각이 듭니다. 최근 공시는 안 봤습니다.',
    stats: [ ['고점 대비', '−60%'], ['PER', '업종 1/2'], ['최근 공시', '미확인'] ],
    reasons: [
      { key: 'cheap', label: '싸 보여서', reflect: '"싸 보이는 것"과 "실제로 싼 것"은 달라요 — 왜 싼지가 먼저예요.' },
      { key: 'past_high', label: '예전엔 더 비쌌으니까', reflect: '과거 고점은 현재 가치와 무관해요. 그건 앵커일 뿐이에요.' },
      { key: 'rebound', label: '반등하면 크게 먹으니까', reflect: '반등을 전제로 한 기대는, 하락 이유를 건너뛴 판단이에요.' },
      { key: 'why_cheap', label: '싼 이유를 먼저 보려고', reflect: 'PER이 낮은 이유부터 확인하는 건, 과정을 지킨 판단이에요.', good: true },
    ],
    reveal: { name: '2019년 어느 제조주', after: '그 후 1년: −38%', counter: '반대로 진짜 저평가였던 종목도 분명 있었습니다' },
  },
  {
    id: 'revenge',
    situation: '어제 −15% 손절했습니다. 아직 속이 쓰린데, 오늘 다른 종목이 급등 중.\n"어제 잃은 거 이걸로 만회하면?" 평소보다 크게 넣고 싶어집니다.',
    stats: [ ['어제 손실', '−15%'], ['오늘 급등주', '+12%'], ['투입 계획', '평소 2배'] ],
    reasons: [
      { key: 'recover', label: '어제 손실을 만회하려고', reflect: '"만회" 목적의 매매는 어제 손실과 오늘 종목을 뒤섞는 거예요.' },
      { key: 'bigger', label: '크게 넣어야 빨리 되니까', reflect: '손실 직후 크기를 키우는 건, 판단이 아니라 도박에 가까워요.' },
      { key: 'fast', label: '지금 안 하면 늦을 것 같아서', reflect: '"지금 아니면 늦는다"는 조급함 자체가 신호예요.' },
      { key: 'cool', label: '하루 쉬고 판단하려고', reflect: '손실 직후 냉각기를 두는 건, 감정과 판단을 분리하는 방법이에요.', good: true },
    ],
    reveal: { name: '흔한 복수 매매 패턴', after: '연구 다수: 손실 직후 매매의 기대수익은 더 낮음', counter: '물론 그날 바로 회복한 사람도 있습니다 — 결과는 아무도 몰라요' },
  },
  {
    id: 'ipo',
    situation: '오늘 상장한 종목. 공모가 대비 벌써 +80%, 계속 오릅니다.\n"올해 최고 IPO"라는 말도. 다만 상장 직후 부정적 뉴스도 하나 보입니다.',
    stats: [ ['공모가 대비', '+80%'], ['상장', '오늘'], ['부정 뉴스', '1건'] ],
    reasons: [
      { key: 'best_ipo', label: '올해 최고라고 하니까', reflect: '"최고"라는 수식은 분위기예요 — 첫날 매수는 평균 이하 수익률로 알려져 있어요.' },
      { key: 'keep_up', label: '계속 오르고 있어서', reflect: '오르는 중이라는 건 방향이지, 살 이유는 아니에요.' },
      { key: 'ignore_bad', label: '부정 뉴스는 사소해 보여서', reflect: '부정적 정보를 작게 본 건, 보고 싶은 것만 본 판단일 수 있어요.' },
      { key: 'wait', label: '며칠 안정되면 다시 보려고', reflect: '변동성이 큰 첫날을 피해 재평가하려는 건, 과정을 지킨 판단이에요.', good: true },
    ],
    reveal: { name: '2022년 어느 IPO', after: '그 후 60일: −47%', counter: '반대로 첫날 사서 크게 번 IPO도 있었습니다' },
  },
];

function Demo() {
  const { Section, SectionLabel } = window.LandingSections1;
  const [scenario, setScenario] = React.useState(() => DEMO_SCENARIOS[Math.floor(Math.random() * DEMO_SCENARIOS.length)]);
  const [screen, setScreen] = React.useState(1);
  const [action, setAction] = React.useState(null);
  const [picked, setPicked] = React.useState([]);
  const accent = CD.body;

  const restart = () => {
    setScenario(prev => {
      const others = DEMO_SCENARIOS.filter(s => s.id !== prev.id);
      return others[Math.floor(Math.random() * others.length)] || prev;
    });
    setScreen(1); setAction(null); setPicked([]);
  };

  const toggle = (k) => setPicked(p => p.includes(k) ? p.filter(x => x !== k) : [...p, k]);
  const chosenReasons = scenario.reasons.filter(r => picked.includes(r.key));
  const traps = chosenReasons.filter(r => !r.good);
  const goods = chosenReasons.filter(r => r.good);

  const card = { background: '#FFFFFF', border: '1px solid rgba(124,92,252,0.16)', borderRadius: 20, padding: '30px 32px', boxShadow: '0 20px 50px rgba(124,92,252,0.10)', maxWidth: 620, margin: '0 auto' };
  const stepDot = (n) => ({ width: 24, height: 24, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 800, flexShrink: 0, background: n <= screen ? accent : 'rgba(124,92,252,0.15)', color: n <= screen ? '#fff' : accent });

  return (
    <Section bg="#F3EEFF" id="demo">
      <div style={{ textAlign: 'center', marginBottom: 34 }}>
        <SectionLabel>TRY IT</SectionLabel>
        <h2 style={{ fontFamily: "'Fraunces', serif", fontWeight: 600, fontSize: 38, letterSpacing: '-0.02em', color: '#241C3D', margin: '10px 0 8px', lineHeight: 1.15 }}>
          가입 전에, <span style={{ color: accent }}>직접</span> 해보세요
        </h2>
        <p style={{ fontSize: 15, color: '#6A6480', fontWeight: 500, margin: 0 }}>익명화된 과거 상황 하나. 30초면 됩니다.</p>
      </div>

      <div style={card}>
        {/* 진행 표시 */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 24 }}>
          {[1,2,3,4].map(n => (
            <React.Fragment key={n}>
              <div style={stepDot(n)}>{n}</div>
              {n < 4 && <div style={{ flex: 1, height: 2, background: n < screen ? accent : 'rgba(124,92,252,0.15)' }}/>}
            </React.Fragment>
          ))}
        </div>

        {screen === 1 && (
          <div>
            <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.14em', color: accent, marginBottom: 14 }}>상황 · 종목명 가림</div>
            <p style={{ fontSize: 17, lineHeight: 1.6, color: '#241C3D', fontWeight: 500, whiteSpace: 'pre-line', margin: '0 0 20px' }}>{scenario.situation}</p>
            <div style={{ display: 'flex', gap: 10, marginBottom: 26, flexWrap: 'wrap' }}>
              {scenario.stats.map(([k,v],i) => (
                <div key={i} style={{ flex: '1 1 120px', background: '#F6F3FF', borderRadius: 12, padding: '12px 14px' }}>
                  <div style={{ fontSize: 11, color: '#8A82A6', fontWeight: 600, marginBottom: 4 }}>{k}</div>
                  <div style={{ fontFamily: "'Fraunces', serif", fontSize: 20, fontWeight: 600, color: '#241C3D' }}>{v}</div>
                </div>
              ))}
            </div>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#6A6480', marginBottom: 12 }}>당신이라면?</div>
            <div style={{ display: 'flex', gap: 10, marginBottom: 18 }}>
              {['산다','관망','더 알아본다'].map(a => (
                <button key={a} onClick={() => setAction(a)}
                  style={{ flex: 1, padding: '15px 0', borderRadius: 13, border: `1px solid ${action===a ? accent : 'rgba(124,92,252,0.25)'}`, background: action===a ? accent : '#fff', color: action===a ? '#fff' : '#241C3D', fontSize: 14.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', transition: 'all .15s' }}>{a}</button>
              ))}
            </div>
            <button disabled={!action} onClick={() => setScreen(2)}
              style={{ width: '100%', padding: '15px 0', borderRadius: 13, border: 0, background: action ? accent : 'rgba(124,92,252,0.2)', color: '#fff', fontSize: 15, fontWeight: 700, cursor: action ? 'pointer' : 'not-allowed', fontFamily: 'inherit' }}>다음</button>
          </div>
        )}

        {screen === 2 && (
          <div>
            <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.14em', color: accent, marginBottom: 6 }}>이유 · 복수 선택</div>
            <p style={{ fontSize: 15, color: '#6A6480', fontWeight: 500, margin: '0 0 18px' }}>왜 그렇게 하고 싶었나요? 해당되는 걸 다 골라주세요.</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9, marginBottom: 24 }}>
              {scenario.reasons.map(r => {
                const on = picked.includes(r.key);
                return (
                  <button key={r.key} onClick={() => toggle(r.key)}
                    style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderRadius: 13, border: `1px solid ${on ? accent : 'rgba(124,92,252,0.2)'}`, background: on ? 'rgba(124,92,252,0.08)' : '#fff', cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', transition: 'all .15s' }}>
                    <span style={{ width: 20, height: 20, borderRadius: 6, flexShrink: 0, border: `2px solid ${on ? accent : 'rgba(124,92,252,0.35)'}`, background: on ? accent : '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 12, fontWeight: 900 }}>{on ? '✓' : ''}</span>
                    <span style={{ fontSize: 15, fontWeight: 600, color: '#241C3D' }}>{r.label}</span>
                  </button>
                );
              })}
            </div>
            <button disabled={picked.length===0} onClick={() => setScreen(3)}
              style={{ width: '100%', padding: '15px 0', borderRadius: 13, border: 0, background: picked.length ? accent : 'rgba(124,92,252,0.2)', color: picked.length ? '#fff' : '#fff', fontSize: 15, fontWeight: 700, cursor: picked.length ? 'pointer' : 'not-allowed', fontFamily: 'inherit' }}>결과 보기</button>
          </div>
        )}

        {screen === 3 && (
          <div>
            <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.14em', color: accent, marginBottom: 14 }}>당신 판단에서 보인 것</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 12 }}>
              {traps.map((r,i) => (
                <div key={i} style={{ display: 'flex', gap: 11, alignItems: 'flex-start' }}>
                  <span style={{ color: accent, fontWeight: 800, flexShrink: 0, lineHeight: 1.5 }}>·</span>
                  <span style={{ fontSize: 15, lineHeight: 1.55, color: '#241C3D' }}>{r.reflect}</span>
                </div>
              ))}
              {goods.map((r,i) => (
                <div key={'g'+i} style={{ display: 'flex', gap: 11, alignItems: 'flex-start' }}>
                  <span style={{ color: '#1F8A5B', fontWeight: 800, flexShrink: 0, lineHeight: 1.5 }}>·</span>
                  <span style={{ fontSize: 15, lineHeight: 1.55, color: '#241C3D' }}>{r.reflect}</span>
                </div>
              ))}
            </div>
            <div style={{ background: '#F6F3FF', borderRadius: 12, padding: '13px 15px', fontSize: 13, lineHeight: 1.55, color: '#6A6480', marginBottom: 24 }}>
              고른 이유만 비춰본 거예요. 산다·관망 중 뭘 골랐는지는 채점하지 않아요 — 그건 시장이 정하니까요.
            </div>
            <button onClick={() => setScreen(4)} style={{ width: '100%', padding: '15px 0', borderRadius: 13, border: 0, background: accent, color: '#fff', fontSize: 15, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>이 종목은 뭐였을까?</button>
          </div>
        )}

        {screen === 4 && (
          <div>
            <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.14em', color: accent, marginBottom: 14 }}>공개</div>
            <p style={{ fontSize: 17, lineHeight: 1.6, color: '#241C3D', fontWeight: 600, margin: '0 0 6px' }}>이 상황은 <span style={{ color: accent }}>{scenario.reveal.name}</span>이었습니다.</p>
            <div style={{ fontFamily: "'Fraunces', serif", fontSize: 26, fontWeight: 600, color: '#241C3D', margin: '0 0 18px' }}>{scenario.reveal.after}</div>
            <div style={{ background: '#F6F3FF', borderRadius: 12, padding: '14px 16px', fontSize: 14, lineHeight: 1.6, color: '#4A4460', marginBottom: 22 }}>
              {scenario.reveal.counter} — 결과는 아무도 모릅니다.<br/>Keitta가 보는 건 결과가 아니라, 방금 그 '과정'이에요.
            </div>
            <a href="#beta" onClick={() => { try { localStorage.setItem('keitta_demo', JSON.stringify({ scenario: scenario.id, action, picked, ts: Date.now(), label: '체험' })); } catch(e){} }} style={{ display: 'block', textAlign: 'center', padding: '16px 0', borderRadius: 14, background: accent, color: '#fff', fontSize: 15.5, fontWeight: 700, textDecoration: 'none', marginBottom: 12 }}>내 진짜 판단으로 해보기 → 베타 신청</a>
            <button onClick={restart} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, width: '100%', padding: '12px 0', borderRadius: 13, border: '1px solid rgba(124,92,252,0.25)', background: '#fff', color: accent, fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', marginBottom: 14 }}>↺ 다른 상황으로 다시 해보기</button>
            <p style={{ fontSize: 11, color: '#9A93AE', textAlign: 'center', lineHeight: 1.5, margin: 0 }}>이 기록은 이 기기에만 임시 저장돼요 · 서버 전송 없음<br/>과거 사례이며 특정 종목·시점의 매매를 권유하지 않습니다.</p>
          </div>
        )}
      </div>
    </Section>
  );
}

window.LandingDemo = { Demo };
