function AnalyticsView({ onNavigate }) {
  const [loading, setLoading]   = useState(false);
  const [tips, setTips]         = useState([]);
  const [applied, setApplied]   = useState([]);
  const [selected, setSelected] = useState(null); // selected campaign for preview
  const [campaigns, setCampaigns] = useState([]);
  const [isLive, setIsLive]     = useState(false);
  const [fetchError, setFetchError] = useState(null);
  const [fetching, setFetching] = useState(false);

  // Auto-fetch from Meta API on mount if settings exist
  React.useEffect(() => {
    if (hasMetaKey()) {
      fetchLiveCampaigns();
    }
  }, []);

  const fetchLiveCampaigns = async () => {
    setFetching(true);
    setFetchError(null);
    try {
      const data = await fetchMetaCampaigns();
      if (data.length > 0) {
        setCampaigns(data);
        setIsLive(true);
      } else {
        setFetchError('เชื่อมต่อ Meta API สำเร็จ แต่ยังไม่มีแคมเปญที่ Active');
      }
    } catch (e) {
      setFetchError(e.message);
    }
    setFetching(false);
  };


  const hasData = campaigns.length > 0;
  const metaConfigured = hasMetaKey();

  const run = async () => {
    if (!hasData) return;
    setLoading(true);
    try {
      const data = await aiOptimize(campaigns);
      setTips(Array.isArray(data) ? data : OPTIMIZATIONS);
    } catch(e) { setTips(OPTIMIZATIONS); }
    setLoading(false);
  };

  const actionLabel = { change_creative:'เปลี่ยนครีเอทีฟ', pause:'หยุดชั่วคราว', adjust_budget:'ปรับงบ', modify_audience:'ปรับกลุ่ม' };

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:'var(--section-gap)' }} className="fade-up">

      {/* header */}
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', gap:16, flexWrap:'wrap' }}>
        <ViewHeader title="วิเคราะห์ผล & ปรับปรุง" en="Performance & Optimization"
          sub="ตารางแคมเปญจาก Meta Ads API — คลิกแถวเพื่อดูรายละเอียดและ AI แนะนำการปรับปรุง" />
        <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
          {metaConfigured && !fetching && (
            <button className="btn btn-ghost" onClick={fetchLiveCampaigns} style={{ fontSize:12 }}>
              <IconRefresh size={13} style={{ color:'var(--accent)' }} /> รีเฟรชข้อมูล n8n
            </button>
          )}
          {hasData && (
            <button className="btn btn-ghost" onClick={run} disabled={loading}>
              {loading ? <IconRefresh size={16} className="spin" style={{ color:'var(--accent)' }} /> : <IconRefresh size={16} style={{ color:'var(--accent)' }} />}
              ให้ AI ช่วยวิเคราะห์
            </button>
          )}
        </div>
      </div>

      {/* fetching state */}
      {fetching && (
        <div className="card fade-up" style={{ padding:'40px 32px', display:'flex', flexDirection:'column', alignItems:'center', textAlign:'center', gap:16 }}>
          <IconRefresh size={32} className="spin" style={{ color:'var(--accent)' }} />
          <div>
            <h3 style={{ margin:'0 0 6px', fontSize:17, fontWeight:700, color:'var(--ink)' }}>กำลังดึงข้อมูลแคมเปญจาก n8n Webhook…</h3>
            <p style={{ margin:0, fontSize:13, color:'var(--ink-2)' }}>กรุณารอสักครู่</p>
          </div>
        </div>
      )}

      {/* Error state */}
      {!fetching && fetchError && metaConfigured && (
        <div style={{ display:'flex', gap:12, padding:'14px 18px', borderRadius:'var(--radius-sm)', background:'var(--neg-soft)', border:'1px solid var(--neg)' }} className="fade-up">
          <IconWarn size={18} style={{ color:'var(--neg)', flexShrink:0, marginTop:2 }} />
          <div style={{ flex:1 }}>
            <div style={{ fontSize:13.5, fontWeight:700, color:'var(--neg)', marginBottom:3 }}>ไม่สามารถดึงข้อมูลแคมเปญได้</div>
            <div style={{ fontSize:12.5, color:'var(--neg)', lineHeight:1.55 }}>{fetchError}</div>
          </div>
        </div>
      )}

      {/* Live data banner */}
      {isLive && hasData && (
        <div style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 16px', borderRadius:'var(--radius-sm)', background:'var(--pos-soft)', border:'1px solid var(--pos)', fontSize:13, color:'var(--pos)', fontWeight:600 }}>
          <span style={{ width:8, height:8, borderRadius:99, background:'var(--pos)', boxShadow:'0 0 0 3px rgba(22,160,106,0.2)' }} />
          ข้อมูลแคมเปญจริงผ่าน n8n Webhook · {campaigns.length} แคมเปญ
        </div>
      )}

      {/* empty state */}
      {!fetching && !hasData && (
        <div className="card fade-up" style={{ padding:'clamp(32px,6vw,64px) 32px', display:'flex', flexDirection:'column', alignItems:'center', textAlign:'center', gap:20 }}>
          <div style={{ width:72, height:72, borderRadius:'50%', background:'var(--surface-3)', display:'grid', placeItems:'center' }}>
            <svg width="36" height="36" viewBox="0 0 40 40" fill="none">
              <rect width="40" height="40" rx="10" fill="var(--ink)" opacity="0.08"/>
              <circle cx="20" cy="20" r="9" stroke="var(--ink-3)" strokeWidth="1.8"/>
              <path d="M11 20h18M20 11c3.2 2.4 3.2 15.6 0 18M20 11c-3.2 2.4-3.2 15.6 0 18" stroke="var(--ink-3)" strokeWidth="1.5" opacity="0.8"/>
              <ellipse cx="20" cy="20" rx="14.5" ry="6.2" stroke="var(--accent)" strokeWidth="1.6" transform="rotate(-32 20 20)"/>
              <circle cx="31.2" cy="13.2" r="2.6" fill="var(--accent)" opacity="0.6"/>
            </svg>
          </div>
          <div>
            <h3 style={{ margin:'0 0 8px', fontSize:20, fontWeight:800, color:'var(--ink)', letterSpacing:'-0.01em' }}>ยังไม่มีข้อมูลแคมเปญ</h3>
            <p style={{ margin:0, fontSize:14, color:'var(--ink-2)', lineHeight:1.65, maxWidth:380 }}>
              เชื่อมต่อ n8n Webhook เพื่อดึงข้อมูล Campaigns, Ad Sets และ Ads จริงจาก Facebook Ads Manager มายังหน้านี้โดยอัตโนมัติ
            </p>
          </div>
          <div style={{ display:'flex', gap:8, flexWrap:'wrap', justifyContent:'center' }}>
            {['Campaigns', 'Ad Sets', 'Ads', 'Insights', 'ROAS', 'CTR', 'CPC'].map(t => (
              <span key={t} className="chip">{t}</span>
            ))}
          </div>
          <div style={{ display:'flex', gap:10, flexWrap:'wrap', justifyContent:'center' }}>
            <button className="btn btn-primary" onClick={() => onNavigate('settings')}>
              <IconNetwork size={16} /> ตั้งค่า n8n Webhook
            </button>
            <button className="btn btn-ghost" onClick={() => setCampaigns([
              { id:'1', name:'Promo_Video_V1', status:'ACTIVE', spend:4500, revenue:13500, roas:3.0, ctr:2.1, cpc:12, conversions:45, adSetId:'as_001', campaignId:'c_001' },
              { id:'2', name:'Lookalike_Image_Carousel', status:'ACTIVE', spend:2100, revenue:2520, roas:1.2, ctr:0.8, cpc:25, conversions:8, adSetId:'as_002', campaignId:'c_001' },
              { id:'3', name:'Retargeting_Offer', status:'ACTIVE', spend:850, revenue:3825, roas:4.5, ctr:3.5, cpc:8, conversions:12, adSetId:'as_003', campaignId:'c_002' },
              { id:'4', name:'Broad_Audience_Test', status:'ACTIVE', spend:3200, revenue:2880, roas:0.9, ctr:0.6, cpc:30, conversions:5, adSetId:'as_004', campaignId:'c_002' },
            ])}>
              <IconPlay size={15} /> ดูตัวอย่างข้อมูล
            </button>
          </div>
          <div style={{ padding:'16px 20px', borderRadius:'var(--radius-sm)', background:'var(--surface-2)', border:'1px solid var(--border)', maxWidth:480, width:'100%' }}>
            <div className="eyebrow" style={{ marginBottom:10 }}>API ENDPOINT PREVIEW</div>
            <div className="mono" style={{ fontSize:12, color:'var(--ink-2)', lineHeight:1.8, textAlign:'left' }}>
              <div>GET /v21.0/{'{'}ad_account_id{'}'}/campaigns</div>
              <div>GET /v21.0/{'{'}ad_account_id{'}'}/adsets</div>
              <div>GET /v21.0/{'{'}ad_account_id{'}'}/insights</div>
            </div>
          </div>
        </div>
      )}

      {/* AI recommendations */}
      {tips.length > 0 && !loading && hasData && (
        <div style={{ display:'flex', flexDirection:'column', gap:'var(--gap)' }} className="fade-up">
          <div className="eyebrow">OPTIMIZATION ENGINE · AI RECOMMENDATIONS</div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(300px, 1fr))', gap:'var(--gap)' }}>
            {tips.map((t, i) => {
              const done = applied.includes(t.adId);
              const isPos = t.actionType === 'adjust_budget';
              return (
                <div key={i} className="card" style={{ display:'flex', flexDirection:'column', borderColor: isPos ? 'var(--pos)' : 'var(--neg)' }}>
                  <div style={{ padding:'var(--pad-card)', flex:1 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10 }}>
                      <span style={{ color: isPos ? 'var(--pos)' : 'var(--neg)' }}>{isPos ? <IconTrend size={18} /> : <IconWarn size={18} />}</span>
                      <h4 style={{ margin:0, fontSize:13.5, fontWeight:700, color:'var(--ink)' }}>{t.adName}</h4>
                    </div>
                    <div className={`chip ${isPos ? 'chip-pos' : 'chip-neg'}`} style={{ marginBottom:10 }}>{t.issue}</div>
                    <p style={{ margin:0, fontSize:13, color:'var(--ink-2)', lineHeight:1.55 }}>{t.recommendation}</p>
                  </div>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'14px var(--pad-card)', borderTop:'1px solid var(--border)', background:'var(--surface-2)' }}>
                    <span className="eyebrow">{actionLabel[t.actionType]}</span>
                    <button className="btn" style={{ padding:'7px 12px', fontSize:12.5, background: done ? 'var(--pos-soft)' : 'var(--accent)', color: done ? 'var(--pos)' : '#fff' }}
                      onClick={() => setApplied(p => [...p, t.adId])} disabled={done}>
                      {done ? <><IconCheck size={14} /> ใช้แล้ว</> : <><IconBolt size={14} /> ใช้อัตโนมัติ</>}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* campaign table */}
      {hasData && (
        <div className="card">
          <div className="card-head">
            <h3 className="card-title">ตารางแคมเปญ
              <span className="eyebrow" style={{ marginLeft:6 }}>{campaigns.length} CAMPAIGNS</span>
            </h3>
            <span className="chip chip-accent">n8n Data · Live</span>
          </div>
          <div style={{ overflowX:'auto' }}>
            <table className="tbl">
              <thead><tr>
                <th>ชื่อแคมเปญ</th>
                <th>สถานะ</th>
                <th style={{ textAlign:'right' }}>Spend</th>
                <th style={{ textAlign:'right' }}>Revenue</th>
                <th style={{ textAlign:'right' }}>ROAS</th>
                <th style={{ textAlign:'right' }}>CTR</th>
                <th style={{ textAlign:'right' }}>Conv.</th>
                <th></th>
              </tr></thead>
              <tbody>
                {campaigns.map(ad => (
                  <tr key={ad.id} style={{ cursor:'pointer' }}
                    onClick={() => setSelected(ad)}
                    onMouseEnter={e => e.currentTarget.style.background='var(--accent-soft)'}
                    onMouseLeave={e => e.currentTarget.style.background=''}>
                    <td style={{ fontWeight:600, color:'var(--ink)' }}>{ad.name}</td>
                    <td>
                      <span className="chip chip-pos" style={{ gap:5 }}>
                        <span style={{ width:6, height:6, borderRadius:99, background:'var(--pos)', flexShrink:0 }} />
                        {ad.status || 'ACTIVE'}
                      </span>
                    </td>
                    <td className="mono" style={{ textAlign:'right' }}>฿{Number(ad.spend).toLocaleString()}</td>
                    <td className="mono" style={{ textAlign:'right', color:'var(--pos)', fontWeight:600 }}>฿{Number(ad.revenue).toLocaleString()}</td>
                    <td className="mono" style={{ textAlign:'right', fontWeight:700, color: ad.roas < 2 ? 'var(--neg)' : ad.roas >= 3.5 ? 'var(--pos)' : 'var(--accent-strong)' }}>{Number(ad.roas).toFixed(2)}x</td>
                    <td className="mono" style={{ textAlign:'right' }}>{ad.ctr}%</td>
                    <td className="mono" style={{ textAlign:'right' }}>{ad.conversions}</td>
                    <td>
                      <span style={{ display:'flex', alignItems:'center', gap:5, fontSize:12.5, fontWeight:600, color:'var(--accent-strong)', whiteSpace:'nowrap' }}>
                        ดูรายละเอียด <IconArrowRight size={14} />
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Preview panel */}
      {selected && (
        <CampaignPreview campaign={selected} onClose={() => setSelected(null)} tips={tips} />
      )}
    </div>
  );
}

/* ── Campaign Preview Panel ── */
