// demo-install.jsx — 일반인 친화 데모 + 가격(묘운 무료 우선) + 개발자 설치(별도)
const { useState: useStateDI, useEffect: useEffectDI } = React;

function Demo({ lang }) {
  const t = (ko, en) => (lang === 'ko' ? ko : en);
  const [date, setDate] = useStateDI('1992-05-25');
  const [time, setTime] = useStateDI('14:30');
  const [place, setPlace] = useStateDI('서울');
  const [persona, setPersona] = useStateDI('warm-30s');
  const [exp, setExp] = useStateDI('일반');
  const [loading, setLoading] = useStateDI(false);
  const [result, setResult] = useStateDI(true);

  const personas = [
    { id: 'warm-30s',  ko: '따듯한 친구 (30대)',  en: 'Warm 30s friend' },
    { id: 'mentor-60s', ko: '정통 어르신 (60대)', en: 'Orthodox 60s mentor' },
    { id: 'analyst',   ko: '데이터 분석가',        en: 'Data analyst' },
    { id: 'enthusiast',ko: '명리 매니아',          en: 'Myeongri enthusiast' },
  ];
  const levels = lang === 'ko'
    ? ['입문', '일반', '심화', '전문가']
    : ['Novice', 'General', 'Deep', 'Expert'];

  const run = () => {
    setLoading(true); setResult(false);
    setTimeout(() => { setLoading(false); setResult(true); }, 1100);
  };

  return (
    <section className="block" id="demo">
      <div className="container">
        <div className="demo-wrap">
          <div className="section-eyebrow">
            <span className="hanja">試</span>
            {t('직접 보기', 'See it yourself')}
          </div>
          <h2 className="section-title">
            {t('내 생년월일로 차이를 확인하세요.', 'Try it with your own birth date.')}
          </h2>
          <p className="section-sub">
            {t('생년월일·시·장소를 바꾸면 두 응답이 함께 갱신됩니다. 입력하신 정보는 14일 후 자동으로 삭제됩니다.',
               'Change birth date, time, or place — both sides refresh. Your input auto-purges after 14 days.')}
          </p>

          <div className="demo-grid">
            <div className="demo-form">
              <div className="field">
                <label>{t('생년월일', 'Birth date')}</label>
                <input type="date" value={date} onChange={e => setDate(e.target.value)} />
              </div>
              <div className="row2">
                <div className="field">
                  <label>{t('태어난 시각', 'Time of birth')}</label>
                  <input type="time" value={time} onChange={e => setTime(e.target.value)} />
                </div>
                <div className="field">
                  <label>{t('태어난 곳', 'Place of birth')}</label>
                  <input type="text" value={place} onChange={e => setPlace(e.target.value)} />
                </div>
              </div>
              <div className="field">
                <label>{t('말투', 'Voice')} · {personas.length}{t('가지', '')}</label>
                <select value={persona} onChange={e => setPersona(e.target.value)}>
                  {personas.map(p => <option key={p.id} value={p.id}>{lang === 'ko' ? p.ko : p.en}</option>)}
                </select>
              </div>
              <div className="field">
                <label>{t('풀이 깊이', 'Depth')}</label>
                <div className="demo-seg">
                  {levels.map(l => (
                    <button key={l} className={exp === l ? 'on' : ''} onClick={() => setExp(l)}>{l}</button>
                  ))}
                </div>
              </div>
              <button className="demo-go" onClick={run} disabled={loading}>
                {loading ? <span>{t('풀이 중…', 'Calculating…')}</span> : (
                  <React.Fragment>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
                    {t('나란히 비교하기', 'Compare side by side')}
                  </React.Fragment>
                )}
              </button>
              <div style={{fontSize:11.5, color:'rgba(255,244,232,.55)', textAlign:'center', marginTop:2, lineHeight:1.5}}>
                {t('회원가입 없이 무료로 시도', 'Free to try, no sign-up')}
              </div>
            </div>

            <div className="demo-out">
              {/* 일반 AI 챗봇 */}
              <div className="demo-card">
                <div className="ttl">
                  <span>{t('일반 AI 챗봇 답변', 'Generic AI chatbot')}</span>
                  <span className="pill r">{t('틀린 풀이', 'wrong')}</span>
                </div>
                <div className="body">
                  {loading ? (
                    <React.Fragment>
                      <div className="demo-skel" style={{width:'88%'}}></div>
                      <div className="demo-skel" style={{width:'72%'}}></div>
                      <div className="demo-skel" style={{width:'92%'}}></div>
                      <div className="demo-skel" style={{width:'60%'}}></div>
                    </React.Fragment>
                  ) : result ? (
                    <React.Fragment>
                      <div className="pillars-row">
                        <span>壬</span><span className="mismatch">午</span><span className="mismatch">午</span><span>未</span>
                      </div>
                      <p>{t(
                        '"1992년 5월 25일생은 壬午年 庚午月 庚午日… 화 기운이 강합니다. 이 시기엔 격정적이고, 이혼수도 보이네요."',
                        '"Born May 25, 1992 → year 壬午, month 庚午, day 庚午… strong fire energy. There’s also a divorce indicator for this period."'
                      )}</p>
                      <p style={{color:'#F0A595'}}>{t(
                        '✗ 월주·일주가 잘못된 글자.  ✗ "이혼수" 같은 부정적 단정.  ✗ 안전 안내 없음.',
                        '✗ Wrong month/day stems.  ✗ Negative fatalism ("divorce indicator").  ✗ No safety guidance.'
                      )}</p>
                    </React.Fragment>
                  ) : null}
                </div>
                <div className="meta-row">
                  <span>{t('정확도', 'Accuracy')} <b>~35%</b></span>
                  <span>{t('안전 장치', 'Safety')} <b>{t('없음', 'none')}</b></span>
                </div>
              </div>

              {/* 묘운 사주 */}
              <div className="demo-card" style={{borderColor:'rgba(162,111,62,0.5)'}}>
                <div className="ttl">
                  <span>{t('묘운 사주 답변', 'Myoun Saju')}</span>
                  <span className="pill g">{t('정확', 'verified')}</span>
                </div>
                <div className="body">
                  {loading ? (
                    <React.Fragment>
                      <div className="demo-skel" style={{width:'92%'}}></div>
                      <div className="demo-skel" style={{width:'78%'}}></div>
                      <div className="demo-skel" style={{width:'85%'}}></div>
                      <div className="demo-skel" style={{width:'66%'}}></div>
                    </React.Fragment>
                  ) : result ? (
                    <React.Fragment>
                      <div className="pillars-row">
                        <span>壬</span><span className="verified">乙</span><span className="verified">庚</span><span>癸</span>
                      </div>
                      <p>{t(
                        '"1992년 5월 25일 오후 2:30 한국 시간 — 壬申年 乙巳月 庚辰日 癸未時. 일간 庚금이 巳월의 화토 기운 안에 자리합니다. 안정적인 구조로, 변화는 부정이 아닌 기회로 풀이드립니다."',
                        '"1992-05-25 14:30 KST · year 壬申, month 乙巳, day 庚辰, hour 癸未. The day stem 庚 (metal) sits within an 巳-month fire/earth field — a stable chart we read as opportunity, not as fated misfortune."'
                      )}</p>
                      <p style={{color:'#A8C7B5'}}>{t(
                        '✓ 한국천문연구원 입춘 시각 확인  ✓ 따듯한 화법 · 단정 어휘 차단  ✓ 위기 상황 시 1393 자동 안내',
                        '✓ KASI 立春 verified  ✓ Warm voice · fatalism blocked  ✓ 1393 auto-trigger on crisis'
                      )}</p>
                    </React.Fragment>
                  ) : null}
                </div>
                <div className="meta-row">
                  <span>{t('정확도', 'Accuracy')} <b>100%</b></span>
                  <span>{t('안전 장치', 'Safety')} <b>5{t('단 모두 통과', '/5 PASS')}</b></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.Demo = Demo;

/* ─────────────────────────────────────────────────────────────
   가격 — 일반인 우선 (묘운 앱 무료), 개발자 호스팅은 작은 표
   ───────────────────────────────────────────────────────────── */

function Pricing({ lang }) {
  const t = (ko, en) => (lang === 'ko' ? ko : en);
  const tiers = [
    { tier: t('무료', 'Free'),     price: '₩0',     quota: t('월 1,000회', '1,000 / mo'),
      feats: [t('내 컴퓨터에서 무제한', 'Unlimited on your computer'), t('커뮤니티 지원', 'Community support')] },
    { tier: t('취미', 'Hobby'),    price: '₩9,900',  unit: t('/월', '/mo'), quota: t('월 1만회', '10K / mo'),
      feats: [t('호스팅 API 키', 'Hosted API key'), t('14일 자동 삭제', '14-day auto-purge')] },
    { tier: t('프로', 'Pro'),      price: '₩99,000',   unit: t('/월', '/mo'), quota: t('월 10만회', '100K / mo'), featured: true,
      feats: [t('우선 지원 · 99.5% SLA', 'Priority · 99.5% SLA'), t('맞춤 말투 조정', 'Custom voice tuning')] },
    { tier: t('비즈니스', 'Business'), price: '₩990,000',  unit: t('/월', '/mo'), quota: t('월 100만회', '1M / mo'),
      feats: [t('B2B 도입 컨설팅', 'B2B consulting'), t('사내망 설치 옵션', 'On-prem option')] },
  ];

  return (
    <div>
      <div className="pricing">
        {tiers.map(p => (
          <div key={p.tier} className={`price ${p.featured ? 'featured' : ''}`}>
            <div className="tier">
              {p.tier}
              {p.featured && <span className="badge">{t('인기', 'popular')}</span>}
            </div>
            <div className="pp">{p.price}{p.unit && <small>{p.unit}</small>}</div>
            <div className="quota">{p.quota}</div>
            <ul>{p.feats.map((f,i) => <li key={i}>{f}</li>)}</ul>
            <a className="price-cta" href="#">
              {p.featured || p.unit ? t('업그레이드', 'Upgrade') : t('지금 시작', 'Start free')} →
            </a>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────
   개발자 연동 — Smithery 1-click + 5 클라이언트 설치 가이드
   ───────────────────────────────────────────────────────────── */

const INSTALL_TABS = [
  { id: 'smithery',     label: 'Smithery',       sub: '1-click' },
  { id: 'claude-desk',  label: 'Claude Desktop', sub: 'JSON' },
  { id: 'cursor',       label: 'Cursor',         sub: '.cursor/mcp.json' },
  { id: 'claude-code',  label: 'Claude Code',    sub: 'CLI' },
  { id: 'codex',        label: 'Codex CLI',      sub: 'npx' },
];

function InstallTabs({ lang }) {
  const t = (ko, en) => (lang === 'ko' ? ko : en);
  const [tab, setTab] = useStateDI('smithery');
  const [copied, setCopied] = useStateDI('');

  const cfgs = {
    'claude-desk':
`{
  "mcpServers": {
    "saju": {
      "command": "npx",
      "args": ["-y", "@mildo/saju-mcp@latest"]
    }
  }
}`,
    'cursor':
`{
  "mcpServers": {
    "saju": {
      "command": "npx",
      "args": ["-y", "@mildo/saju-mcp@latest"],
      "env": { "SAJU_TZ": "Asia/Seoul" }
    }
  }
}`,
    'claude-code':
`# .claude/mcp.json
claude mcp add saju \\
  --command "npx -y @mildo/saju-mcp@latest" \\
  --env SAJU_TZ=Asia/Seoul`,
    'codex':
`# 전역 설치 후 등록
npm install -g @mildo/saju-mcp
codex mcp register saju --stdio "@mildo/saju-mcp"`,
  };

  const copy = (text) => {
    navigator.clipboard?.writeText(text);
    setCopied(tab);
    setTimeout(() => setCopied(''), 1400);
  };

  return (
    <div className="install-tabs">
      <div className="install-tabbar" role="tablist">
        {INSTALL_TABS.map(x => (
          <button key={x.id} className={tab === x.id ? 'on' : ''} onClick={() => setTab(x.id)}>
            {x.label}
            <span style={{display:'block', fontSize:10.5, opacity:.55, fontWeight:500, marginTop:2, fontFamily:'var(--font-mono)'}}>{x.sub}</span>
          </button>
        ))}
      </div>

      <div className="install-body">
        {tab === 'smithery' ? (
          <React.Fragment>
            <button className="smithery-cta" onClick={() => copy('https://smithery.ai/server/@mildo/saju-mcp')}>
              <div className="top">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3 7h7l-6 4 2 7-6-4-6 4 2-7-6-4h7z"/></svg>
                {t('SMITHERY 마켓플레이스 · 1-CLICK', 'SMITHERY MARKETPLACE · 1-CLICK')}
              </div>
              <div className="ttl">
                {t('Saju MCP 한 번에 설치', 'Install Saju MCP')}
                <span className="arr">→</span>
              </div>
              <div className="sub">smithery.ai/server/@mildo/saju-mcp</div>
            </button>
            <p className="hint" style={{margin:'8px 0 0'}}>
              {t('Smithery에서 사용 중인 클라이언트를 고르면 설정 파일이 자동 갱신됩니다.',
                 'Pick your client on Smithery and your config file is patched automatically.')}
            </p>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <p className="hint">
              {tab === 'claude-desk' && t(<React.Fragment>설정 파일에 추가: <code>~/Library/Application Support/Claude/claude_desktop_config.json</code></React.Fragment>,
                                          <React.Fragment>Add to <code>~/Library/Application Support/Claude/claude_desktop_config.json</code></React.Fragment>)}
              {tab === 'cursor' && t(<React.Fragment>프로젝트 루트에 <code>.cursor/mcp.json</code>으로 추가하거나 글로벌 설정에 넣습니다.</React.Fragment>,
                                     <React.Fragment>Drop into <code>.cursor/mcp.json</code> at repo root, or use global settings.</React.Fragment>)}
              {tab === 'claude-code' && t('명령줄 한 줄로 등록됩니다.', 'One CLI line registers the server globally.')}
              {tab === 'codex' && t('npm 전역 설치 + Codex CLI 등록.', 'Global npm install, then register with Codex CLI.')}
            </p>
            <div className="cli-block">
              <code>{cfgs[tab]}</code>
              <button className={`copy ${copied === tab ? 'ok' : ''}`} onClick={() => copy(cfgs[tab])}>
                {copied === tab ? '✓ ' + t('복사됨', 'copied') : t('복사', 'Copy')}
              </button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────
   가격 + 개발자 섹션 (페이지에서 분리해 사용)
   ───────────────────────────────────────────────────────────── */

function PricingSection({ lang }) {
  const t = (ko, en) => (lang === 'ko' ? ko : en);
  return (
    <section className="block" id="cta">
      <div className="container">
        <div className="section-eyebrow">
          <span className="hanja">無</span>
          {t('가격', 'Pricing')}
        </div>
        <h2 className="section-title">
          {t('일반 사용자는 무료. 그게 끝.', 'Free for everyday users. That’s it.')}
        </h2>
        <p className="section-sub">
          {t('묘운 앱은 광고 없이 무료입니다. 회사·서비스에 사주 풀이를 붙이실 때만 호스팅 요금이 듭니다.',
             'The Myoun app is free with no ads. You only pay if you plug Saju readings into your own product.')}
        </p>

        {/* 일반인 — 큰 묘운 앱 CTA 카드 */}
        <div className="myoun-card">
          <div>
            <div className="myoun-tag">{t('일반 사용자', 'Everyday user')}</div>
            <h3>{t('묘운 앱, 평생 무료.', 'The Myoun app — free, forever.')}</h3>
            <p>
              {t('매일 일진, 부부 합·충, 자녀 입시 운까지 — 같은 엔진을 휴대폰에서 바로. 광고 없음, 회원가입은 30초.',
                 'Daily fortune, couple compatibility, school-entry timing — same engine, in your pocket. No ads. 30-second sign-up.')}
            </p>
            <div className="myoun-meta">
              <span>★ 4.8 · 2,300+ {t('리뷰', 'reviews')}</span>
              <span>·</span>
              <span>{t('iOS · Android', 'iOS · Android')}</span>
            </div>
          </div>
          <div className="myoun-cta-col">
            <a className="btn btn-lg btn-amethyst" href="#">⌘ App Store</a>
            <a className="btn btn-lg btn-ghost" href="#">▶ Play Store</a>
            <a className="link-mini" href="#">{t('웹에서 미리보기 →', 'Try on web →')}</a>
          </div>
        </div>

        {/* 개발자/B2B — 작은 가격표 */}
        <div className="dev-pricing-wrap" id="dev-pricing">
          <div className="dev-pricing-head">
            <h4>{t('개발자 · B2B 호스팅 요금', 'Developer & B2B hosting')}</h4>
            <p>
              {t('자체 제품에 사주 풀이 API를 붙이는 경우에만 해당합니다. 개인 사용엔 필요 없습니다.',
                 'Only relevant if you’re wiring Saju readings into your own product. Personal use never needs this.')}
            </p>
          </div>
          <Pricing lang={lang} />
        </div>
      </div>
    </section>
  );
}

function DevSection({ lang }) {
  const t = (ko, en) => (lang === 'ko' ? ko : en);
  return (
    <section className="block dev-block" id="dev">
      <div className="container">
        <div className="dev-banner">
          <div className="dev-banner-tag">{t('개발자 전용', 'Developers only')}</div>
          <div className="dev-banner-copy">
            {t('일반 사용자라면 위의 묘운 앱이면 충분합니다. 아래는 사주 풀이를 자체 제품에 붙이실 분들을 위한 섹션입니다.',
               'Everyday users — the Myoun app above is all you need. This section is for plugging Saju into your own product.')}
          </div>
        </div>

        <div className="section-eyebrow">
          <span className="hanja">入</span>
          {t('개발자 연동', 'Developer integration')}
        </div>
        <h2 className="section-title">
          {t('5초 안에 Claude · Cursor · Codex에 붙이세요.', 'Plug into Claude, Cursor, Codex in 5 seconds.')}
        </h2>
        <p className="section-sub">
          {t('동일한 만세력 엔진을 stdio MCP 서버로 노출합니다. 로컬은 영구 무료, 호스팅 API는 첫 1,000회 무료.',
             'The same engine, exposed as an MCP stdio server. Local is free forever; hosted is free for the first 1,000 calls.')}
        </p>

        <div className="dev-grid">
          <InstallTabs lang={lang} />
          <div className="dev-side">
            <div className="dev-side-row">
              <span className="num">①</span>
              <div>
                <b>{t('Smithery 또는 JSON 설정', 'Smithery or JSON config')}</b>
                <p>{t('Smithery에서 클라이언트를 고르면 한 번에 끝납니다.', 'Smithery patches your client config automatically.')}</p>
              </div>
            </div>
            <div className="dev-side-row">
              <span className="num">②</span>
              <div>
                <b>{t('Claude · Cursor 재시작', 'Restart Claude / Cursor')}</b>
                <p>{t('재시작 후 도구 목록에 saju가 나타납니다.', 'After restart, "saju" shows up in your tools.')}</p>
              </div>
            </div>
            <div className="dev-side-row">
              <span className="num">③</span>
              <div>
                <b>{t('생년월일로 호출', 'Call with a birth date')}</b>
                <p>{t('"1992년 5월 25일 14시 30분 사주 봐줘" — 끝.', '"Read the Saju for May 25, 1992, 14:30" — done.')}</p>
              </div>
            </div>
            <div className="dev-side-note">
              <b>{t('영구 무료', 'Free, forever')}</b>
              {t(' — 로컬 stdio · Apache 2.0 라이선스. 사내망 운영도 가능.',
                 ' — local stdio · Apache 2.0. Self-host anywhere.')}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.PricingSection = PricingSection;
window.DevSection = DevSection;
