/* Panel: AEO Audit — manual weekly citation + mention audit per the SOP.
   Renders inside AIVisibilityView, below the auto-pulled keyword section.
   Pairs the two lenses on one page:
     - Top of page: where do AIOs appear on our tracked rank keywords (auto)
     - Bottom of page (this panel): are we cited / mentioned on 15 audit
       prompts we strategically picked (manual capture per the SOP). */

function AEOAuditPanel({ client }) {
  const { data, loading, error } = useApi(`/api/clients/${client.id}/aeo-audit`, [client.id]);

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

  const d = data || {};
  const s = d.summary || {};
  const latest = d.latest || null;
  const history = d.history || [];
  const auditCount = d.audit_count || 0;
  const lastAuditDate = d.last_audit_date ? new Date(d.last_audit_date) : null;
  const lastAuditLabel = lastAuditDate ? lastAuditDate.toLocaleDateString() : 'never';
  const ageDays = lastAuditDate ? Math.floor((Date.now() - lastAuditDate.getTime()) / 86400000) : null;
  // Weekly cadence per SOP: "fresh" covers 7d, "aging" 8-13d, "stale" 14d+.
  const staleness = !lastAuditDate ? '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 · audit overdue` :
    staleness === 'aging' ? `${ageDays}d old` :
    staleness === 'fresh' ? (ageDays === 0 ? 'today' : `${ageDays}d ago`) : 'never';

  const deltaText = (n) => n == null ? 'first week of tracking' :
    n === 0 ? 'flat vs last week' :
    n > 0 ? `+${n} vs last week` : `${n} vs last week`;
  const deltaClass = (n) => n == null ? 'flat' : n > 0 ? 'up' : n < 0 ? 'down' : 'flat';

  // Empty state — no audits yet.
  if (auditCount === 0) {
    return (
      <>
        <div className="section-head">
          <span className="label">Strategic prompt audit · weekly manual capture</span>
          <span className="rule"/>
        </div>
        <div style={{display:'flex',gap:14,alignItems:'flex-start',background:'var(--bg)',
          border:'1px dashed var(--border-light)',borderRadius:8,padding:'20px 22px',margin:'0 0 24px'}}>
          <span style={{fontFamily:'var(--font-mono)',fontSize:9,letterSpacing:'0.16em',textTransform:'uppercase',
            color:'var(--text-dim)',border:'1px solid var(--border-light)',borderRadius:4,padding:'4px 8px',flexShrink:0}}>Pending</span>
          <div style={{lineHeight:1.65}}>
            <p style={{margin:'0 0 8px'}}>
              <strong>Baseline AEO audit pending.</strong> Once the first weekly audit runs,
              this panel shows two numbers — <strong>citations earned</strong> (AI Mode sidebar
              source links) and <strong>mentions earned</strong> (brand named inside the AI's
              answer body) — across 15 strategic prompts chosen for {client.name} at onboarding.
            </p>
            <p style={{margin:0,fontSize:13,color:'var(--text-dim)'}}>
              Citations come from structural retrievability. Mentions come from market consensus
              across Reddit, LinkedIn, YouTube, PR, named-expert quotes. Different mechanisms,
              different leverage. The audit measures both weekly so action items split cleanly.
            </p>
          </div>
        </div>
      </>
    );
  }

  // Normal state — at least one audit logged.
  const prompts = (latest && latest.prompts) || [];
  const totals = (latest && latest.totals) || {};
  const maxBarValue = Math.max(
    ...history.map(h => Math.max(h.citations || 0, h.mentions || 0)),
    1,
  );

  return (
    <>
      <div className="section-head" style={{marginTop:32}}>
        <span className="label">Strategic prompt audit · {s.prompts_audited || 15} prompts tracked weekly</span>
        <span className="mono" style={{marginLeft:'auto',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 audit {lastAuditLabel} · {staleLabel}
        </span>
        <span className="rule"/>
      </div>

      <div className="kpi-grid">
        <div className="kpi">
          <span className="label">Citations earned this week</span>
          <span className="value" style={{color:'var(--gold)'}}>{s.citations_this_week}</span>
          <span className={`delta ${deltaClass(s.citations_delta_wow)}`}>{deltaText(s.citations_delta_wow)}</span>
          <span className="source">source links in AI Mode sidebar</span>
        </div>
        <div className="kpi">
          <span className="label">Mentions earned this week</span>
          <span className="value" style={{color:'var(--gold)'}}>{s.mentions_this_week}</span>
          <span className={`delta ${deltaClass(s.mentions_delta_wow)}`}>{deltaText(s.mentions_delta_wow)}</span>
          <span className="source">brand named in AI answer body</span>
        </div>
        <div className="kpi">
          <span className="label">Prompts audited</span>
          <span className="value">{s.prompts_audited || prompts.length}</span>
          <span className="delta flat">locked at onboarding</span>
          <span className="source">5 brand · 5 service-intent · 5 competitor</span>
        </div>
        <div className="kpi">
          <span className="label">Audits in history</span>
          <span className="value">{auditCount}</span>
          <span className="delta flat">weekly cadence</span>
          <span className="source">manual capture per SOP</span>
        </div>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'1.55fr 1fr',gap:16,alignItems:'start',marginTop:16}}>
        <div className="panel">
          <div className="panel-head">
            <h3 style={{fontSize:14}}>Prompt-level outcome (latest audit)</h3>
            <div className="right" style={{marginLeft:'auto',fontFamily:'var(--font-mono)',fontSize:10,color:'var(--text-dim)'}}>{prompts.length} prompts</div>
          </div>
          <table className="table">
            <thead>
              <tr>
                <th style={{width:30}}>#</th>
                <th>Prompt</th>
                <th style={{width:80}}>Bucket</th>
                <th style={{width:80}}>Citation</th>
                <th style={{width:80}}>Mention</th>
              </tr>
            </thead>
            <tbody>
              {prompts.map((p) => (
                <tr key={p.n}>
                  <td className="mono" style={{fontSize:11,color:'var(--text-dim)'}}>{p.n}</td>
                  <td style={{fontSize:12}}>{p.prompt}</td>
                  <td>
                    <span className="mono" style={{fontSize:10,textTransform:'uppercase',letterSpacing:'0.04em',color:'var(--text-dim)'}}>
                      {p.bucket || '—'}
                    </span>
                  </td>
                  <td>
                    <span className={`serp-badge ${p.client_cited ? 'gold' : ''}`}>
                      {p.client_cited ? 'Yes' : 'No'}
                    </span>
                  </td>
                  <td>
                    <span className={`serp-badge ${p.mention_present ? 'gold' : ''}`}>
                      {p.mention_present ? 'Yes' : 'No'}
                    </span>
                  </td>
                </tr>
              ))}
              {prompts.length === 0 && (
                <tr><td colSpan={5} className="dim" style={{padding:'16px 18px',fontSize:12}}>No prompt-level data on this audit.</td></tr>
              )}
            </tbody>
          </table>
        </div>

        <div className="panel">
          <div className="panel-head">
            <h3 style={{fontSize:14}}>4-week trend</h3>
            <div className="right" style={{marginLeft:'auto',fontFamily:'var(--font-mono)',fontSize:10,color:'var(--text-dim)'}}>{history.length} of 4 weeks</div>
          </div>
          <div style={{padding:'14px 18px'}}>
            <div style={{display:'flex',gap:8,fontSize:11,color:'var(--text-dim)',marginBottom:10}}>
              <span><span style={{display:'inline-block',width:10,height:10,background:'var(--gold)',borderRadius:2,marginRight:6,verticalAlign:'middle'}}/>Citations</span>
              <span><span style={{display:'inline-block',width:10,height:10,background:'var(--accent)',borderRadius:2,marginRight:6,verticalAlign:'middle'}}/>Mentions</span>
            </div>
            {history.map((h, i) => (
              <div key={i} style={{marginBottom:14}}>
                <div style={{fontFamily:'var(--font-mono)',fontSize:10,color:'var(--text-dim)',marginBottom:4,display:'flex',justifyContent:'space-between'}}>
                  <span>{h.audit_week || h.audit_date}</span>
                  <span>{h.citations} cit · {h.mentions} men</span>
                </div>
                <div style={{height:6,background:'var(--bg)',borderRadius:2,overflow:'hidden',marginBottom:3}}>
                  <span style={{display:'block',height:'100%',width:`${Math.round((h.citations/maxBarValue)*100)}%`,background:'var(--gold)',borderRadius:2}}/>
                </div>
                <div style={{height:6,background:'var(--bg)',borderRadius:2,overflow:'hidden'}}>
                  <span style={{display:'block',height:'100%',width:`${Math.round((h.mentions/maxBarValue)*100)}%`,background:'var(--accent)',borderRadius:2}}/>
                </div>
              </div>
            ))}
            {history.length === 0 && (
              <div className="dim" style={{padding:'16px 0',fontSize:12}}>Trend builds as weekly audits accumulate.</div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

window.AEOAuditPanel = AEOAuditPanel;
