/* Funnel Lab — LP × LINE × CRM parts generation + test analysis */

function FunnelLabPage({ form, onBack }) {
  const [brief, setBrief] = React.useState({
    industry: '',
    productName: form?.name || '',
    target: form?.target || '',
    pain: '',
    benefit: '',
    price: '',
    offer: '',
    cta: 'LINEで無料診断を受け取る',
  });
  const [planState, setPlanState] = React.useState({ status: 'idle', error: '', plan: null });
  const [tests, setTests] = React.useState([
    { label: '悩み直撃型', impressions: 1000, clicks: 18, lineAdds: 4, conversions: 0 },
    { label: 'ベネフィット型', impressions: 1000, clicks: 24, lineAdds: 7, conversions: 1 },
    { label: '無料特典型', impressions: 1000, clicks: 20, lineAdds: 9, conversions: 1 },
  ]);
  const [analysisState, setAnalysisState] = React.useState({ status: 'idle', error: '', analysis: null });

  const updateBrief = (key, value) => setBrief((prev) => ({ ...prev, [key]: value }));
  const updateTest = (index, key, value) => {
    setTests((prev) => prev.map((row, i) => i === index ? { ...row, [key]: value } : row));
  };

  const generatePlan = async () => {
    setPlanState({ status: 'sending', error: '', plan: null });
    try {
      const res = await fetch('/api/funnel/generate', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ brief }),
      });
      const json = await res.json();
      if (!res.ok || !json.ok) throw new Error(json.error || '導線生成に失敗しました');
      setPlanState({ status: 'done', error: '', plan: json.plan });
    } catch (e) {
      setPlanState({ status: 'error', error: e.message || String(e), plan: null });
    }
  };

  const analyzeTests = async () => {
    setAnalysisState({ status: 'sending', error: '', analysis: null });
    try {
      const res = await fetch('/api/funnel/analyze', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ tests }),
      });
      const json = await res.json();
      if (!res.ok || !json.ok) throw new Error(json.error || '分析に失敗しました');
      setAnalysisState({ status: 'done', error: '', analysis: json.analysis });
    } catch (e) {
      setAnalysisState({ status: 'error', error: e.message || String(e), analysis: null });
    }
  };

  return (
    <main className="funnel-wrap fade-in">
      <div className="container">
        <div className="page-head">
          <div className="page-head__eyebrow">LP × LINE × CRM Funnel Lab</div>
          <h1 className="page-head__title">LP検証・導線改善ツール</h1>
          <p className="page-head__lede">
            完成LPを一発で当てにいくのではなく、複数の訴求・動的LP・LINE登録導線を作り、数字から改善案を出します。
          </p>
        </div>

        <div style={{ marginBottom: 18, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <button className="btn btn--ghost" onClick={onBack}>← バナー結果に戻る</button>
          <button className="btn btn--primary" onClick={generatePlan} disabled={planState.status === 'sending'}>
            {planState.status === 'sending' ? '生成中…' : '導線パーツを生成'}
          </button>
          <button className="btn btn--ghost" onClick={analyzeTests} disabled={analysisState.status === 'sending'}>
            {analysisState.status === 'sending' ? '分析中…' : 'テスト結果を分析'}
          </button>
        </div>

        <div className="funnel-grid">
          <section className="funnel-card">
            <h3>1. 生成する導線の入力</h3>
            <div className="funnel-form">
              <label>業種<input value={brief.industry} onChange={(e) => updateBrief('industry', e.target.value)} placeholder="例: 美容サロン / 学習塾 / B2B" /></label>
              <label>商品・サービス名<input value={brief.productName} onChange={(e) => updateBrief('productName', e.target.value)} /></label>
              <label>ターゲット<textarea value={brief.target} onChange={(e) => updateBrief('target', e.target.value)} placeholder="誰に売るか" /></label>
              <label>悩み<textarea value={brief.pain} onChange={(e) => updateBrief('pain', e.target.value)} placeholder="広告/LPで刺す痛み" /></label>
              <label>ベネフィット<textarea value={brief.benefit} onChange={(e) => updateBrief('benefit', e.target.value)} placeholder="得られる変化" /></label>
              <label>価格/条件<input value={brief.price} onChange={(e) => updateBrief('price', e.target.value)} placeholder="例: 月額9,800円 / 初回無料" /></label>
              <label>LINE登録特典<input value={brief.offer} onChange={(e) => updateBrief('offer', e.target.value)} placeholder="例: 無料診断シート" /></label>
              <label>CTA<input value={brief.cta} onChange={(e) => updateBrief('cta', e.target.value)} /></label>
            </div>
            {planState.error && <p className="funnel-error">{planState.error}</p>}
          </section>

          <section className="funnel-card">
            <h3>2. A/Bテスト入力</h3>
            <p className="dim-2">最初は手入力で検証。後で広告/LP計測と接続します。</p>
            <div className="test-table">
              <div className="test-row test-row--head"><span>案</span><span>表示</span><span>クリック</span><span>LINE</span><span>CV</span></div>
              {tests.map((row, index) => (
                <div className="test-row" key={index}>
                  <input value={row.label} onChange={(e) => updateTest(index, 'label', e.target.value)} />
                  <input type="number" value={row.impressions} onChange={(e) => updateTest(index, 'impressions', e.target.value)} />
                  <input type="number" value={row.clicks} onChange={(e) => updateTest(index, 'clicks', e.target.value)} />
                  <input type="number" value={row.lineAdds} onChange={(e) => updateTest(index, 'lineAdds', e.target.value)} />
                  <input type="number" value={row.conversions} onChange={(e) => updateTest(index, 'conversions', e.target.value)} />
                </div>
              ))}
            </div>
            {analysisState.error && <p className="funnel-error">{analysisState.error}</p>}
          </section>
        </div>

        <FunnelPlan plan={planState.plan} />
        <FunnelAnalysis analysis={analysisState.analysis} />
      </div>
    </main>
  );
}

function FunnelPlan({ plan }) {
  if (!plan) return null;
  const { parts } = plan;
  return (
    <section className="funnel-output">
      <h2>生成された導線パーツ</h2>
      <div className="funnel-output-grid">
        <div className="funnel-card">
          <h3>LP動的バリエーション</h3>
          {parts.lpVariants.map((lp) => (
            <div className="variant-card" key={lp.id}>
              <div className="variant-card__tag">{lp.name}</div>
              <strong>{lp.hero.headline}</strong>
              <p>{lp.hero.subhead}</p>
              <code>{lp.path}</code>
              <ul>{lp.sections.map((s) => <li key={s}>{s}</li>)}</ul>
            </div>
          ))}
        </div>
        <div className="funnel-card">
          <h3>LINE/CRM設計</h3>
          <h4>登録特典</h4>
          <p><strong>{parts.lineOffer.title}</strong><br />{parts.lineOffer.promise}</p>
          <h4>ステップ配信</h4>
          <ol>{parts.lineMessages.map((m) => <li key={m.day}>Day{m.day}: {m.title} — {m.body}</li>)}</ol>
          <h4>タグ</h4>
          <div className="tag-list">{parts.crm.tags.map((tag) => <span key={tag}>{tag}</span>)}</div>
        </div>
        <div className="funnel-card">
          <h3>動的LPルール</h3>
          <ul>{parts.dynamicRules.map((r) => <li key={r.if}><code>{r.if}</code> → {r.then}</li>)}</ul>
          <h3>広告コピー</h3>
          {parts.adCopy.map((ad) => <p key={ad.angle}><strong>{ad.headline}</strong><br />{ad.text}</p>)}
        </div>
      </div>
      {parts.inventory && <FunnelPartsInventory inventory={parts.inventory} />}
    </section>
  );
}

function FunnelPartsInventory({ inventory }) {
  return (
    <div className="funnel-card" style={{ marginTop: 18 }}>
      <h3>競合調査ベースのLPパーツ分解</h3>
      <p className="dim-2">LP単体ではなく、広告→LP→LINE→CRM→改善までを1キャンペーンとして分解します。</p>
      <div className="funnel-output-grid">
        <div>
          <h4>共通パーツ</h4>
          <ul>{inventory.common.map((item) => <li key={item.name}><strong>{item.name}</strong>: {item.role}</li>)}</ul>
        </div>
        <div>
          <h4>A/Bテスト対象</h4>
          <ul>{inventory.abTargets.map((item) => <li key={item}>{item}</li>)}</ul>
          <h4>動的出し分け</h4>
          <ul>{inventory.dynamicTargets.map((item) => <li key={item}>{item}</li>)}</ul>
        </div>
        <div>
          <h4>LINE/CRM接続</h4>
          <ul>{inventory.crmParts.map((item) => <li key={item}>{item}</li>)}</ul>
          <h4>業種別差分</h4>
          <ul>{inventory.industrySpecific.map((item) => <li key={item.key}><strong>{item.key}</strong>: {item.parts.join(' / ')}</li>)}</ul>
        </div>
      </div>
    </div>
  );
}

function fmtPct(value) {
  const n = Number(value || 0) * 100;
  return `${n.toFixed(n >= 10 ? 1 : 2)}%`;
}

function FunnelAnalysis({ analysis }) {
  if (!analysis) return null;
  return (
    <section className="funnel-output">
      <h2>テスト分析・改善提案</h2>
      {analysis.best && (
        <div className="funnel-card funnel-card--highlight">
          <h3>暫定勝ち案: {analysis.best.label}</h3>
          <p>CTR {fmtPct(analysis.best.ctr)} / LINE登録率 {fmtPct(analysis.best.lineRate)} / 登録後CVR {fmtPct(analysis.best.cvr)} / 総合CV率 {fmtPct(analysis.best.totalRate)}</p>
        </div>
      )}
      <div className="funnel-output-grid">
        <div className="funnel-card">
          <h3>数値</h3>
          {analysis.rows.map((row) => (
            <p key={row.id}><strong>{row.label}</strong>: CTR {fmtPct(row.ctr)} / LINE {fmtPct(row.lineRate)} / CVR {fmtPct(row.cvr)}</p>
          ))}
        </div>
        <div className="funnel-card">
          <h3>検出した課題</h3>
          <ul>{(analysis.insights || []).map((item) => <li key={item}>{item}</li>)}</ul>
        </div>
        <div className="funnel-card">
          <h3>次の提案</h3>
          <ol>{(analysis.recommendations || []).map((item) => <li key={item}>{item}</li>)}</ol>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { FunnelLabPage });
