/* easy-mode.jsx — 이지 모드
   초보자용 즉시 적용 GFA 광고 설정
   브랜드명 하나 → 타겟·키워드·설정 3단계 즉시 출력
*/
const { useState: useEMState } = React;

function EasyMode({ onGotoStandard }) {
  const [step, setStep] = useEMState('input');
  const [brand, setBrand] = useEMState('');
  const [result, setResult] = useEMState(null);
  const [pct, setPct] = useEMState(0);
  const [copied, setCopied] = useEMState(null);

  async function run() {
    if (!brand.trim()) return;
    setStep('loading');
    for (const p of [15, 35, 60, 85, 100]) {
      setPct(p);
      await new Promise(r => setTimeout(r, 380 + Math.random() * 280));
    }
    setResult(computeEasy(brand.trim()));
    setStep('result');
  }

  function computeEasy(name) {
    let personas = [], archetype = null;
    try {
      if (window.runBrandPipeline) {
        const pipe = window.runBrandPipeline({ name, category: '', keywords: '', description: '' });
        personas = pipe.personas || [];
        archetype = pipe.archetype || null;
      } else if (window.generatePersonas) {
        personas = window.generatePersonas({ brand: name, category: '', seed: null, keywords: '' }, window.TAXONOMY) || [];
      }
    } catch (e) {}

    const top = personas[0];
    if (!top) return { name, empty: true };

    const r = top.result || {};
    const leaves = top.query.flatMap(g => g.leaves).slice(0, 5);
    const kwSets = window.KeywordEngine?.generateKeywordSets([{ op: 'OR', leaves }]) || [];
    const keywords = [...new Set(kwSets.flatMap(s => s.keywords || []))].slice(0, 6);

    const ages = window.SimEngine?.AGES || [];
    const ageDist = r.ageDist || [];
    const topAgeIdx = ageDist.length ? ageDist.reduce((mi, v, i, a) => v > a[mi] ? i : mi, 0) : -1;
    const topAge = topAgeIdx >= 0 && ages[topAgeIdx] ? ages[topAgeIdx] : '30대';
    const gF = r.genderDist?.F || 0.5;
    const gender = gF > 0.6 ? '여성 중심' : gF < 0.4 ? '남성 중심' : '남녀 균형';
    const tierLabel = top.tier === 'intent' ? '구매 의도층' : '관심층';
    const topCats = top.query.flatMap(g => g.leaves).slice(0, 3).map(l => l.split(' > ').pop());

    return {
      name, archetype, personas,
      reach: r.finalReach || 0,
      ctr: r.ctr || 0,
      fitness: r.conversionFitness || 0,
      validity: r.validity || 0,
      topAge, gender, tierLabel, topCats, keywords,
      budgetEst: r.budget ? window.SimEngine?.fmtKRW(r.budget) : null,
    };
  }

  function copyText(text, key) {
    window.safeCopy?.(text);
    setCopied(key);
    setTimeout(() => setCopied(null), 1600);
  }

  return (
    <div className="em-shell">
      <div className="em-body">
        {step === 'input' && <EMInput brand={brand} setBrand={setBrand} onRun={run} />}
        {step === 'loading' && <EMLoading pct={pct} />}
        {step === 'result' && result && (
          <EMResult
            result={result}
            copied={copied}
            onCopy={copyText}
            onReset={() => { setStep('input'); setBrand(''); setResult(null); setPct(0); }}
            onUpgrade={onGotoStandard}
          />
        )}
      </div>
      <EMStyles />
    </div>
  );
}

/* ── Input ── */
function EMInput({ brand, setBrand, onRun }) {
  const examples = ['티블레스', '프리미엄 골프 용품', '건강기능식품', '여성 패션몰'];
  return (
    <div className="em-input-wrap">
      <div className="em-hero">
        <div className="em-hero-badge">이지 모드</div>
        <h1>광고할 브랜드나 제품이 무엇인가요?</h1>
        <p>브랜드명 하나만 입력하면 GFA 타겟·키워드·설정을 바로 알려드립니다.</p>
      </div>
      <div className="em-input-row">
        <input
          className="em-input"
          placeholder="예: 브랜드명, 제품 카테고리..."
          value={brand}
          onChange={e => setBrand(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && brand.trim() && onRun()}
          autoFocus
        />
        <button className="em-run-btn" onClick={onRun} disabled={!brand.trim()}>
          분석 시작 →
        </button>
      </div>
      <div className="em-examples">
        {examples.map(ex => (
          <button key={ex} className="em-ex-chip" onClick={() => setBrand(ex)}>{ex}</button>
        ))}
      </div>
      <div className="em-mode-hint">
        더 세밀한 분석이 필요하면
        <button className="em-inline-link" onClick={() => {}}>스탠다드 모드</button>를 이용하세요.
      </div>
    </div>
  );
}

/* ── Loading ── */
function EMLoading({ pct }) {
  const msg = pct < 35 ? '브랜드 카테고리 파악 중…' : pct < 70 ? '타겟 그룹 매칭 중…' : '광고 설정 생성 중…';
  return (
    <div className="em-loading">
      <div className="em-load-ring"></div>
      <div className="em-load-title">분석 중</div>
      <div className="em-load-bar"><div style={{ width: pct + '%' }} /></div>
      <div className="em-load-hint">{msg}</div>
    </div>
  );
}

/* ── Result ── */
function EMResult({ result, copied, onCopy, onReset, onUpgrade }) {
  if (result.empty) {
    return (
      <div className="em-result">
        <div className="em-empty">
          <p><strong>{result.name}</strong>과 매칭되는 카테고리를 찾지 못했습니다.</p>
          <p className="em-empty-hint">스탠다드 모드에서 카테고리를 직접 선택해 보세요.</p>
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <button className="em-reset" onClick={onReset}>↺ 다시 입력</button>
            <button className="em-upgrade-btn" onClick={onUpgrade}>스탠다드 모드로 →</button>
          </div>
        </div>
      </div>
    );
  }

  const { name, reach, ctr, fitness, validity, topAge, gender, tierLabel, topCats, keywords, archetype, budgetEst } = result;
  const SE = window.SimEngine;

  const steps = [
    {
      n: '01', title: '타겟 설정',
      body: `성별: ${gender.includes('여성') ? '여성 우선' : gender.includes('남성') ? '남성 우선' : '전체'} · 핵심 연령: ${topAge} · ${tierLabel} 집중`,
    },
    {
      n: '02', title: '관심사·구매의도 카테고리 선택',
      body: topCats.length ? topCats.join(', ') : '스탠다드 모드에서 확인',
    },
    {
      n: '03', title: '소재 방향',
      body: archetype
        ? `${archetype.label} 타입 → ${archetype.target || tierLabel} 대상, 차별 혜택 강조 소재`
        : `${tierLabel} 대상, 제품 혜택·차별점 강조`,
    },
  ];

  return (
    <div className="em-result">
      <div className="em-result-head">
        <div>
          <div className="em-result-label">분석 완료 · GFA 설정 준비됨</div>
          <h2 className="em-result-title">{name}</h2>
        </div>
        <button className="em-reset" onClick={onReset}>↺ 다시</button>
      </div>

      {/* KPI 4개 */}
      <div className="em-kpi-row">
        <div className="em-kpi">
          <div className="em-kpi-n">{SE?.fmtN(reach) || '—'}</div>
          <div className="em-kpi-l">예상 도달 (명)</div>
        </div>
        <div className="em-kpi">
          <div className="em-kpi-n">{ctr || '—'}%</div>
          <div className="em-kpi-l">예상 CTR</div>
        </div>
        <div className="em-kpi">
          <div className="em-kpi-n em-kpi-sm">{topAge}</div>
          <div className="em-kpi-l">핵심 연령대</div>
        </div>
        <div className="em-kpi">
          <div className="em-kpi-n em-kpi-sm">{gender}</div>
          <div className="em-kpi-l">성별 분포</div>
        </div>
      </div>

      {/* GFA 즉시 설정 3단계 */}
      <div className="em-section">
        <div className="em-section-title">GFA 광고 즉시 설정 — 3단계</div>
        <div className="em-steps">
          {steps.map(s => (
            <div key={s.n} className="em-step">
              <div className="em-step-n">{s.n}</div>
              <div>
                <div className="em-step-t">{s.title}</div>
                <div className="em-step-b">{s.body}</div>
              </div>
            </div>
          ))}
        </div>
        {budgetEst && (
          <div className="em-budget-hint">예상 월 예산: <strong>{budgetEst}</strong></div>
        )}
      </div>

      {/* 맞춤타겟 키워드 */}
      {keywords.length > 0 && (
        <div className="em-section">
          <div className="em-section-head">
            <div className="em-section-title">맞춤타겟 키워드 — 바로 복사해서 사용</div>
            <button className="em-copy-all" onClick={() => onCopy(keywords.join(', '), 'all')}>
              {copied === 'all' ? '✓ 복사됨' : '전체 복사'}
            </button>
          </div>
          <div className="em-kws">
            {keywords.map((kw, i) => (
              <button key={i} className={'em-kw' + (copied === kw ? ' copied' : '')}
                onClick={() => onCopy(kw, kw)}>
                {kw}
                <span className="em-kw-ico">{copied === kw ? '✓' : '📋'}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {/* 스탠다드 CTA */}
      <div className="em-upgrade-bar">
        <div>
          <strong>더 세밀한 분석이 필요하신가요?</strong>
          <span>스탠다드 모드에서 SA 매트릭스, 입찰 전략, 집행 계획까지 확인하세요.</span>
        </div>
        <button className="em-upgrade-btn" onClick={onUpgrade}>스탠다드로 →</button>
      </div>
    </div>
  );
}

/* ── Styles ── */
function EMStyles() {
  return <style>{`
    .em-shell { min-height: calc(100vh - 64px); display: flex; flex-direction: column; }
    .em-body {
      flex: 1; display: flex; flex-direction: column;
      align-items: center; justify-content: center;
      padding: 36px 24px;
    }

    /* Input */
    .em-input-wrap { width: 100%; max-width: 580px; }
    .em-hero { text-align: center; margin-bottom: 28px; }
    .em-hero-badge {
      display: inline-block;
      padding: 3px 10px; margin-bottom: 14px;
      background: oklch(0.68 0.21 22 / 0.2);
      color: oklch(0.78 0.18 22);
      font-size: 10px; font-weight: 700; letter-spacing: 0.08em;
    }
    .em-hero h1 {
      font-size: 26px; font-weight: 800; letter-spacing: -0.03em;
      margin: 0 0 10px; line-height: 1.35; color: var(--text);
    }
    .em-hero p { font-size: 14px; color: var(--text-dim); margin: 0; line-height: 1.6; }
    .em-input-row { display: flex; gap: 8px; }
    .em-input {
      flex: 1; background: oklch(0.10 0.015 240 / 0.7);
      border: 1px solid rgba(255,240,220,0.18);
      color: var(--text); padding: 13px 16px;
      font-size: 15px; font-family: var(--font-sans); outline: none;
    }
    .em-input:focus { border-color: var(--signal); }
    .em-run-btn {
      padding: 13px 22px; background: var(--signal);
      color: var(--ink-000); border: none; cursor: pointer;
      font-size: 14px; font-weight: 700; white-space: nowrap;
    }
    .em-run-btn:disabled { opacity: 0.35; cursor: not-allowed; }
    .em-run-btn:not(:disabled):hover { filter: brightness(1.12); }
    .em-examples { display: flex; gap: 7px; margin-top: 12px; flex-wrap: wrap; justify-content: center; }
    .em-ex-chip {
      padding: 5px 13px;
      background: oklch(0.13 0.015 240 / 0.5);
      border: 1px solid rgba(255,240,220,0.10);
      color: var(--text-dim); font-size: 12px; cursor: pointer;
    }
    .em-ex-chip:hover { border-color: var(--signal); color: var(--text); }
    .em-mode-hint { margin-top: 16px; text-align: center; font-size: 12px; color: var(--text-mute); }
    .em-inline-link {
      background: none; border: none; color: var(--signal);
      cursor: pointer; font-size: 12px; padding: 0 4px; text-decoration: underline;
    }

    /* Loading */
    .em-loading { text-align: center; width: 320px; }
    .em-load-ring {
      width: 36px; height: 36px; border: 2px solid rgba(255,240,220,0.1);
      border-top-color: var(--signal); border-radius: 50%;
      animation: em-spin 0.8s linear infinite; margin: 0 auto 16px;
    }
    @keyframes em-spin { to { transform: rotate(360deg); } }
    .em-load-title { font-size: 18px; font-weight: 700; color: var(--text); margin-bottom: 14px; }
    .em-load-bar { height: 3px; background: oklch(0.18 0.02 240); overflow: hidden; margin-bottom: 10px; }
    .em-load-bar > div { height: 100%; background: linear-gradient(90deg, var(--signal), var(--cyan)); transition: width 0.45s ease; }
    .em-load-hint { font-size: 12px; color: var(--text-mute); font-family: var(--font-mono); }

    /* Result */
    .em-result { width: 100%; max-width: 700px; display: flex; flex-direction: column; gap: 16px; }
    .em-result-head { display: flex; align-items: flex-start; justify-content: space-between; }
    .em-result-label { font-size: 10px; color: var(--text-mute); font-weight: 600; letter-spacing: 0.08em; }
    .em-result-title { font-size: 24px; font-weight: 800; margin: 4px 0 0; letter-spacing: -0.03em; color: var(--text); }
    .em-reset {
      background: transparent; border: 1px solid var(--border-strong);
      color: var(--text-dim); font-size: 12px; padding: 6px 11px; cursor: pointer; flex-shrink: 0;
    }
    .em-reset:hover { border-color: var(--text-dim); }

    /* KPI */
    .em-kpi-row { display: grid; grid-template-columns: repeat(4,1fr); gap: 10px; }
    .em-kpi {
      padding: 16px 12px; text-align: center;
      background: oklch(0.13 0.015 240 / 0.6);
      border: 1px solid rgba(255,240,220,0.08);
    }
    .em-kpi-n { font-size: 26px; font-weight: 800; letter-spacing: -0.03em; color: var(--signal); font-family: var(--font-mono); }
    .em-kpi-sm { font-size: 16px; }
    .em-kpi-l { font-size: 10px; color: var(--text-dim); margin-top: 4px; }

    /* Sections */
    .em-section { background: oklch(0.12 0.015 240 / 0.5); border: 1px solid rgba(255,240,220,0.07); padding: 16px; }
    .em-section-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
    .em-section-title { font-size: 11px; font-weight: 700; color: var(--text-dim); letter-spacing: 0.04em; margin-bottom: 12px; }
    .em-section-head .em-section-title { margin-bottom: 0; }

    /* Steps */
    .em-steps { display: flex; flex-direction: column; gap: 8px; }
    .em-step {
      display: flex; gap: 12px; align-items: flex-start;
      padding: 11px 13px; background: oklch(0.09 0.01 240 / 0.5);
    }
    .em-step-n { font-family: var(--font-mono); font-size: 11px; font-weight: 700; color: var(--signal); flex-shrink: 0; margin-top: 2px; }
    .em-step-t { font-size: 13px; font-weight: 700; color: var(--text); }
    .em-step-b { font-size: 12px; color: var(--text-dim); margin-top: 3px; line-height: 1.5; }
    .em-budget-hint { margin-top: 10px; font-size: 12px; color: var(--text-dim); font-family: var(--font-mono); padding-top: 10px; border-top: 1px dashed rgba(255,240,220,0.1); }
    .em-budget-hint strong { color: var(--signal); }

    /* Keywords */
    .em-kws { display: flex; flex-wrap: wrap; gap: 7px; }
    .em-kw {
      padding: 7px 13px; background: oklch(0.09 0.01 240 / 0.6);
      border: 1px solid rgba(255,240,220,0.10); color: var(--text-dim);
      font-size: 12px; cursor: pointer; display: flex; align-items: center; gap: 6px;
    }
    .em-kw:hover { border-color: var(--signal); color: var(--text); }
    .em-kw.copied { border-color: var(--plant); color: var(--plant); }
    .em-kw-ico { font-size: 10px; opacity: 0.5; }
    .em-copy-all {
      font-size: 11px; padding: 4px 11px;
      background: oklch(0.80 0.14 72 / 0.12); border: 1px solid var(--signal);
      color: var(--signal); cursor: pointer; white-space: nowrap;
    }
    .em-copy-all:hover { background: oklch(0.80 0.14 72 / 0.22); }

    /* Upgrade */
    .em-upgrade-bar {
      display: flex; align-items: center; justify-content: space-between; gap: 14px;
      padding: 16px 18px;
      background: linear-gradient(90deg, oklch(0.78 0.12 220 / 0.07), oklch(0.80 0.14 72 / 0.05));
      border: 1px solid rgba(120,200,240,0.16);
    }
    .em-upgrade-bar strong { display: block; font-size: 13px; font-weight: 700; color: var(--text); margin-bottom: 3px; }
    .em-upgrade-bar span { font-size: 11px; color: var(--text-dim); }
    .em-upgrade-btn {
      white-space: nowrap; padding: 9px 16px;
      background: var(--signal); color: var(--ink-000);
      border: none; cursor: pointer; font-size: 12px; font-weight: 700;
    }
    .em-upgrade-btn:hover { filter: brightness(1.1); }

    /* Empty */
    .em-empty { text-align: center; padding: 32px 16px; color: var(--text-dim); }
    .em-empty p { font-size: 14px; line-height: 1.6; margin: 6px 0; }
    .em-empty-hint { font-size: 12px; color: var(--text-mute); }

    @media (max-width: 600px) {
      .em-kpi-row { grid-template-columns: 1fr 1fr; }
      .em-input-row { flex-direction: column; }
      .em-upgrade-bar { flex-direction: column; align-items: flex-start; }
    }
  `}</style>;
}

Object.assign(window, { EasyMode });
