/* Page: Single client SEO Overview */
const { useState: useStateO } = React;

// Compact AI Visibility tile for the Overview KPI grid. Mirrors the lead
// metric on the AI Visibility deep-dive page: client cited count + "of N
// addressable" + last-checked source. Falls back to a placeholder when no
// snapshot exists for the client.
function AioKpiTile({ data, clientName }) {
  if (!data) {
    return (
      <div className="kpi">
        <span className="label">AI Visibility</span>
        <span className="value">—</span>
        <span className="source">no snapshot yet</span>
      </div>
    );
  }
  const cited = data.value ?? 0;
  const opportunity = data.extra?.opportunity ?? null;
  const detected = data.extra?.detected ?? null;
  const sub = opportunity != null
    ? `of ${opportunity} addressable`
    : detected != null ? `${detected} AIOs in tracked set` : 'baseline · grows with pages';
  return (
    <div className="kpi">
      <span className="label">{clientName || 'Client'} cited in AI Overviews</span>
      <span className="value" style={{color:'var(--gold)'}}>{cited}</span>
      <span className="delta flat">{sub}</span>
      <span className="source">{data.source || 'AI Visibility'}</span>
    </div>
  );
}

// Compact AEO Audit tile for the Overview KPI grid. Mirrors the strategic
// prompt audit panel on the AI Visibility deep-dive page: citations earned
// this week as the headline, mentions visible in the source line so the
// citations-vs-mentions distinction stays surfaced even at a glance.
// Fetches the same /aeo-audit endpoint as AEOAuditPanel; both stay
// consistent because they read from the same data.
function AeoAuditKpiTile({ client }) {
  const { data, loading, error } = useApi(`/api/clients/${client.id}/aeo-audit`, [client.id]);
  if (loading) {
    return (
      <div className="kpi">
        <span className="label">AEO citations earned</span>
        <span className="value">…</span>
        <span className="source">loading audit data</span>
      </div>
    );
  }
  if (error || !data) {
    return (
      <div className="kpi">
        <span className="label">AEO citations earned</span>
        <span className="value">—</span>
        <span className="source">audit data unavailable</span>
      </div>
    );
  }
  const s = data.summary || {};
  const auditCount = data.audit_count || 0;
  if (auditCount === 0) {
    return (
      <div className="kpi">
        <span className="label">AEO citations earned</span>
        <span className="value" style={{color:'var(--text-dim)'}}>—</span>
        <span className="delta flat">baseline pending</span>
        <span className="source">15-prompt weekly audit · SOP standard</span>
      </div>
    );
  }
  const citations = s.citations_this_week || 0;
  const mentions = s.mentions_this_week || 0;
  const citationDelta = s.citations_delta_wow;
  const deltaText = citationDelta == null ? 'first week of tracking' :
    citationDelta === 0 ? 'flat vs last week' :
    citationDelta > 0 ? `+${citationDelta} vs last week` : `${citationDelta} vs last week`;
  const deltaClass = citationDelta == null ? 'flat' : citationDelta > 0 ? 'up' : citationDelta < 0 ? 'down' : 'flat';
  return (
    <div className="kpi">
      <span className="label">AEO citations earned</span>
      <span className="value" style={{color:'var(--gold)'}}>{citations}</span>
      <span className={`delta ${deltaClass}`}>{deltaText}</span>
      <span className="source">{mentions} mention{mentions === 1 ? '' : 's'} · weekly prompt audit</span>
    </div>
  );
}

function OverviewView({ client, range }) {
  // Range is passed through unchanged — the backend's parseDateRange handles
  // both legacy ('7d' | '30d' | '90d' | 'ytd') and calendar-month ('month:YYYY-MM')
  // forms. encodeURIComponent for the colon in month: values.
  const rangeParam = range || '30d';

  const [metric, setMetric] = useStateO('sessions'); // 'sessions' | 'users' | 'engaged'

  const { data: D, loading, error } = useApi(
    `/api/clients/${client.id}/overview?range=${encodeURIComponent(rangeParam)}`,
    [client.id, rangeParam]
  );

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

  // Defensive: older cached responses only carry kpis.sessions.sparkline.
  const traffic = D.traffic || {
    sessions: D.kpis?.sessions?.sparkline || [],
    users: [],
    engaged: [],
    dates: []
  };
  const totals = D.totals || {
    sessions: D.kpis?.sessions?.value ?? 0,
    users: 0,
    engaged: 0
  };
  const currentSeries = traffic[metric] || [];
  const metricLabel = { sessions: 'sessions', users: 'users', engaged: 'engaged sessions' }[metric];
  // Period label comes from the API now (computed by rangeLabel server-side)
  // so the dashboard text and the picker value always match.
  const periodLabel = D.periodLabel
    || (rangeParam === '7d' ? '7 days'
        : rangeParam === '90d' ? '90 days'
        : rangeParam === 'ytd' ? 'YTD' : '30 days');

  return (
    <>
      <div style={{position:'relative'}}>
        <div className="wash"/>
        <div className="page-head" style={{position:'relative', zIndex:1}}>
          <div>
            <div className="eyebrow gold"><span className="dot"/>SEO · {client?.name || 'Client'}</div>
            <h1>Overview</h1>
            <div className="sub">Sessions, conversions, and rank highlights for the selected reporting period. Filter the date range from the topbar.</div>
          </div>
          <div className="actions">
            <button className="btn btn-secondary" disabled title="PDF export not yet built" style={{opacity:0.5, cursor:'not-allowed'}}>
              <Icon name="ext" size={13}/> Open report (soon)
            </button>
          </div>
        </div>
      </div>

      <div className="kpi-grid">
        <KPI label="Organic sessions"    {...D.kpis.sessions}/>
        <KPI label="Impressions"         {...(D.kpis.impressions || {})}/>
        <KPI label="Conversions"         {...D.kpis.conversions}/>
        <KPI label="Avg position"        {...D.kpis.avgPosition}/>
        <KPI label="CTR"                 {...D.kpis.ctr}/>
        <AioKpiTile data={D.kpis.aioVisibility} clientName={client?.name}/>
        <AeoAuditKpiTile client={client}/>
        <KPI label="Top-3 keywords"      {...D.kpis.top3Keywords}/>
        <KPI label="Top-10 keywords"     {...D.kpis.top10Keywords}/>
        <KPI label="Striking distance"   {...D.kpis.strikingDistance}/>
      </div>

      <div className="row-2" style={{marginTop: 24}}>
        <div className="panel">
          <div className="panel-head">
            <h3>Organic traffic</h3>
            <span className="sub">Daily {metricLabel} · {periodLabel}</span>
            <div className="right">
              <div className="tabs">
                <span className={`tab ${metric === 'sessions' ? 'active' : ''}`}
                      onClick={() => setMetric('sessions')}
                      style={{cursor:'pointer'}}>Sessions</span>
                <span className={`tab ${metric === 'users' ? 'active' : ''}`}
                      onClick={() => setMetric('users')}
                      style={{cursor:'pointer'}}>Users</span>
                <span className={`tab ${metric === 'engaged' ? 'active' : ''}`}
                      onClick={() => setMetric('engaged')}
                      style={{cursor:'pointer'}}>Engaged</span>
              </div>
            </div>
          </div>
          <div className="panel-body" style={{padding: '12px 8px 4px'}}>
            <TrendChart current={currentSeries} previous={[]} dates={traffic.dates}/>
          </div>
          <div className="panel-body" style={{borderTop:'1px solid var(--border-light)', display:'flex', gap: 24, padding: '14px 18px'}}>
            <div>
              <div className="mono-label">Current {periodLabel}</div>
              <div style={{fontFamily:'var(--font-display)', fontWeight: 700, fontSize: 22}}>{(totals[metric] ?? 0).toLocaleString()}</div>
            </div>
            <div>
              <div className="mono-label">Best day</div>
              <div style={{fontFamily:'var(--font-display)', fontWeight: 700, fontSize: 22}}>{(currentSeries.length ? Math.max(...currentSeries) : 0).toLocaleString()}</div>
            </div>
            <div style={{marginLeft:'auto', alignSelf:'center'}}>
              <span className="source-line"><span className="dot"/>GA4 · property {client?.ga4PropertyId || '—'}</span>
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="panel-head"><h3>Top movers</h3><span className="sub">Last 7 days</span></div>
          <div className="panel-body" style={{padding: '4px 0 8px'}}>
            <div style={{padding: '8px 18px 4px'}} className="mono-label">Climbing</div>
            {(D.topMovers?.up || []).map((m, i) => (
              <div key={i} style={{display:'flex', alignItems:'center', gap: 12, padding: '8px 18px', borderBottom: '1px solid var(--border-light)'}}>
                <div style={{flex: 1, minWidth: 0}}>
                  <div style={{fontSize: 13, color: 'var(--text)', whiteSpace: 'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{m.kw}</div>
                  <div className="mono-label" style={{fontSize: 9}}>{m.page}</div>
                </div>
                <span className="pos-chip top30">{m.from}</span>
                <Icon name="chevR" size={11} color="var(--text-dim)"/>
                <span className={`pos-chip ${m.to <= 3 ? 'top3' : 'top10'}`}>{m.to}</span>
              </div>
            ))}
            <div style={{padding: '12px 18px 4px'}} className="mono-label">Slipping</div>
            {(D.topMovers?.down || []).map((m, i) => (
              <div key={i} style={{display:'flex', alignItems:'center', gap: 12, padding: '8px 18px', borderBottom: i < (D.topMovers?.down || []).length-1 ? '1px solid var(--border-light)' : 'none'}}>
                <div style={{flex: 1, minWidth: 0}}>
                  <div style={{fontSize: 13, color: 'var(--text)', whiteSpace: 'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{m.kw}</div>
                  <div className="mono-label" style={{fontSize: 9}}>{m.page}</div>
                </div>
                <span className="pos-chip top10">{m.from}</span>
                <Icon name="chevR" size={11} color="var(--text-dim)"/>
                <span className="pos-chip top30">{m.to}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="row-3" style={{marginTop: 16}}>
        <div className="panel">
          <div className="panel-head"><h3>Channel mix</h3><span className="sub">GA4 · 30d</span></div>
          <div className="panel-body" style={{display:'flex', gap: 18, alignItems: 'center'}}>
            <Donut data={D.channels || []} size={180} total={(D.channels || []).reduce((a,c) => a + c.value, 0)}/>
            <div style={{flex: 1, display:'flex', flexDirection:'column', gap: 8}}>
              {(D.channels || []).map((c, i) => (
                <div key={i} style={{display:'flex', alignItems:'center', gap: 8, fontSize: 12}}>
                  <span style={{width: 8, height: 8, borderRadius: 2, background: ['var(--gold)','var(--text)','var(--accent)','var(--gold-light)','var(--text-muted)','var(--text-dim)'][i]}}/>
                  <span style={{flex: 1, color: 'var(--text)'}}>{c.name}</span>
                  <span className="mono num" style={{color: 'var(--text-dim)'}}>{c.share.toFixed(1)}%</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="panel-head"><h3>This cycle's findings</h3><span className="sub">Manual notes</span></div>
          <div className="panel-body" style={{fontSize: 13, color:'var(--text-muted)', lineHeight: 1.6}}>
            <p>Findings will appear here once the client-cycle notes feature ships. Until then, write findings into the monthly client report directly.</p>
          </div>
        </div>

        <div className="panel">
          <div className="panel-head"><h3>Data sources</h3><span className="sub">Last sync</span></div>
          <div className="panel-body" style={{display:'flex', flexDirection:'column', gap: 12}}>
            {(D.dataSources || []).map((s, i) => (
              <div key={i} style={{display:'flex', alignItems:'center', gap: 10, fontSize: 12, paddingBottom: 8, borderBottom: i < (D.dataSources || []).length-1 ? '1px solid var(--border-light)' : 'none'}}>
                <span className="serp-badge gold" style={{minWidth: 56, justifyContent:'center'}}>{s.name.toUpperCase()}</span>
                <div style={{flex: 1, minWidth: 0}}>
                  <div className="mono num" style={{fontSize: 11, color: 'var(--text)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{s.prop}</div>
                  <div className="mono-label" style={{fontSize: 9}}>STATUS {s.status.toUpperCase()}</div>
                </div>
                <span className={`status ${s.status === 'ok' ? 'ok' : s.status === 'mock' ? 'warn' : 'err'}`}><span className="dot"/></span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}
window.OverviewView = OverviewView;
