/* Page: AI Visibility — Google AI Overview presence + citation share. */
const { useState: useStateAIV } = React;

function AIVisibilityView({ client }) {
  const { data, loading, error } = useApi(`/api/clients/${client.id}/ai-visibility`, [client.id]);
  const [refreshing, setRefreshing] = useStateAIV(false);
  const [override, setOverride] = useStateAIV(null);

  if (loading) return <div className="loading-state">Loading AI visibility...</div>;
  if (error) return <div className="error-state">Failed to load AI visibility: {error}</div>;

  const d = override || data || {};
  const s = d.summary || {};
  const kws = d.keywords || [];
  const aioPct = s.aio_pct || 0;
  const lastCheckedDate = d.last_checked ? new Date(d.last_checked) : null;
  const lastChecked = lastCheckedDate ? lastCheckedDate.toLocaleDateString() : 'never';
  // AI Overview triggering shifts day-to-day; surface staleness so manual
  // Google checks against an old snapshot are interpreted as drift, not bugs.
  // Sync cadence is weekly (cost discipline while STLAF is on RNPL), so
  // "fresh" covers a full 7d cycle, "aging" flags a missed cycle, "stale"
  // flags two missed cycles.
  const ageDays = lastCheckedDate ? Math.floor((Date.now() - lastCheckedDate.getTime()) / 86400000) : null;
  const staleness = !lastCheckedDate ? 'none' : ageDays >= 14 ? 'stale' : ageDays >= 8 ? 'aging' : 'fresh';
  const staleColor = staleness === 'stale' ? 'var(--danger,#c0392b)' :
    staleness === 'aging' ? 'var(--gold)' : 'var(--text-dim)';
  const staleLabel = staleness === 'stale' ? `${ageDays}d old · refresh recommended` :
    staleness === 'aging' ? `${ageDays}d old` :
    staleness === 'fresh' ? (ageDays === 0 ? 'today' : `${ageDays}d ago`) : 'never';
  const maxCount = (s.most_cited_domains || []).reduce((m, x) => Math.max(m, x.count), 0) || 1;
  const barColor = (a) => a === 'big4' ? 'var(--accent)' : a === 'government' ? 'var(--text-muted)'
    : a === 'social' ? 'var(--text-dim)' : a === 'local' ? 'var(--gold-light)' : 'var(--gold)';

  async function doRefresh() {
    setRefreshing(true);
    try {
      const r = await fetch(`${window.API_BASE}/api/clients/${client.id}/ai-visibility/refresh`,
        { method: 'POST', headers: { Authorization: `Bearer ${window.__GE_API_KEY__ || ''}` } });
      if (r.ok) setOverride(await r.json());
    } finally { setRefreshing(false); }
  }

  return (
    <>
      <div className="page-head">
        <div>
          <div className="eyebrow gold"><span className="dot"/>AI Search · {kws.length} keywords tracked</div>
          <h1>AI Visibility</h1>
          <div className="sub">Where {client.name} appears in Google's AI Overviews, and who is being cited across your tracked keyword set.</div>
        </div>
        <div className="actions" style={{display:'flex',alignItems:'center',gap:10}}>
          <span className="mono" title={`Last checked ${lastChecked}`}
            style={{fontSize:11,color:staleColor,
              border:staleness === 'stale' ? `1px solid ${staleColor}` : 'none',
              borderRadius:4,padding:staleness === 'stale' ? '3px 8px' : 0,
              fontWeight:staleness === 'stale' ? 600 : 400}}>
            Last checked {lastChecked} · {staleLabel}
          </span>
          <button className="btn btn-secondary" onClick={doRefresh} disabled={refreshing}>
            <Icon name="refresh" size={13}/> {refreshing ? 'Refreshing...' : 'Refresh now'}
          </button>
        </div>
      </div>

      <div style={{display:'flex',gap:14,alignItems:'flex-start',background:'var(--gold-dim)',
        border:'1px solid var(--gold-dim2)',borderRadius:8,padding:'16px 20px',margin:'0 0 24px'}}>
        <span style={{fontFamily:'var(--font-mono)',fontSize:9,letterSpacing:'0.16em',textTransform:'uppercase',
          color:'var(--gold)',border:'1px solid var(--gold-dim2)',borderRadius:4,padding:'4px 8px',flexShrink:0}}>New</span>
        <p style={{lineHeight:1.65,margin:0}}>
          <strong>New: AI Overviews and Citations tracking.</strong> Google now shows an AI-generated
          answer box for <strong>{aioPct}% of your tracked keywords</strong>. That is the surface where
          future clients look first. Pages that earn these citations are still being published, so a low
          citation count now is the expected baseline. As pages go live, this panel shows them earning
          their place in AI answers.
        </p>
      </div>

      <div className="kpi-grid">
        <div className="kpi"><span className="label">{client.name} cited in AI Overviews</span>
          <span className="value" style={{color:'var(--gold)'}}>{s.client_cited_count || 0}</span>
          <span className="delta flat">of {s.opportunity_keywords || 0} addressable · grows with pages</span>
          <span className="source">{client.name} appears as a source</span></div>
        <div className="kpi"><span className="label">Opportunity keywords</span>
          <span className="value">{s.opportunity_keywords || 0}</span>
          <span className="delta flat">AIO present, citation slot open</span>
          <span className="source">addressable as pages publish</span></div>
        <div className="kpi"><span className="label">AI Overviews detected</span>
          <span className="value">{s.aio_detected || 0}</span>
          <span className="delta flat">of {s.aio_total || 0} tracked ({aioPct}%)</span>
          <span className="source">total AIO surface in tracked set</span></div>
        <div className="kpi"><span className="label">Avg organic rank</span>
          <span className="value">{s.avg_organic_rank == null ? '—' : s.avg_organic_rank}</span>
          <span className="delta flat">prerequisite for citation</span>
          <span className="source">{s.avg_organic_rank == null ? 'no top-100 positions yet' : 'across ranked keywords'}</span></div>
      </div>

      <div className="section-head"><span className="label">Citation share: who Google cites in your space</span><span className="rule"/></div>

      <div style={{display:'grid',gridTemplateColumns:'1.55fr 1fr',gap:16,alignItems:'start'}}>
        <div className="panel">
          <div className="panel-head"><h3 style={{fontSize:14}}>Tracked keywords</h3>
            <div className="right" style={{marginLeft:'auto',fontFamily:'var(--font-mono)',fontSize:10,color:'var(--text-dim)'}}>{kws.length} keywords</div></div>
          <table className="table">
            <thead><tr><th>Keyword</th><th>AI Overview</th><th>{client.name} cited</th><th className="num">Organic rank</th></tr></thead>
            <tbody>
              {kws.map((k, i) => (
                <tr key={i}>
                  <td>{k.keyword}</td>
                  <td><span className={`serp-badge ${k.aio_present ? 'gold' : ''}`}>{k.aio_present ? 'Present' : 'None'}</span></td>
                  <td><span className="serp-badge">{!k.aio_present ? '—' : (k.client_cited ? 'Yes' : 'No')}</span></td>
                  <td className="num mono">{k.organic_rank == null ? '—' : k.organic_rank}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="panel">
          <div className="panel-head"><h3 style={{fontSize:14}}>Most-cited domains</h3>
            <div className="right" style={{marginLeft:'auto',fontFamily:'var(--font-mono)',fontSize:10,color:'var(--text-dim)'}}>across {s.aio_detected || 0} AIO results</div></div>
          <div style={{padding:'8px 0'}}>
            {(s.most_cited_domains || []).map((dm, i) => (
              <div key={i} style={{display:'grid',gridTemplateColumns:'150px 1fr 30px',gap:12,alignItems:'center',padding:'9px 18px',borderBottom:'1px solid var(--border-light)'}}>
                <span className="mono" style={{fontSize:11,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{dm.domain}</span>
                <span style={{height:14,background:'var(--bg)',borderRadius:3,overflow:'hidden'}}>
                  <span style={{display:'block',height:'100%',width:`${Math.round((dm.count/maxCount)*100)}%`,borderRadius:3,background:barColor(dm.archetype)}}/>
                </span>
                <span className="mono" style={{fontSize:11,textAlign:'right'}}>{dm.count}</span>
              </div>
            ))}
            {(!s.most_cited_domains || s.most_cited_domains.length === 0) && (
              <div className="dim" style={{padding:'16px 18px',fontSize:12}}>No citations recorded yet. This fills in as pages publish and the next monthly check runs.</div>
            )}
          </div>
        </div>
      </div>

      {/* Strategic prompt audit — manual weekly capture per the SOP at
          _agency/operations/aeo-citation-mention-audit-sop-v1.0-2026-05-31.md.
          Renders an informative empty state until the first audit lands. */}
      <AEOAuditPanel client={client} />
      <AEOVisibilityPanel client={client} />
    </>
  );
}

window.AIVisibilityView = AIVisibilityView;
