/* Page: Single client SEO Overview */
function OverviewView({ client, range }) {
  const rangeParam = range === 'Last 7 days' ? '7d'
                   : range === 'Last 90 days' ? '90d'
                   : range === 'YTD' ? 'ytd'
                   : '30d';

  const { data: D, loading, error } = useApi(
    `/api/clients/${client.id}/overview?range=${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>;

  const traffic90 = D.traffic90 || [];
  const trafficPrev = D.trafficPrev || [];
  const totalSessions = traffic90.reduce((a,b) => a+b, 0);
  const prevSessions = trafficPrev.reduce((a,b) => a+b, 0);
  const delta = prevSessions > 0 ? ((totalSessions - prevSessions) / prevSessions) * 100 : 0;

  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 · Q2 2026 in progress</div>
            <h1>Foundation set. Rank stabilising. Content investment unblocked.</h1>
            <div className="sub">Cannibalisation resolved on 3 priority clusters. Crawl budget recovered. Organic sessions +18% MoM in March.</div>
          </div>
          <div className="actions">
            <button className="btn btn-secondary"><Icon name="ext" size={13}/> Open report</button>
          </div>
        </div>
      </div>

      <div className="kpi-grid">
        <div className="kpi">
          <span className="label">Organic sessions</span>
          <span className="value">{(totalSessions/1000).toFixed(1)}k</span>
          <span className="delta up"><Icon name="arrowUp" size={10}/> +{delta.toFixed(1)}% vs prev 90d</span>
          <Spark values={traffic90.slice(-30)} w={120} h={28} color="var(--gold)"/>
          <span className="source">GA4 · last 90 days</span>
        </div>
        <div className="kpi">
          <span className="label">Conversions</span>
          <span className="value">{D.conversions}</span>
          <span className="delta up"><Icon name="arrowUp" size={10}/> +{D.convDelta}%</span>
          <Spark values={[180,190,205,210,224,238,245,260,278,290,298,308,318]} w={120} h={28} color="var(--accent)"/>
          <span className="source">GA4 · key events</span>
        </div>
        <div className="kpi">
          <span className="label">Avg position</span>
          <span className="value">{D.avgPosition}</span>
          <span className="delta up"><Icon name="arrowDown" size={10}/> −2.7</span>
          <Spark values={[16,15,14.5,14,13.5,13,12.8,12.4,12,11.8,11.5,11.4,11.4]} w={120} h={28} color="var(--gold)"/>
          <span className="source">GSC · 142 tracked</span>
        </div>
        <div className="kpi">
          <span className="label">CTR</span>
          <span className="value">{D.ctr}%</span>
          <span className="delta up"><Icon name="arrowUp" size={10}/> +0.6pp</span>
          <Spark values={[3.9,4.0,4.1,4.0,4.2,4.3,4.4,4.5,4.5,4.6,4.7,4.8,4.8]} w={120} h={28} color="var(--gold)"/>
          <span className="source">GSC · last 28 days</span>
        </div>
        <div className="kpi">
          <span className="label">Top-3 keywords</span>
          <span className="value">{D.top3Keywords}</span>
          <span className="delta up"><Icon name="arrowUp" size={10}/> +11</span>
          <Spark values={[22,24,25,27,29,30,32,33,34,36,37,38,38]} w={120} h={28} color="var(--gold)"/>
          <span className="source">Semrush · tracked set</span>
        </div>
      </div>

      <div className="row-2" style={{marginTop: 24}}>
        <div className="panel">
          <div className="panel-head">
            <h3>Organic traffic</h3>
            <span className="sub">Daily sessions · 90 days</span>
            <div className="right">
              <div className="tabs">
                <span className="tab active">Sessions</span>
                <span className="tab">Users</span>
                <span className="tab">Engaged</span>
              </div>
            </div>
          </div>
          <div className="panel-body" style={{padding: '12px 8px 4px'}}>
            <TrendChart current={traffic90} previous={trafficPrev}/>
          </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 90d</div>
              <div style={{fontFamily:'var(--font-display)', fontWeight: 700, fontSize: 22}}>{totalSessions.toLocaleString()}</div>
            </div>
            <div>
              <div className="mono-label">Previous 90d</div>
              <div style={{fontFamily:'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--text-muted)'}}>{prevSessions.toLocaleString()}</div>
            </div>
            <div>
              <div className="mono-label">Best day</div>
              <div style={{fontFamily:'var(--font-display)', fontWeight: 700, fontSize: 22}}>{(traffic90.length ? Math.max(...traffic90) : 0).toLocaleString()}</div>
            </div>
            <div style={{marginLeft:'auto', alignSelf:'center'}}>
              <span className="source-line"><span className="dot"/>GA4 · property 287654032<span className="dot"/>Synced 14m ago</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></div>
          <div className="panel-body" style={{display:'flex', flexDirection:'column', gap: 14}}>
            {[
              { p: 'High', t: 'Cannibalisation across 14 pages', d: 'Core service terms split rank between competing pages. Highest-leverage fix this cycle.' },
              { p: 'High', t: '340 parameterised URLs wasting crawl budget', d: 'Faceted-nav URLs indexed without intent. Block in robots.txt.' },
              { p: 'Med',  t: 'Cluster architecture missing for 3 service lines', d: 'No pillar pages anchor mid-funnel intent. Briefs queued for Q2 execution.' },
            ].map((f, i) => (
              <div key={i} style={{display:'flex', gap: 12, alignItems:'flex-start', paddingBottom: i < 2 ? 14 : 0, borderBottom: i < 2 ? '1px solid var(--border-light)' : 'none'}}>
                <span className={`status ${f.p === 'High' ? 'err' : 'warn'}`} style={{marginTop: 3}}>
                  <span className="dot"/>{f.p}
                </span>
                <div>
                  <div style={{fontSize: 13, color: 'var(--text)', fontWeight: 500}}>{f.t}</div>
                  <div style={{fontSize: 12, color: 'var(--text-muted)', marginTop: 2}}>{f.d}</div>
                </div>
              </div>
            ))}
          </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;
