function ResearchView() {
  const [query, setQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [tab, setTab] = useState(0);
  const [validating, setValidating] = useState(false);
  const [validation, setValidation] = useState(null);
  const [sortAud, setSortAud] = useState({ col: 'efficiencyScore', dir: -1 });
  const [expandedAud, setExpandedAud] = useState(null);
  const [expandedAngle, setExpandedAngle] = useState(null);
  const [aiMode, setAiMode]   = useState(null); // 'live' | 'demo' | 'error'
  const [aiError, setAiError] = useState(null);

  const run = async () => {
    if (!query.trim() || loading) return;
    setLoading(true); setResult(null); setValidation(null); setTab(0); setAiError(null);
    try {
      const data = await aiResearch(query);
      setResult(data); setAiMode('live');
    } catch(e) {
      const mockData = getMockResearch(query);
      setResult(mockData);
      if (e.code === 'NO_KEY') { setAiMode('demo'); }
      else { setAiMode('error'); setAiError(e.message); }
    }
    setLoading(false);
  };

  const runValidate = async () => {
    if (validating || !result) return;
    setValidating(true); setTab(3);
    try {
      const data = await aiValidateResearch(result);
      setValidation(data);
    } catch(e) {
      const mockVal = getMockValidation(query, result);
      setValidation(mockVal);
    }
    setValidating(false);
  };

  const sortedAud = result ? [...result.targetAudiences].sort((a, b) => {
    const av = a[sortAud.col]; const bv = b[sortAud.col];
    return typeof av === 'number' ? (av - bv) * sortAud.dir : av.localeCompare(bv) * sortAud.dir;
  }) : [];

  const sortBy = (col) => setSortAud(s => ({ col, dir: s.col === col ? -s.dir : -1 }));
  const SortIcon = ({ col }) => sortAud.col === col
    ? <span className="mono" style={{ fontSize: 10, marginLeft: 3 }}>{sortAud.dir === -1 ? '↓' : '↑'}</span>
    : <span style={{ opacity: 0.25, marginLeft: 3, fontSize: 10 }}>↕</span>;

  const TABS = ['กลุ่มเป้าหมาย', 'มุมมองสื่อสาร', 'คู่แข่ง', 'ตรวจสอบ AI'];
  const TABS_EN = ['AUDIENCES', 'AD ANGLES', 'COMPETITORS', 'AI VALIDATOR'];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--section-gap)' }} className="fade-up">
      <ViewHeader title="วิเคราะห์สินค้า & กลุ่มเป้าหมาย" en="Audience Research"
        sub="พิมพ์อธิบายสินค้าเพื่อให้ AI ช่วยหากลุ่มเป้าหมาย มุมมองสื่อสาร คู่แข่ง และตรวจสอบความแม่นยำของผลวิเคราะห์" />

      {/* ── Search bar ── */}
      <div className="card" style={{ padding: 'var(--pad-card)' }}>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <div style={{ position: 'relative', flex: '1 1 280px' }}>
            <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-4)', pointerEvents: 'none' }}><IconSearch size={18} /></span>
            <input className="field" style={{ paddingLeft: 42 }} value={query}
              onChange={(e) => setQuery(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && run()}
              placeholder="เช่น: ครีมกันแดดเนื้อบางเบา ผิวแพ้ง่าย SPF50…" />
          </div>
          <button className="btn btn-primary" onClick={run} disabled={loading || !query.trim()}>
            {loading ? <IconRefresh size={17} className="spin" /> : <IconSpark size={17} />}
            {loading ? 'กำลังวิเคราะห์…' : 'วิเคราะห์ข้อมูล'}
          </button>
          {result && (
            <button className="btn btn-ghost" onClick={runValidate} disabled={validating} style={{ borderColor: validating ? 'var(--accent)' : undefined }}>
              {validating ? <IconRefresh size={16} className="spin" style={{ color: 'var(--accent)' }} /> : <IconCheckCircle size={16} style={{ color: 'var(--pos)' }} />}
              {validating ? 'กำลังตรวจสอบ…' : 'ตรวจสอบความแม่นยำ AI'}
            </button>
          )}
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap', alignItems: 'center' }}>
          <span className="eyebrow">ลองเลย :</span>
          {['ครีมกันแดดผิวแพ้ง่าย', 'อาหารเสริมคอลลาเจน', 'รองเท้าวิ่งน้ำหนักเบา', 'กาแฟสดส่งตรงบ้าน'].map(s => (
            <button key={s} className="chip" style={{ cursor: 'pointer' }} onClick={() => setQuery(s)}>{s}</button>
          ))}
        </div>
      </div>

      {loading && <SkeletonBlock rows={5} />}

      {result && !loading && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }} className="fade-up">

          {/* ── Result header row ── */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ width: 8, height: 8, borderRadius: 99, background: 'var(--pos)', boxShadow: '0 0 0 3px var(--pos-soft)', flexShrink: 0 }} />
              <span style={{ fontWeight: 700, color: 'var(--ink)', fontSize: 15 }}>ผลวิเคราะห์ <span style={{ color: 'var(--accent-strong)' }}>{result.productSector}</span></span>
              <span className="chip">Thailand</span>
              {aiMode === 'live' && <span className="chip chip-pos" style={{ gap:5, fontSize:11 }}><IconSpark size={11} /> Live AI</span>}
              {aiMode === 'demo' && <span className="chip chip-accent" style={{ gap:5, fontSize:11 }}><IconSpark size={11} /> Demo Mode</span>}
              {aiMode === 'error' && <span className="chip chip-neg" style={{ gap:5, fontSize:11 }}><IconWarn size={11} /> AI Error</span>}
              {validation && (
                <span className={`chip ${validation.verdict === 'ใช้ได้' ? 'chip-pos' : 'chip-neg'}`} style={{ gap: 5 }}>
                  <IconCheckCircle size={12} /> AI Validator: {validation.overallScore}/100
                </span>
              )}
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <span className="chip"><IconUsers size={13} /> {result.targetAudiences.length} กลุ่ม</span>
              <span className="chip"><IconSpark size={13} /> {result.angles.length} Angles</span>
              <span className="chip"><IconTarget size={13} /> {result.competitorInsights.length} คู่แข่ง</span>
            </div>
          </div>

          {/* ── Tabs ── */}
          <div style={{ display: 'flex', gap: 0, borderBottom: '1px solid var(--border)', overflowX: 'auto' }}>
            {TABS.map((t, i) => (
              <button key={i} onClick={() => setTab(i)} style={{
                padding: '10px 20px', fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: tab === i ? 700 : 500,
                color: tab === i ? 'var(--accent-strong)' : 'var(--ink-3)', background: 'transparent',
                border: 'none', cursor: 'pointer', borderBottom: tab === i ? '2.5px solid var(--accent)' : '2.5px solid transparent',
                whiteSpace: 'nowrap', transition: 'all .14s', display: 'flex', alignItems: 'center', gap: 7, flexShrink: 0,
              }}>
                {t}
                <span className="eyebrow" style={{ fontSize: 9, color: tab === i ? 'var(--accent)' : 'var(--ink-4)' }}>{TABS_EN[i]}</span>
                {i === 3 && validation && (
                  <span style={{ width: 7, height: 7, borderRadius: 99, background: validation.verdict === 'ใช้ได้' ? 'var(--pos)' : 'var(--neg)', flexShrink: 0 }} />
                )}
              </button>
            ))}
          </div>

          {/* ── Tab 0: กลุ่มเป้าหมาย ── */}
          {tab === 0 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {/* Summary bar */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 12 }}>
                {result.targetAudiences.map((a, i) => (
                  <div key={i} className="card" style={{ padding: '14px 18px', display: 'flex', gap: 12, alignItems: 'center', cursor: 'pointer', border: expandedAud === i ? '1px solid var(--accent)' : undefined, background: expandedAud === i ? 'var(--accent-soft)' : undefined }}
                    onClick={() => setExpandedAud(expandedAud === i ? null : i)}>
                    <div style={{ width: 36, height: 36, borderRadius: '50%', background: expandedAud === i ? 'var(--accent)' : 'var(--surface-3)', color: expandedAud === i ? '#fff' : 'var(--ink-2)', display: 'grid', placeItems: 'center', flexShrink: 0, fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 700 }}>
                      {i + 1}
                    </div>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink)', marginBottom: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.segment.split(' ')[0]}</div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <Meter value={a.efficiencyScore} w={48} />
                        <span className="mono" style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--pos)' }}>{a.efficiencyScore}%</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* Sortable table */}
              <div className="card" style={{ overflow: 'hidden' }}>
                <div className="card-head">
                  <h3 className="card-title"><IconUsers size={15} style={{ color: 'var(--accent)' }} /> รายการกลุ่มเป้าหมายทั้งหมด</h3>
                  <span className="eyebrow">คลิกชื่อคอลัมน์เพื่อเรียงลำดับ</span>
                </div>
                <div style={{ overflowX: 'auto' }}>
                  <table className="tbl">
                    <thead>
                      <tr>
                        <th style={{ cursor: 'pointer' }} onClick={() => sortBy('segment')}>กลุ่มเป้าหมาย <SortIcon col="segment" /></th>
                        <th style={{ cursor: 'pointer', textAlign: 'center' }} onClick={() => sortBy('efficiencyScore')}>Efficiency <SortIcon col="efficiencyScore" /></th>
                        <th style={{ cursor: 'pointer', textAlign: 'center' }} onClick={() => sortBy('searchTrend')}>เทรนด์ค้นหา <SortIcon col="searchTrend" /></th>
                        <th style={{ textAlign: 'center' }}>Est. CPC</th>
                        <th>ทำไมถึงดี</th>
                        <th></th>
                      </tr>
                    </thead>
                    <tbody>
                      {sortedAud.map((a, i) => {
                        const origIdx = result.targetAudiences.indexOf(a);
                        const isExp = expandedAud === origIdx;
                        return (
                          <React.Fragment key={i}>
                            <tr style={{ background: isExp ? 'var(--accent-soft)' : undefined }}>
                              <td>
                                <div style={{ fontWeight: 700, color: 'var(--ink)', fontSize: 13.5 }}>{a.segment}</div>
                                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{a.description.substring(0, 55)}…</div>
                              </td>
                              <td style={{ textAlign: 'center' }}>
                                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 }}>
                                  <Meter value={a.efficiencyScore} w={60} color={a.efficiencyScore >= 85 ? 'var(--pos)' : a.efficiencyScore >= 70 ? 'var(--accent)' : 'var(--ink-4)'} />
                                  <span className="mono" style={{ fontSize: 12.5, fontWeight: 700, color: a.efficiencyScore >= 85 ? 'var(--pos)' : 'var(--accent-strong)' }}>{a.efficiencyScore}%</span>
                                </div>
                              </td>
                              <td style={{ textAlign: 'center' }}>
                                <span style={{ color: 'var(--accent-strong)', fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 13 }}>
                                  <IconFlame size={13} />{a.searchTrend}
                                </span>
                              </td>
                              <td style={{ textAlign: 'center' }}>
                                <span className="chip">{a.estimatedCpc}</span>
                              </td>
                              <td style={{ color: 'var(--ink-2)', maxWidth: 280, whiteSpace: 'normal', fontSize: 12.5, lineHeight: 1.55 }}>{a.rationale}</td>
                              <td>
                                <button onClick={() => setExpandedAud(isExp ? null : origIdx)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 6, display: 'grid', placeItems: 'center', borderRadius: 6 }}>
                                  <IconChevron size={16} style={{ transform: isExp ? 'rotate(90deg)' : 'none', transition: 'transform .15s' }} />
                                </button>
                              </td>
                            </tr>
                            {isExp && (
                              <tr>
                                <td colSpan={6} style={{ background: 'var(--surface-2)', padding: '0' }}>
                                  <div style={{ padding: '14px 20px', borderTop: '1px solid var(--border)' }}>
                                    <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.65, marginBottom: 12 }}>{a.description}</div>
                                    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                                      <span className="chip chip-accent"><IconSpark size={12} /> เทรนด์ {a.searchTrend}</span>
                                      <span className="chip">CPC {a.estimatedCpc}</span>
                                      <span className="chip chip-pos">Efficiency {a.efficiencyScore}%</span>
                                    </div>
                                  </div>
                                </td>
                              </tr>
                            )}
                          </React.Fragment>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* ── Tab 1: มุมมองสื่อสาร ── */}
          {tab === 1 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div className="card" style={{ overflow: 'hidden' }}>
                <div className="card-head">
                  <h3 className="card-title"><IconSpark size={15} style={{ color: 'var(--accent)' }} /> Ad Angles ที่แนะนำ</h3>
                  <span className="eyebrow">{result.angles.length} ANGLES</span>
                </div>
                <div style={{ overflowX: 'auto' }}>
                  <table className="tbl">
                    <thead>
                      <tr>
                        <th>#</th><th>มุมมองการสื่อสาร</th><th style={{ textAlign: 'center' }}>Efficiency</th>
                        <th style={{ textAlign: 'center' }}>เทรนด์</th><th style={{ textAlign: 'center' }}>Est. CPA</th><th></th>
                      </tr>
                    </thead>
                    <tbody>
                      {result.angles.map((a, i) => {
                        const isExp = expandedAngle === i;
                        return (
                          <React.Fragment key={i}>
                            <tr style={{ background: isExp ? 'var(--accent-soft)' : undefined }}>
                              <td className="mono" style={{ color: 'var(--ink-4)', fontSize: 13, fontWeight: 600 }}>#{i + 1}</td>
                              <td>
                                <div style={{ fontWeight: 700, color: 'var(--ink)', fontSize: 13.5 }}>{a.title}</div>
                                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{a.description.substring(0, 60)}…</div>
                              </td>
                              <td style={{ textAlign: 'center' }}>
                                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                                  <Meter value={a.efficiencyScore} w={56} color="var(--pos)" />
                                  <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: 'var(--pos)' }}>{a.efficiencyScore}</span>
                                </div>
                              </td>
                              <td style={{ textAlign: 'center' }}>
                                <span style={{ color: 'var(--accent-strong)', fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 13 }}>
                                  <IconFlame size={13} />{a.searchTrend}
                                </span>
                              </td>
                              <td style={{ textAlign: 'center' }}><span className="chip">{a.estimatedCpa}</span></td>
                              <td>
                                <button onClick={() => setExpandedAngle(isExp ? null : i)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 6, borderRadius: 6, display: 'grid', placeItems: 'center' }}>
                                  <IconChevron size={16} style={{ transform: isExp ? 'rotate(90deg)' : 'none', transition: 'transform .15s' }} />
                                </button>
                              </td>
                            </tr>
                            {isExp && (
                              <tr>
                                <td colSpan={6} style={{ background: 'var(--surface-2)', padding: 0 }}>
                                  <div style={{ padding: '14px 20px', borderTop: '1px solid var(--border)', fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.65 }}>{a.description}</div>
                                </td>
                              </tr>
                            )}
                          </React.Fragment>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Angle ranking visual */}
              <div className="card">
                <div className="card-head"><h3 className="card-title">จัดอันดับ Efficiency Score</h3></div>
                <div style={{ padding: 'var(--pad-card)', display: 'flex', flexDirection: 'column', gap: 16 }}>
                  {[...result.angles].sort((a, b) => b.efficiencyScore - a.efficiencyScore).map((a, i) => (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                      <div className="mono" style={{ width: 22, fontSize: 11, color: 'var(--ink-4)', textAlign: 'center', flexShrink: 0 }}>#{i + 1}</div>
                      <div style={{ flex: 1, fontSize: 13, fontWeight: 600, color: 'var(--ink)', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.title}</div>
                      <div style={{ flex: 2, height: 22, background: 'var(--surface-3)', borderRadius: 6, overflow: 'hidden', flexShrink: 0 }}>
                        <div style={{ width: `${a.efficiencyScore}%`, height: '100%', background: i === 0 ? 'var(--pos)' : 'var(--accent)', borderRadius: 6, transition: 'width .6s cubic-bezier(.2,.7,.2,1)' }} />
                      </div>
                      <span className="mono" style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink)', flexShrink: 0, width: 36, textAlign: 'right' }}>{a.efficiencyScore}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* ── Tab 2: คู่แข่ง ── */}
          {tab === 2 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div className="card" style={{ overflow: 'hidden' }}>
                <div className="card-head">
                  <h3 className="card-title"><IconTarget size={15} style={{ color: 'var(--accent)' }} /> ภูมิทัศน์คู่แข่ง <span className="eyebrow" style={{ marginLeft: 4 }}>COMPETITIVE LANDSCAPE</span></h3>
                </div>
                <div style={{ overflowX: 'auto' }}>
                  <table className="tbl">
                    <thead>
                      <tr><th>กลยุทธ์คู่แข่ง</th><th>โอกาสของเรา</th><th style={{ textAlign: 'center' }}>Est. Spend/เดือน</th></tr>
                    </thead>
                    <tbody>
                      {result.competitorInsights.map((c, i) => (
                        <tr key={i}>
                          <td style={{ maxWidth: 260, whiteSpace: 'normal' }}>
                            <div style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 13, marginBottom: 4 }}>{c.strategy}</div>
                          </td>
                          <td style={{ maxWidth: 300, whiteSpace: 'normal' }}>
                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
                              <IconArrowUpRight size={15} style={{ color: 'var(--pos)', flexShrink: 0, marginTop: 1 }} />
                              <span style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55 }}>{c.opportunity}</span>
                            </div>
                          </td>
                          <td style={{ textAlign: 'center' }}>
                            <span className="chip chip-accent">{c.estimatedSpend}</span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Gap analysis cards */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 12 }}>
                {result.competitorInsights.map((c, i) => (
                  <div key={i} className="card" style={{ padding: 'var(--pad-card)' }}>
                    <div className="eyebrow" style={{ marginBottom: 10, display: 'flex', alignItems: 'center', gap: 5 }}>
                      <span style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--accent)', flexShrink: 0 }} />COMPETITOR {i + 1}
                    </div>
                    <p style={{ margin: '0 0 10px', fontSize: 13, color: 'var(--ink)', fontWeight: 600, lineHeight: 1.5 }}>{c.strategy}</p>
                    <div style={{ background: 'var(--pos-soft)', borderRadius: 'var(--radius-sm)', padding: '10px 12px', display: 'flex', gap: 8 }}>
                      <IconArrowUpRight size={16} style={{ color: 'var(--pos)', flexShrink: 0, marginTop: 1 }} />
                      <p style={{ margin: 0, fontSize: 12.5, color: 'var(--pos)', fontWeight: 600, lineHeight: 1.55 }}>{c.opportunity}</p>
                    </div>
                    <div className="eyebrow" style={{ display: 'flex', justifyContent: 'space-between', marginTop: 14 }}>
                      <span>EST. SPEND</span>
                      <span className="mono" style={{ color: 'var(--ink)' }}>{c.estimatedSpend}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* ── Tab 3: AI Validator ── */}
          {tab === 3 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {!validation && !validating && (
                <div className="card" style={{ padding: 'calc(var(--pad-card) * 1.6)', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 16 }}>
                  <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--surface-3)', color: 'var(--ink-2)', display: 'grid', placeItems: 'center' }}>
                    <IconCheckCircle size={26} />
                  </div>
                  <div>
                    <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)', marginBottom: 6 }}>ยังไม่ได้ตรวจสอบ</div>
                    <p style={{ margin: 0, fontSize: 13.5, color: 'var(--ink-2)', maxWidth: 380, lineHeight: 1.6 }}>
                      กด <b>"ตรวจสอบความแม่นยำ AI"</b> เพื่อให้ระบบตรวจสอบว่าผลวิเคราะห์ใช้ได้จริงใน Meta Ads หรือต้องปรับก่อน
                    </p>
                  </div>
                  <button className="btn btn-primary" onClick={runValidate}>
                    <IconCheckCircle size={17} /> เริ่มตรวจสอบทันที
                  </button>
                </div>
              )}
              {validating && <SkeletonBlock rows={6} label="AI กำลังตรวจสอบความแม่นยำ…" />}
              {validation && !validating && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }} className="fade-up">
                  {/* Overall score */}
                  <div className="card" style={{ padding: 'var(--pad-card)', display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap', background: validation.verdict === 'ใช้ได้' ? 'var(--pos-soft)' : 'var(--neg-soft)', borderColor: validation.verdict === 'ใช้ได้' ? 'var(--pos)' : 'var(--neg)' }}>
                    <div style={{ width: 76, height: 76, borderRadius: '50%', background: validation.verdict === 'ใช้ได้' ? 'var(--pos)' : 'var(--neg)', color: '#fff', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <div className="mono" style={{ fontSize: 24, fontWeight: 700, lineHeight: 1 }}>{validation.overallScore}</div>
                      <div style={{ fontSize: 9, fontWeight: 600, opacity: 0.85, letterSpacing: '0.06em' }}>/100</div>
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                        <IconCheckCircle size={17} style={{ color: validation.verdict === 'ใช้ได้' ? 'var(--pos)' : 'var(--neg)' }} />
                        <span style={{ fontSize: 16, fontWeight: 800, color: 'var(--ink)' }}>ผลตรวจสอบ: {validation.verdict}</span>
                      </div>
                      <p style={{ margin: 0, fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.65, maxWidth: 580 }}>{validation.summary}</p>
                    </div>
                  </div>

                  {/* Audience validation table */}
                  <div className="card" style={{ overflow: 'hidden' }}>
                    <div className="card-head">
                      <h3 className="card-title"><IconUsers size={15} style={{ color: 'var(--accent)' }} /> ตรวจสอบกลุ่มเป้าหมาย</h3>
                    </div>
                    <div style={{ overflowX: 'auto' }}>
                      <table className="tbl">
                        <thead>
                          <tr><th>กลุ่มเป้าหมาย</th><th style={{ textAlign: 'center' }}>ผลตรวจ</th><th style={{ textAlign: 'center' }}>Confidence</th><th>Interest ใน Meta</th><th>Audience Size</th><th>CPC</th></tr>
                        </thead>
                        <tbody>
                          {validation.audienceValidation.map((av, i) => (
                            <tr key={i}>
                              <td style={{ fontWeight: 700, color: 'var(--ink)' }}>{av.segment}</td>
                              <td style={{ textAlign: 'center' }}>
                                <span className={`chip ${av.verdict === 'pass' ? 'chip-pos' : 'chip-neg'}`} style={{ gap: 5 }}>
                                  {av.verdict === 'pass' ? <IconCheck size={12} /> : <IconWarn size={12} />}
                                  {av.verdict === 'pass' ? 'ใช้ได้' : 'ควรระวัง'}
                                </span>
                              </td>
                              <td style={{ textAlign: 'center' }}>
                                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                                  <Meter value={av.confidence} w={56} color={av.confidence >= 80 ? 'var(--pos)' : 'var(--accent)'} />
                                  <span className="mono" style={{ fontSize: 11.5, color: 'var(--ink-2)', fontWeight: 600 }}>{av.confidence}%</span>
                                </div>
                              </td>
                              {av.checks.map((ch, ci) => (
                                <td key={ci} style={{ maxWidth: 200, whiteSpace: 'normal' }}>
                                  <div style={{ display: 'flex', alignItems: 'flex-start', gap: 6 }}>
                                    <span style={{ flexShrink: 0, marginTop: 2 }}>{ch.pass ? <IconCheck size={13} style={{ color: 'var(--pos)' }} /> : <IconWarn size={13} style={{ color: 'var(--neg)' }} />}</span>
                                    <span style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>{ch.note}</span>
                                  </div>
                                </td>
                              ))}
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>

                  {/* Angle validation */}
                  <div className="card" style={{ overflow: 'hidden' }}>
                    <div className="card-head"><h3 className="card-title"><IconSpark size={15} style={{ color: 'var(--accent)' }} /> ตรวจสอบ Ad Angles</h3></div>
                    <div style={{ overflowX: 'auto' }}>
                      <table className="tbl">
                        <thead><tr><th>Ad Angle</th><th style={{ textAlign: 'center' }}>ผลตรวจ</th><th style={{ textAlign: 'center' }}>Confidence</th><th>หมายเหตุ AI</th></tr></thead>
                        <tbody>
                          {validation.angleValidation.map((av, i) => (
                            <tr key={i}>
                              <td style={{ fontWeight: 700, color: 'var(--ink)' }}>{av.title}</td>
                              <td style={{ textAlign: 'center' }}>
                                <span className={`chip ${av.verdict === 'pass' ? 'chip-pos' : 'chip-neg'}`} style={{ gap: 5 }}>
                                  {av.verdict === 'pass' ? <IconCheck size={12} /> : <IconWarn size={12} />}
                                  {av.verdict === 'pass' ? 'ดี' : 'ควรปรับ'}
                                </span>
                              </td>
                              <td style={{ textAlign: 'center' }}>
                                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                                  <Meter value={av.confidence} w={56} color={av.confidence >= 80 ? 'var(--pos)' : 'var(--accent)'} />
                                  <span className="mono" style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-2)' }}>{av.confidence}%</span>
                                </div>
                              </td>
                              <td style={{ maxWidth: 340, whiteSpace: 'normal', fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.55 }}>{av.note}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>

                  {/* Meta Ads Tips */}
                  <div className="card">
                    <div className="card-head"><h3 className="card-title"><IconBolt size={15} style={{ color: 'var(--accent)' }} /> คำแนะนำการตั้งค่า Meta Ads</h3></div>
                    <div style={{ padding: 'var(--pad-card)', display: 'flex', flexDirection: 'column', gap: 10 }}>
                      {validation.metaAdsTips.map((tip, i) => (
                        <div key={i} style={{ display: 'flex', gap: 12, padding: '12px 14px', background: 'var(--surface-2)', borderRadius: 'var(--radius-sm)', border: '1px solid var(--border)' }}>
                          <span className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', flexShrink: 0, marginTop: 1 }}>0{i + 1}</span>
                          <span style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.6 }}>{tip}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* ============================ CREATE AD ============================ */
// MOCK_CONTEXTS ถูกลบออกแล้ว — ใช้ aiGenContext(title) เท่านั้น
const MOCK_CONTEXTS = [];
