/* global React, useLang, IcoBrand, IcoWeb, IcoApp, IcoRocket, IcoChart, IcoChat, IcoSwatch, IcoFlag, Cloud, Star, Heart, Sparkle, Diamond, Flower */
/* solution-demos.jsx — 솔루션 마켓 데이터(24종) + 재사용 인터랙티브 데모 엔진 + 레지스트리
   원칙: 데모는 외부 유료 API 미호출. 컴포넌트 로컬 state + mockData 로만 동작. UI 텍스트 이모지 금지. */

const { useState, useEffect, useRef } = React;

/* ─────────────────────────────────────────────
   공용 헬퍼
   ───────────────────────────────────────────── */
function useKo() { const { lang } = useLang(); return lang === 'ko'; }

function SolAvatar({ name, photo, accent }) {
  const [err, setErr] = useState(false);
  const initial = (name || '?').trim().charAt(0).toUpperCase();
  if (photo && !err) {
    return <img src={photo} alt={name} onError={() => setErr(true)}
      style={{ width: '100%', height: '100%', objectFit: 'cover' }} />;
  }
  return (
    <div style={{
      width: '100%', height: '100%', display: 'grid', placeItems: 'center',
      background: `linear-gradient(135deg, ${accent}55, ${accent}22)`,
      color: '#fff', fontFamily: 'var(--f-display)', fontSize: '1.8em',
    }}>{initial}</div>
  );
}

function SolBar({ label, pct, accent }) {
  return (
    <div style={{ marginBottom: 8 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--t-body)', marginBottom: 3 }}>
        <span>{label}</span><span style={{ fontWeight: 700, color: accent }}>{pct}%</span>
      </div>
      <div style={{ height: 7, borderRadius: 5, background: 'rgba(0,0,0,0.07)', overflow: 'hidden' }}>
        <div style={{ width: `${pct}%`, height: '100%', borderRadius: 5, background: accent, transition: 'width 600ms cubic-bezier(.2,.7,.2,1)' }}></div>
      </div>
    </div>
  );
}

const ACCENTS = { lavender: '#6B5BA8', pink: '#C2517C', cyan: '#3E8C9C', yellow: '#B8902E' };
function accentOf(bg) { return ACCENTS[bg] || '#6B5BA8'; }

/* ─────────────────────────────────────────────
   엔진 1. brokerageMatch — 중개/매칭 공통 엔진 (12개 버티컬 재사용)
   listing 그리드 → 선택 → 적합도 점수 분해 → 연결/문의 → 매칭 성공 + 채팅 미리보기
   ───────────────────────────────────────────── */
function DemoBrokerage({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const [sel, setSel] = useState(0);
  const [connected, setConnected] = useState(false);
  const list = data.listings || [];
  const cur = list[sel] || null;
  const select = (i) => { setSel(i); setConnected(false); };

  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('일일 추천', 'Daily picks')} · {list.length}{pick('건', '')}</span>
        <span className="sol-demo-hint">{pick('카드를 눌러 매칭 근거를 확인하세요', 'Tap a card to see why it matched')}</span>
      </div>
      <div className="sol-broker-grid">
        {list.map((it, i) => (
          <button key={it.id} className={`sol-broker-card ${i === sel ? 'on' : ''}`}
            style={i === sel ? { borderColor: accent } : {}} onClick={() => select(i)}>
            <div className="sol-broker-photo">
              <SolAvatar name={it.name} photo={it.photo} accent={accent} />
              <span className="sol-broker-match" style={{ background: accent }}>{it.match}%</span>
            </div>
            <div className="sol-broker-name">{pick(it.name, it.nameEn || it.name)}</div>
            <div className="sol-broker-sub">{pick(it.sub, it.subEn || it.sub)}</div>
          </button>
        ))}
      </div>

      {cur && (
        <div className="sol-broker-detail" data-c={bg}>
          <div className="sol-broker-detail-top">
            <div className="sol-broker-detail-photo"><SolAvatar name={cur.name} photo={cur.photo} accent={accent} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="sol-broker-name" style={{ fontSize: 18 }}>{pick(cur.name, cur.nameEn || cur.name)}</div>
              <div className="sol-broker-sub" style={{ marginBottom: 6 }}>{pick(cur.sub, cur.subEn || cur.sub)}</div>
              <div className="sol-chips">
                {(cur.tags || []).map(tg => <span key={tg} className="sol-chip">{tg}</span>)}
              </div>
            </div>
            <div className="sol-broker-score" style={{ color: accent }}>
              <div className="sol-broker-score-n">{cur.match}</div>
              <div className="sol-broker-score-l">{pick('적합도', 'match')}</div>
            </div>
          </div>
          <div className="sol-broker-factors">
            <div className="sol-broker-factors-t">{pick('매칭 근거', 'Match factors')}</div>
            {(cur.factors || []).map((f, i) => (
              <SolBar key={i} label={pick(f.label, f.labelEn || f.label)} pct={f.pct} accent={accent} />
            ))}
          </div>
          {!connected ? (
            <button className="sol-cta-btn" style={{ background: accent }} onClick={() => setConnected(true)}>
              {pick(data.ctaLabel || '연결하기', data.ctaLabelEn || 'Connect')}
            </button>
          ) : (
            <div className="sol-broker-success" style={{ borderColor: accent }}>
              <div style={{ fontWeight: 800, color: accent, marginBottom: 6 }}>
                {pick(data.successLabel || '매칭 성공', data.successLabelEn || 'Matched')}
              </div>
              <div className="sol-broker-chat">
                <div className="sol-chat-bubble in">{pick(cur.firstMsg || '안녕하세요, 반가워요!', cur.firstMsgEn || 'Hi, nice to meet you!')}</div>
                <div className="sol-chat-bubble out">{pick('네, 잘 부탁드려요!', 'Likewise, looking forward to it!')}</div>
              </div>
              <div className="sol-demo-hint" style={{ marginTop: 6 }}>{pick('채팅방이 자동 생성되었습니다 (chatService createChatRoom)', 'A chat room was auto-created (chatService createChatRoom)')}</div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 2. tutorQuiz — AI 다국어 학습 튜터 (단어 퀴즈 3종 + API 응답)
   ───────────────────────────────────────────── */
function DemoTutorQuiz({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const words = data.words || [];
  const [idx, setIdx] = useState(0);
  const [picked, setPicked] = useState(null);
  const [score, setScore] = useState(0);
  const [showApi, setShowApi] = useState(false);
  const w = words[idx];
  if (!w) return null;
  const choose = (opt) => {
    if (picked) return;
    setPicked(opt);
    if (opt === w.answer) setScore(s => s + 1);
  };
  const next = () => { setPicked(null); setIdx(i => (i + 1) % words.length); };

  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('단어 퀴즈', 'Word quiz')} · {idx + 1}/{words.length}</span>
        <span className="sol-demo-hint">{pick('점수', 'Score')} {score}</span>
      </div>
      <div className="sol-quiz-q" data-c={bg}>
        <div className="sol-quiz-prompt">{pick(w.prompt, w.promptEn)}</div>
        <div className="sol-quiz-word">{w.word}{w.roman && <span className="sol-quiz-roman"> {w.roman}</span>}</div>
        <div className="sol-quiz-opts">
          {w.options.map(opt => {
            const isAns = opt === w.answer;
            const state = picked ? (isAns ? 'right' : (opt === picked ? 'wrong' : '')) : '';
            return (
              <button key={opt} className={`sol-quiz-opt ${state}`} onClick={() => choose(opt)}
                style={state === 'right' ? { borderColor: accent, color: accent } : {}}>{opt}</button>
            );
          })}
        </div>
        {picked && <button className="sol-cta-btn" style={{ background: accent }} onClick={next}>{pick('다음 문제', 'Next')}</button>}
      </div>
      <button className="sol-api-toggle" onClick={() => setShowApi(v => !v)}>
        {showApi ? pick('API 응답 숨기기', 'Hide API response') : pick('실제 API 응답 보기', 'View API response')}
      </button>
      {showApi && (
        <pre className="sol-api-pre">{`GET /api/cloud/v1/lingua/quiz?lang=${ko ? 'ko' : 'en'}&cefr=A1\n\n` + JSON.stringify(data.apiSample, null, 2)}</pre>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 3. rtcCall — WebRTC 통화 시그널링 상태머신 + ICE 조회
   ───────────────────────────────────────────── */
function DemoRtcCall({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const steps = ['idle', 'calling', 'ringing', 'connected', 'ended'];
  const labels = { idle: pick('대기', 'idle'), calling: pick('발신', 'calling'), ringing: pick('수신중', 'ringing'), connected: pick('연결됨', 'connected'), ended: pick('종료', 'ended') };
  const [si, setSi] = useState(0);
  const [showIce, setShowIce] = useState(false);
  const [mute, setMute] = useState(false);
  const [cam, setCam] = useState(true);
  const cur = steps[si];
  const advance = () => setSi(i => Math.min(i + 1, steps.length - 1));
  const reset = () => setSi(0);

  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('WebRTC 시그널링', 'WebRTC signaling')}</span>
        <span className="sol-demo-hint">{data.event || 'call:initiate → accept → ice-candidate'}</span>
      </div>
      <div className="sol-rtc-states">
        {steps.map((s, i) => (
          <div key={s} className={`sol-rtc-state ${i === si ? 'on' : ''} ${i < si ? 'done' : ''}`}
            style={i === si ? { borderColor: accent, color: accent } : {}}>
            <span className="sol-rtc-dot" style={i <= si ? { background: accent } : {}}></span>{labels[s]}
          </div>
        ))}
      </div>
      <div className="sol-rtc-stage" data-c={bg}>
        <div className="sol-rtc-tile" style={{ opacity: cam ? 1 : 0.35 }}>
          <SolAvatar name={data.peer || 'Mina'} photo={data.peerPhoto} accent={accent} />
          {cur === 'ringing' && <div className="sol-rtc-ring">{pick('수신 중...', 'Ringing...')}</div>}
          {!cam && <div className="sol-rtc-camoff">{pick('카메라 꺼짐', 'Camera off')}</div>}
        </div>
        <div className="sol-rtc-controls">
          <button className={`sol-rtc-ctrl ${mute ? 'off' : ''}`} onClick={() => setMute(m => !m)}>{mute ? pick('음소거', 'Muted') : pick('마이크', 'Mic')}</button>
          <button className={`sol-rtc-ctrl ${!cam ? 'off' : ''}`} onClick={() => setCam(c => !c)}>{cam ? pick('영상', 'Cam') : pick('영상끔', 'Cam off')}</button>
        </div>
      </div>
      <div className="sol-rtc-actions">
        {cur !== 'ended' ? <button className="sol-cta-btn" style={{ background: accent }} onClick={advance}>{pick('다음 단계', 'Next step')}</button>
          : <button className="sol-cta-btn ghost" onClick={reset}>{pick('다시 시작', 'Restart')}</button>}
        <button className="sol-api-toggle" onClick={() => setShowIce(v => !v)}>{showIce ? 'ICE −' : 'ICE config'}</button>
      </div>
      {showIce && <pre className="sol-api-pre">{`GET /api/cloud/v1/call/ice-config\n\n` + JSON.stringify(data.iceSample, null, 2)}</pre>}
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 4. pushPreview — 다국어 푸시 30언어 자동 미리보기 + 발송 시뮬
   ───────────────────────────────────────────── */
function DemoPush({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const [title, setTitle] = useState(data.defaultTitle || '새 메시지가 도착했어요');
  const [sent, setSent] = useState(false);
  const previews = data.previews || [];

  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('다국어 자동 변환', 'Auto multilingual')}</span>
        <span className="sol-demo-hint">{pick('30개 언어 title-pool 매핑', '30-language title pool')}</span>
      </div>
      <input className="sol-input" value={title} onChange={e => setTitle(e.target.value)}
        placeholder={pick('알림 제목 입력', 'Notification title')} />
      <div className="sol-push-grid">
        {previews.map(p => (
          <div key={p.code} className="sol-push-banner">
            <span className="sol-push-lang">{p.code.toUpperCase()}</span>
            <div className="sol-push-body">
              <div className="sol-push-title">{p.code === 'ko' ? title : p.label}</div>
              <div className="sol-push-text">{p.body}</div>
            </div>
          </div>
        ))}
      </div>
      <button className="sol-cta-btn" style={{ background: accent }} onClick={() => setSent(true)}>
        {pick('발송 (시뮬레이션)', 'Send (simulated)')}
      </button>
      {sent && <div className="sol-api-pre" style={{ color: accent }}>{`POST /api/cloud/v1/notify/send → 200\n{ "queued": ${previews.length}, "status": "sent", "rateLimiter": "ok" }`}</div>}
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 5. adAuction — 광고 송출 + CTR 실시간
   ───────────────────────────────────────────── */
function DemoAdAuction({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const [views, setViews] = useState(120);
  const [clicks, setClicks] = useState(7);
  const [budget, setBudget] = useState(data.budget || 50000);
  const cpc = data.cpc || 100;
  const ctr = views ? ((clicks / views) * 100).toFixed(1) : '0.0';
  const ad = data.creative || { title: '여름 신상 30% 할인', sub: 'OO브랜드' };
  const serve = () => setViews(v => v + 1);
  const click = () => { if (budget < cpc) return; setClicks(c => c + 1); setBudget(b => b - cpc); };

  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('슬롯 송출', 'Ad serving')} · home_top</span>
        <span className="sol-demo-hint">{pick('영국식 공개경매 · ATT 미사용', 'English auction · ATT-free')}</span>
      </div>
      <div className="sol-ad-banner" data-c={bg} onClick={click}>
        <div className="sol-ad-badge">AD</div>
        <div className="sol-ad-title">{ad.title}</div>
        <div className="sol-ad-sub">{ad.sub}</div>
        <div className="sol-demo-hint" style={{ marginTop: 4 }}>{pick('배너 클릭 → 클릭 이벤트', 'Click banner → click event')}</div>
      </div>
      <div className="sol-ad-stats">
        <div className="sol-ad-stat"><b>{views}</b><span>View</span></div>
        <div className="sol-ad-stat"><b>{clicks}</b><span>Click</span></div>
        <div className="sol-ad-stat" style={{ color: accent }}><b>{ctr}%</b><span>CTR</span></div>
        <div className="sol-ad-stat"><b>{budget.toLocaleString()}</b><span>{pick('잔여예산', 'Budget')}</span></div>
      </div>
      <button className="sol-cta-btn" style={{ background: accent }} onClick={serve}>{pick('노출 +1 (View)', 'Impression +1')}</button>
      <div className="sol-demo-hint" style={{ marginTop: 4 }}>{pick('CTR = 클릭 / View × 100, 클릭당 ' + cpc + '원 차감', 'CTR = clicks / views × 100')}</div>
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 6. liveChat — 실시간 채팅 위젯 + 상담 콘솔
   ───────────────────────────────────────────── */
function DemoLiveChat({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const [msgs, setMsgs] = useState(data.seed || [{ who: 'agent', text: ko ? '안녕하세요! 무엇을 도와드릴까요?' : 'Hi! How can I help?' }]);
  const [val, setVal] = useState('');
  const [status, setStatus] = useState('open');
  const endRef = useRef(null);
  useEffect(() => { if (endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; }, [msgs]);
  const send = () => {
    const text = val.trim(); if (!text) return;
    setVal('');
    setMsgs(m => [...m, { who: 'user', text }]);
    setStatus('pending');
    setTimeout(() => {
      setMsgs(m => [...m, { who: 'agent', text: (data.autoReply && data.autoReply[ko ? 'ko' : 'en']) || (ko ? '확인했습니다. 곧 처리해 드릴게요!' : 'Got it. We will handle it shortly!') }]);
      setStatus('open');
    }, 700);
  };
  return (
    <div className="sol-demo sol-chat-split">
      <div className="sol-chat-widget" data-c={bg}>
        <div className="sol-chat-bar" style={{ background: accent }}>{pick('고객 상담', 'Support chat')}</div>
        <div className="sol-chat-thread" ref={endRef}>
          {msgs.map((m, i) => <div key={i} className={`sol-chat-bubble ${m.who === 'user' ? 'out' : 'in'}`}>{m.text}</div>)}
        </div>
        <div className="sol-chat-input">
          <input className="sol-input" value={val} onChange={e => setVal(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && send()} placeholder={pick('메시지 입력', 'Type a message')} />
          <button className="sol-chat-send" style={{ background: accent }} onClick={send}>{pick('전송', 'Send')}</button>
        </div>
      </div>
      <div className="sol-chat-console">
        <div className="sol-demo-tag" style={{ color: accent }}>{pick('상담 콘솔', 'Agent console')}</div>
        <div className="sol-console-row"><span>{pick('상태', 'Status')}</span><b style={{ color: accent }}>{status}</b></div>
        <div className="sol-console-row"><span>{pick('미읽음', 'Unread')}</span><b>{msgs.filter(m => m.who === 'user').length}</b></div>
        <div className="sol-console-row"><span>{pick('룸 타입', 'Room')}</span><b>open</b></div>
        <div className="sol-demo-hint" style={{ marginTop: 8 }}>{pick('WebSocket /cloud-chat · direct/group/open', 'WebSocket /cloud-chat')}</div>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 7. anonBoard — 익명 커뮤니티
   ───────────────────────────────────────────── */
function DemoAnonBoard({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const [posts, setPosts] = useState(data.posts || []);
  const [val, setVal] = useState('');
  const vote = (i, d) => setPosts(ps => ps.map((p, j) => j === i ? { ...p, votes: p.votes + d } : p));
  const add = () => {
    const text = val.trim(); if (!text) return; setVal('');
    const alias = (data.aliases || ['익명의 다람쥐', '익명의 부엉이', '익명의 너구리'])[posts.length % 3];
    setPosts(ps => [{ alias, text, votes: 0 }, ...ps]);
  };
  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('익명 게시판', 'Anonymous board')}</span>
        <span className="sol-demo-hint">{pick('게시글별 HMAC 익명 매핑', 'Per-post HMAC alias')}</span>
      </div>
      <div className="sol-anon-write">
        <input className="sol-input" value={val} onChange={e => setVal(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && add()} placeholder={pick('익명으로 글쓰기', 'Post anonymously')} />
        <button className="sol-chat-send" style={{ background: accent }} onClick={add}>{pick('등록', 'Post')}</button>
      </div>
      <div className="sol-anon-list">
        {posts.map((p, i) => (
          <div key={i} className="sol-anon-post">
            <div className="sol-anon-meta"><b style={{ color: accent }}>{p.alias}</b></div>
            <div className="sol-anon-text">{p.text}</div>
            <div className="sol-anon-votes">
              <button onClick={() => vote(i, 1)}>▲</button>
              <span>{p.votes}</span>
              <button onClick={() => vote(i, -1)}>▼</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 8. oracleSbti — SBTI 성향 분석
   ───────────────────────────────────────────── */
function DemoOracle({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const qs = data.questions || [];
  const [ans, setAns] = useState({});
  const [result, setResult] = useState(null);
  const done = Object.keys(ans).length === qs.length && qs.length > 0;
  const analyze = () => {
    let score = 0; Object.values(ans).forEach(v => score += v);
    const r = data.results[score >= qs.length ? 1 : 0] || data.results[0];
    setResult(r);
  };
  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('SBTI 성향 분석', 'SBTI typing')}</span>
        <span className="sol-demo-hint">{pick('27타입 × 30언어 정적 데이터', '27 types × 30 languages')}</span>
      </div>
      {!result ? (
        <div>
          {qs.map((q, i) => (
            <div key={i} className="sol-oracle-q">
              <div className="sol-oracle-qt">{pick(q.q, q.qEn)}</div>
              <div className="sol-oracle-opts">
                <button className={`sol-quiz-opt ${ans[i] === 0 ? 'on' : ''}`} style={ans[i] === 0 ? { borderColor: accent, color: accent } : {}} onClick={() => setAns(a => ({ ...a, [i]: 0 }))}>{pick(q.a, q.aEn)}</button>
                <button className={`sol-quiz-opt ${ans[i] === 1 ? 'on' : ''}`} style={ans[i] === 1 ? { borderColor: accent, color: accent } : {}} onClick={() => setAns(a => ({ ...a, [i]: 1 }))}>{pick(q.b, q.bEn)}</button>
              </div>
            </div>
          ))}
          <button className="sol-cta-btn" style={{ background: accent, opacity: done ? 1 : 0.5 }} disabled={!done} onClick={analyze}>{pick('분석하기', 'Analyze')}</button>
        </div>
      ) : (
        <div className="sol-oracle-result" data-c={bg}>
          <div className="sol-oracle-animal">{pick(result.name, result.nameEn)}</div>
          <div className="sol-oracle-desc">{pick(result.desc, result.descEn)}</div>
          <button className="sol-cta-btn ghost" onClick={() => { setResult(null); setAns({}); }}>{pick('다시 하기', 'Retry')}</button>
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 9. meetingStt — AI 회의록 STT 요약
   ───────────────────────────────────────────── */
function DemoMeeting({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const [stage, setStage] = useState(0); // 0 녹음전 1 처리중 2 결과
  useEffect(() => {
    if (stage === 1) { const t = setTimeout(() => setStage(2), 1400); return () => clearTimeout(t); }
  }, [stage]);
  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('AI 회의록', 'AI meeting notes')}</span>
        <span className="sol-demo-hint">{pick('Whisper STT + 화자분리 + 요약', 'Whisper STT + diarization + summary')}</span>
      </div>
      {stage === 0 && <button className="sol-cta-btn" style={{ background: accent }} onClick={() => setStage(1)}>{pick('샘플 회의 오디오 처리', 'Process sample audio')}</button>}
      {stage === 1 && <div className="sol-meeting-load" style={{ color: accent }}>{pick('음성 인식 → 화자 분리 → 요약 중...', 'Transcribing → diarizing → summarizing...')}</div>}
      {stage === 2 && (
        <div className="sol-meeting-result">
          <div className="sol-meeting-block"><b style={{ color: accent }}>{pick('요약', 'Summary')}</b><p>{pick(data.summary, data.summaryEn)}</p></div>
          <div className="sol-meeting-block"><b style={{ color: accent }}>{pick('화자 분리', 'Speakers')}</b>
            {(data.speakers || []).map((s, i) => <div key={i} className="sol-meeting-line"><span className="sol-meeting-spk" style={{ background: accent }}>{s.spk}</span> {pick(s.text, s.textEn)}</div>)}
          </div>
          <div className="sol-meeting-block"><b style={{ color: accent }}>{pick('액션 아이템', 'Action items')}</b>
            <ul>{(data.actions || []).map((a, i) => <li key={i}>{pick(a, data.actionsEn ? data.actionsEn[i] : a)}</li>)}</ul>
          </div>
          <button className="sol-cta-btn ghost" onClick={() => setStage(0)}>{pick('다시', 'Reset')}</button>
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 10. gamify — 게이미피케이션 (XP/레벨/미션)
   ───────────────────────────────────────────── */
function DemoGamify({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const [xp, setXp] = useState(320);
  const [missions, setMissions] = useState(data.missions || []);
  const per = 500; const level = Math.floor(xp / per) + 1; const pct = Math.round((xp % per) / per * 100);
  const complete = (i) => setMissions(ms => ms.map((m, j) => {
    if (j === i && !m.done) { setXp(x => x + m.xp); return { ...m, done: true }; } return m;
  }));
  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('게이미피케이션', 'Gamification')}</span>
        <span className="sol-demo-hint">Lv {level} · {xp} XP</span>
      </div>
      <div className="sol-gamify-level" data-c={bg}>
        <div className="sol-gamify-ring" style={{ borderColor: accent, color: accent }}>{level}</div>
        <div style={{ flex: 1 }}>
          <SolBar label={pick('레벨 진행도', 'Level progress')} pct={pct} accent={accent} />
          <div className="sol-demo-hint">{pick('XP 23종 소스 · 일일 캡', '23 XP sources · daily cap')}</div>
        </div>
      </div>
      <div className="sol-gamify-missions">
        {missions.map((m, i) => (
          <button key={i} className={`sol-mission ${m.done ? 'done' : ''}`} onClick={() => complete(i)} disabled={m.done}>
            <span className="sol-mission-check" style={m.done ? { background: accent, borderColor: accent } : {}}>{m.done ? '✓' : ''}</span>
            <span className="sol-mission-t">{pick(m.t, m.tEn)}</span>
            <span className="sol-mission-xp" style={{ color: accent }}>+{m.xp}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 11. walkTrack — 위치기반 산책/운동 트래킹
   ───────────────────────────────────────────── */
function DemoWalk({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const [run, setRun] = useState(false);
  const [sec, setSec] = useState(0);
  useEffect(() => {
    if (!run) return; const id = setInterval(() => setSec(s => s + 1), 1000); return () => clearInterval(id);
  }, [run]);
  const dist = (sec * 1.4 / 1000).toFixed(2); const kcal = Math.round(sec * 1.4 * 0.06); const steps = sec * 2;
  const mm = String(Math.floor(sec / 60)).padStart(2, '0'); const ss = String(sec % 60).padStart(2, '0');
  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('산책 트래킹', 'Walk tracking')}</span>
        <span className="sol-demo-hint">{pick('BG GPS 5m/1s · Live Activity', 'BG GPS · Live Activity')}</span>
      </div>
      <div className="sol-walk-map" data-c={bg}>
        <svg viewBox="0 0 200 90" style={{ width: '100%', height: 90 }}>
          <path d="M10 70 Q50 20 90 50 T180 30" fill="none" stroke={accent} strokeWidth="3" strokeDasharray="4 4"
            style={{ strokeDashoffset: run ? -sec * 4 : 0, transition: 'stroke-dashoffset 1s linear' }} />
          <circle cx={10 + Math.min(sec * 3, 170)} cy={run ? 50 : 70} r="5" fill={accent} />
        </svg>
      </div>
      <div className="sol-walk-stats">
        <div className="sol-ad-stat" style={{ color: accent }}><b>{mm}:{ss}</b><span>{pick('시간', 'Time')}</span></div>
        <div className="sol-ad-stat"><b>{dist}km</b><span>{pick('거리', 'Dist')}</span></div>
        <div className="sol-ad-stat"><b>{steps}</b><span>{pick('걸음', 'Steps')}</span></div>
        <div className="sol-ad-stat"><b>{kcal}</b><span>kcal</span></div>
      </div>
      <button className="sol-cta-btn" style={{ background: accent }} onClick={() => setRun(r => !r)}>{run ? pick('일시정지', 'Pause') : pick('산책 시작', 'Start walk')}</button>
    </div>
  );
}

/* ─────────────────────────────────────────────
   엔진 12. commerce — 커머스 장바구니
   ───────────────────────────────────────────── */
function DemoCommerce({ data, bg }) {
  const ko = useKo(); const pick = (k, e) => ko ? k : e;
  const accent = accentOf(bg);
  const products = data.products || [];
  const [cart, setCart] = useState({});
  const add = (id) => setCart(c => ({ ...c, [id]: (c[id] || 0) + 1 }));
  const total = products.reduce((sum, p) => sum + (cart[p.id] || 0) * p.price, 0);
  const count = Object.values(cart).reduce((a, b) => a + b, 0);
  return (
    <div className="sol-demo">
      <div className="sol-demo-head">
        <span className="sol-demo-tag" style={{ color: accent }}>{pick('쇼핑몰', 'Storefront')}</span>
        <span className="sol-demo-hint">{pick('장바구니', 'Cart')} {count} · {total.toLocaleString()}{pick('원', '')}</span>
      </div>
      <div className="sol-shop-grid">
        {products.map(p => (
          <div key={p.id} className="sol-shop-card" data-c={bg}>
            <div className="sol-shop-thumb" style={{ background: `linear-gradient(135deg, ${accent}33, ${accent}11)` }}>
              <SolAvatar name={p.name} photo={p.photo} accent={accent} />
            </div>
            <div className="sol-shop-name">{pick(p.name, p.nameEn || p.name)}</div>
            <div className="sol-shop-price" style={{ color: accent }}>{p.price.toLocaleString()}{pick('원', '')}</div>
            <button className="sol-shop-add" style={{ borderColor: accent, color: accent }} onClick={() => add(p.id)}>{pick('담기', 'Add')}{cart[p.id] ? ` (${cart[p.id]})` : ''}</button>
          </div>
        ))}
      </div>
      {count > 0 && <div className="sol-cta-btn" style={{ background: accent, textAlign: 'center' }}>{pick('결제하기', 'Checkout')} · {total.toLocaleString()}{pick('원', '')}</div>}
    </div>
  );
}

/* 데모 레지스트리 */
const SOLUTION_DEMOS = {
  brokerageMatch: DemoBrokerage,
  tutorQuiz: DemoTutorQuiz,
  rtcCall: DemoRtcCall,
  pushPreview: DemoPush,
  adAuction: DemoAdAuction,
  liveChat: DemoLiveChat,
  anonBoard: DemoAnonBoard,
  oracleSbti: DemoOracle,
  meetingStt: DemoMeeting,
  gamify: DemoGamify,
  walkTrack: DemoWalk,
  commerce: DemoCommerce,
};

Object.assign(window, { SOLUTION_DEMOS });
