/* Page: GSC Search Performance */
function GscView({ client, range }) {
  const rangeParam = range === 'Last 7 days' ? '7d' : range === 'Last 90 days' ? '90d' : '28d';
  const { data, loading, error } = useApi(`/api/clients/${client.id}/gsc?range=${rangeParam}`, [client.id, rangeParam]);
  if (loading) return <div className="loading-state">Loading search performance...</div>;
  if (error) return <div className="error-state">Failed to load GSC data: {error}</div>;
  const D = data || {};
  return (
    <>
      <div className="page-head">
        <div>
          <div className="eyebrow gold"><span className="dot"/>Google Search Console · sc-domain:karatenation.ph</div>
          <h1>Search performance</h1>
          <div className="sub">Clicks, impressions, CTR, and average position. Query × page matrix maps where intent meets which page on the site.</div>
        </div>
        <div className="actions">
          <button className="btn btn-secondary"><Icon name="ext" size={13}/> Open in GSC</button>
        </div>
      </div>

      <div className="kpi-grid" style={{gridTemplateColumns: 'repeat(4, 1fr)'}}>
        <div className="kpi"><span className="label">Clicks · {rangeParam}</span><span className="value">{(D.summary?.clicks / 1000).toFixed(1)}k</span><span className="delta up"><Icon name="arrowUp" size={10}/> +22.1%</span><span className="source">GSC</span></div>
        <div className="kpi"><span className="label">Impressions · {rangeParam}</span><span className="value">{(D.summary?.impressions / 1000).toFixed(0)}k</span><span className="delta up"><Icon name="arrowUp" size={10}/> +14.6%</span><span className="source">GSC</span></div>
        <div className="kpi"><span className="label">CTR</span><span className="value">{D.summary?.ctr?.toFixed(1)}%</span><span className="delta up"><Icon name="arrowUp" size={10}/> +0.6pp</span><span className="source">GSC</span></div>
        <div className="kpi"><span className="label">Avg position</span><span className="value">{D.summary?.position?.toFixed(1)}</span><span className="delta up"><Icon name="arrowDown" size={10}/> −2.7</span><span className="source">GSC · all queries</span></div>
      </div>

      <div className="panel" style={{marginTop: 24}}>
        <div className="panel-head">
          <h3>Clicks vs impressions</h3>
          <span className="sub">Daily · {rangeParam}</span>
          <div className="right">
            <div className="tabs">
              <span className="tab active">Web</span>
              <span className="tab">Image</span>
              <span className="tab">News</span>
            </div>
          </div>
        </div>
        <div className="panel-body" style={{padding: '12px 8px 4px'}}>
          <TrendChart current={(D.daily || []).map(d => d.clicks)} previous={[]}/>
        </div>
      </div>

      <div className="row-2" style={{marginTop: 16}}>
        <div className="panel">
          <div className="panel-head"><h3>Top queries</h3><span className="sub">28d</span><div className="right"><div className="tabs"><span className="tab active">Queries</span><span className="tab">Pages</span><span className="tab">Countries</span><span className="tab">Devices</span></div></div></div>
          <div className="panel-body" style={{padding: 0}}>
            <table className="table">
              <thead><tr><th>Query</th><th className="num">Clicks</th><th className="num">Imps</th><th className="num">CTR</th><th className="num">Pos</th><th className="num">Δ Pos</th></tr></thead>
              <tbody>
                {(D.queries || []).map((q, i) => (
                  <tr key={i}>
                    <td><span style={{color:'var(--text)'}}>{q.query}</span></td>
                    <td className="num mono">{(q.clicks || 0).toLocaleString()}</td>
                    <td className="num mono">{(q.impressions || 0).toLocaleString()}</td>
                    <td className="num">
                      <div className="bar-cell">
                        <span className="bar green"><span style={{width: `${Math.min(100, (q.ctr || 0) * 10)}%`}}/></span>
                        <span className="mono">{(q.ctr || 0).toFixed(1)}%</span>
                      </div>
                    </td>
                    <td className="num"><span className={`pos-chip ${(q.position || 0) <= 3 ? 'top3' : (q.position || 0) <= 10 ? 'top10' : 'top30'}`}>{(q.position || 0).toFixed(1)}</span></td>
                    <td className="num"><span className="delta-chip flat">—</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div className="panel">
          <div className="panel-head"><h3>Striking-distance queries</h3><span className="sub">Pos 8–20 · 1k+ imps</span></div>
          <div className="panel-body" style={{display:'flex', flexDirection:'column', gap: 12}}>
            <p style={{fontSize: 12, color: 'var(--text-muted)'}}>22 queries within reach of page-1. Optimise the mapped page for intent + entity coverage to convert impressions into clicks.</p>
            {[
              { q: 'self defense classes near me', pos: 8.7, imps: 31800, page: '/programs/self-defense' },
              { q: 'karate vs taekwondo for kids',  pos: 12.4, imps: 18200, page: '/blog/karate-vs-taekwondo' },
              { q: 'after school activities makati',pos: 11.2, imps: 9400,  page: '/programs/after-school' },
              { q: 'martial arts birthday party ph',pos: 14.6, imps: 6200,  page: '/events/birthday-party' },
              { q: 'karate near bgc',               pos: 9.4,  imps: 4800,  page: '/locations/bgc' },
            ].map((r, i) => (
              <div key={i} style={{display:'flex', alignItems:'center', gap: 10, padding: '8px 0', borderBottom: i < 4 ? '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'}}>{r.q}</div>
                  <div className="mono-label" style={{fontSize: 9}}>{r.page}</div>
                </div>
                <span className="mono num" style={{fontSize: 11, color:'var(--text-muted)'}}>{(r.imps/1000).toFixed(1)}k</span>
                <span className="pos-chip top30">{r.pos.toFixed(1)}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}
window.GscView = GscView;

/* Page: GA4 Traffic & engagement */
function Ga4View({ client, range }) {
  const rangeParam = range === 'Last 7 days' ? '7d' : range === 'Last 90 days' ? '90d' : '30d';
  const { data, loading, error } = useApi(`/api/clients/${client.id}/ga4?range=${rangeParam}`, [client.id, rangeParam]);
  if (loading) return <div className="loading-state">Loading traffic data...</div>;
  if (error) return <div className="error-state">Failed to load GA4 data: {error}</div>;
  const D = data || {};
  return (
    <>
      <div className="page-head">
        <div>
          <div className="eyebrow gold"><span className="dot"/>GA4 · property 287 654 032</div>
          <h1>Traffic & engagement</h1>
          <div className="sub">Sessions, users, channel mix, and conversions. Filtered to organic by default; toggle to see the full picture.</div>
        </div>
      </div>

      <div className="kpi-grid">
        <div className="kpi"><span className="label">Sessions</span><span className="value">{((D.summary?.sessions || 0)/1000).toFixed(1)}k</span><span className="delta up"><Icon name="arrowUp" size={10}/> +14.2%</span><span className="source">GA4 · 30d</span></div>
        <div className="kpi"><span className="label">Users</span><span className="value">{((D.summary?.users || 0)/1000).toFixed(1)}k</span><span className="delta up"><Icon name="arrowUp" size={10}/> +12.6%</span><span className="source">GA4 · 30d</span></div>
        <div className="kpi"><span className="label">Engaged sessions</span><span className="value">{D.summary?.engagedRate != null ? D.summary.engagedRate.toFixed(1) : '—'}%</span><span className="delta up"><Icon name="arrowUp" size={10}/> +1.8pp</span><span className="source">GA4 · 30d</span></div>
        <div className="kpi"><span className="label">Avg session duration</span><span className="value">{D.summary?.avgSessionDurationFormatted || '—'}</span><span className="delta flat">+0:08</span><span className="source">GA4 · 30d</span></div>
        <div className="kpi"><span className="label">Conversions</span><span className="value">{D.summary?.conversions != null ? D.summary.conversions.toLocaleString() : '—'}</span><span className="delta up"><Icon name="arrowUp" size={10}/> +24.1%</span><span className="source">GA4 · key events</span></div>
      </div>

      <div className="row-2" style={{marginTop: 24}}>
        <div className="panel">
          <div className="panel-head"><h3>Sessions by channel</h3><span className="sub">Daily · 30d</span></div>
          <div className="panel-body" style={{padding: '12px 8px 4px'}}>
            <TrendChart current={D.traffic || []} previous={[]} height={220}/>
          </div>
        </div>
        <div className="panel">
          <div className="panel-head"><h3>Channel mix</h3></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>
                  <span className={`delta-chip ${c.delta >= 0 ? 'up' : 'down'}`} style={{minWidth: 50, justifyContent:'flex-end'}}>
                    {c.delta >= 0 ? '+' : ''}{c.delta.toFixed(1)}%
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="row-2" style={{marginTop: 16}}>
        <div className="panel">
          <div className="panel-head"><h3>Top landing pages</h3><span className="sub">Organic only · 30d</span></div>
          <div className="panel-body" style={{padding: 0}}>
            <table className="table">
              <thead><tr><th>Page</th><th className="num">Sessions</th><th className="num">Engaged</th><th className="num">Conv</th><th className="num">Conv rate</th></tr></thead>
              <tbody>
                {(D.pages || []).slice(0, 6).map((p, i) => (
                  <tr key={i}>
                    <td>
                      <div className="cell-stack">
                        <span className="lead">{p.url}</span>
                        <span className="meta mono-label" style={{fontSize:9}}>ORGANIC</span>
                      </div>
                    </td>
                    <td className="num mono">{p.sessions.toLocaleString()}</td>
                    <td className="num">
                      <div className="bar-cell"><span className="bar green"><span style={{width: `${Math.round((p.engagedSessions / Math.max(p.sessions,1)) * 100)}%`}}/></span><span className="mono">{Math.round((p.engagedSessions / Math.max(p.sessions,1)) * 100)}%</span></div>
                    </td>
                    <td className="num mono">{p.conversions}</td>
                    <td className="num mono">{p.sessions > 0 ? ((p.conversions / p.sessions) * 100).toFixed(1) : '0.0'}%</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        <div className="panel">
          <div className="panel-head"><h3>Conversions by event</h3><span className="sub">GA4 · 30d</span></div>
          <div className="panel-body">
            <HBar items={(D.conversions || []).slice(0, 5).map((cv, i) => ({
              label: cv.event.toUpperCase().replace(/_/g, ' '),
              value: cv.conversions,
              color: ['var(--gold)','var(--accent)','var(--gold-light)','var(--text-muted)','var(--text-dim)'][i],
            }))} max={Math.max(1, ...(D.conversions || []).slice(0,5).map(cv => cv.conversions))} format={v => v.toString()}/>
            <div style={{marginTop: 24, padding: 14, background: 'var(--surface)', borderRadius: 8}}>
              <div className="mono-label">Note · Q2</div>
              <p style={{fontSize: 12, color: 'var(--text-muted)', marginTop: 6, lineHeight: 1.6}}>
                Trial-form conversions drive the bulk of attributable revenue. Phone-click value is undercounted in GA4 — true number tracked in CallRail.
              </p>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
window.Ga4View = Ga4View;

/* Page: Backlinks */
function BacklinksView({ client }) {
  const { data, loading, error } = useApi(`/api/clients/${client.id}/backlinks`, [client.id]);
  if (loading) return <div className="loading-state">Loading backlinks...</div>;
  if (error) return <div className="error-state">Failed to load backlinks: {error}</div>;
  const D = data || {};
  return (
    <>
      <div className="page-head">
        <div>
          <div className="eyebrow gold"><span className="dot"/>Ahrefs + Semrush · merged dataset</div>
          <h1>Backlinks</h1>
          <div className="sub">Referring domain growth, DR distribution, gained vs lost. Outreach-ready filters at the bottom of the table.</div>
        </div>
      </div>

      <div className="kpi-grid">
        <div className="kpi"><span className="label">Domain rating</span><span className="value">{D.overview?.domainRating}</span><span className="delta up"><Icon name="arrowUp" size={10}/> +3</span><span className="source">Ahrefs · vs prev 30d</span></div>
        <div className="kpi"><span className="label">Referring domains</span><span className="value">{D.overview?.referringDomains}</span><span className="delta up"><Icon name="arrowUp" size={10}/> +14</span><span className="source">Ahrefs · live</span></div>
        <div className="kpi"><span className="label">Backlinks</span><span className="value">{D.overview?.backlinks?.toLocaleString()}</span><span className="delta up"><Icon name="arrowUp" size={10}/> +112</span><span className="source">Ahrefs · live</span></div>
        <div className="kpi"><span className="label">Dofollow ratio</span><span className="value">82%</span><span className="delta flat">+0.4pp</span><span className="source">Ahrefs</span></div>
        <div className="kpi"><span className="label">Lost · 30d</span><span className="value">8</span><span className="delta down"><Icon name="arrowDown" size={10}/> 4 from DR70+</span><span className="source">Ahrefs</span></div>
      </div>

      <div className="row-2" style={{marginTop: 24}}>
        <div className="panel">
          <div className="panel-head"><h3>Referring domains · growth</h3><span className="sub">90d</span></div>
          <div className="panel-body" style={{padding: '12px 8px 4px'}}>
            <TrendChart current={(D.history || []).map(h => h.refdomains)} previous={[]} height={220}/>
          </div>
        </div>
        <div className="panel">
          <div className="panel-head"><h3>DR distribution</h3></div>
          <div className="panel-body">
            <HBar items={[
              { label: 'DR 70+', value: 14,  color: 'var(--gold)' },
              { label: 'DR 50+', value: 38,  color: 'var(--gold-light)' },
              { label: 'DR 30+', value: 86,  color: 'var(--text-muted)' },
              { label: 'DR 10+', value: 62,  color: 'var(--text-dim)' },
              { label: 'DR <10', value: 18,  color: 'var(--border)' },
            ]} max={100} format={v => `${v} domains`}/>
            <div style={{marginTop: 16, fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.6}}>
              14 referring domains at DR 70+ — strong national press coverage from PH publications. Mid-band (DR 30–50) is where most outreach should focus next cycle.
            </div>
          </div>
        </div>
      </div>

      <div className="panel" style={{marginTop: 16}}>
        <div className="panel-head">
          <h3>Top referring domains</h3>
          <span className="sub">Sorted by DR</span>
          <div className="right">
            <div className="tabs">
              <span className="tab active">All</span>
              <span className="tab">Gained 30d</span>
              <span className="tab">Lost 30d</span>
            </div>
          </div>
        </div>
        <div className="panel-body" style={{padding: 0}}>
          <table className="table">
            <thead><tr><th>Domain</th><th className="num">DR</th><th className="num">Links</th><th className="num">Dofollow</th><th className="num">Domain traffic</th><th>First seen</th><th>Outreach</th></tr></thead>
            <tbody>
              {(D.domains || []).map((d, i) => (
                <tr key={i}>
                  <td>
                    <div style={{display:'flex', alignItems:'center', gap: 10}}>
                      <Icon name="globe" size={14} color="var(--text-dim)"/>
                      <span className="mono" style={{color:'var(--text)'}}>{d.domain}</span>
                    </div>
                  </td>
                  <td className="num">
                    <div className="bar-cell">
                      <span className="bar"><span style={{width: `${d.domainRating}%`}}/></span>
                      <span className="mono">{d.domainRating}</span>
                    </div>
                  </td>
                  <td className="num mono">{d.links}</td>
                  <td className="num mono">{d.dofollow}</td>
                  <td className="num mono">—</td>
                  <td className="mono" style={{fontSize: 11, color:'var(--text-muted)'}}>{d.firstSeen}</td>
                  <td><span className="tag">{i % 3 === 0 ? 'Earned' : i % 3 === 1 ? 'Pitched' : 'Cold'}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}
window.BacklinksView = BacklinksView;

/* Page: Settings / integrations */
function SettingsView({ client }) {
  const { data: health } = useApi('/api/sync/health', []);
  const recentSyncs = health?.recentSyncs || [];

  function getStatus(code) {
    const hit = recentSyncs.find(s => s.client_id === client?.id && s.integration === code.toLowerCase());
    if (!hit) return 'available';
    return hit.status === 'ok' ? 'connected' : 'error';
  }

  function getLastSync(code) {
    const hit = recentSyncs.find(s => s.client_id === client?.id && s.integration === code.toLowerCase());
    if (!hit) return null;
    const age = Math.floor(Date.now() / 1000) - hit.synced_at;
    return age < 3600 ? `${Math.round(age/60)}m ago`
         : age < 86400 ? `${Math.round(age/3600)}h ago`
         : `${Math.round(age/86400)}d ago`;
  }

  const sources = [
    { name: 'Google Analytics 4',   code: 'GA4',     desc: 'Sessions, users, conversions, attribution.' },
    { name: 'Google Search Console',code: 'GSC',     desc: 'Queries, pages, clicks, impressions, position.' },
    { name: 'Ahrefs',               code: 'AHREFS',  desc: 'Backlinks, referring domains, domain rating.' },
    { name: 'Semrush',              code: 'SEMRUSH', desc: 'Keyword positions, visibility, SERP features.' },
    { name: 'Google Ads',           code: 'ADS',     desc: 'Paid campaigns, keywords, conversions.',        future: true },
    { name: 'Meta Ads',             code: 'META',    desc: 'Paid social campaigns, audiences, ROAS.',       future: true },
    { name: 'Looker Studio',        code: 'LOOKER',  desc: 'Embed live tiles into client portals.' },
    { name: 'CallRail',             code: 'CALLRAIL',desc: 'Call tracking attributed to keyword + page.' },
  ].map(s => ({
    ...s,
    status: getStatus(s.code),
    prop: recentSyncs.find(r => r.client_id === client?.id && r.integration === s.code.toLowerCase())?.integration || null,
    sync: getLastSync(s.code),
  }));

  return (
    <>
      <div className="page-head">
        <div>
          <div className="eyebrow gold"><span className="dot"/>Workspace · {client?.name || 'Client'}</div>
          <h1>Integrations</h1>
          <div className="sub">Connect data sources once per client. Tokens are encrypted and refreshed automatically. PPC and Paid Social sources will activate when those channels launch.</div>
        </div>
      </div>

      <div className="row-2">
        <div style={{display:'flex', flexDirection:'column', gap: 10}}>
          {sources.map((s, i) => (
            <div key={i} className="panel" style={{padding: '16px 18px', display:'flex', alignItems:'center', gap: 14}}>
              <div style={{
                width: 44, height: 44, borderRadius: 8,
                background: s.status === 'connected' ? 'var(--gold-dim)' : 'var(--surface)',
                border: '1px solid var(--border)',
                display:'flex', alignItems:'center', justifyContent:'center',
                fontFamily:'var(--font-mono)', fontSize: 9, letterSpacing: '0.1em',
                color: s.status === 'connected' ? 'var(--gold)' : 'var(--text-muted)',
                flexShrink: 0,
              }}>{s.code}</div>
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{display:'flex', alignItems:'center', gap: 8}}>
                  <span style={{fontSize: 14, color:'var(--text)', fontWeight: 500}}>{s.name}</span>
                  {s.future && <span className="serp-badge">PPC · soon</span>}
                </div>
                <div style={{fontSize: 12, color:'var(--text-muted)', marginTop: 2}}>{s.desc}</div>
                {s.sync && (
                  <div className="mono-label" style={{fontSize: 9, marginTop: 6}}>
                    {s.code} · SYNCED {s.sync}
                  </div>
                )}
              </div>
              {s.status === 'connected' || s.status === 'error' ? (
                <>
                  <span className={`status ${s.status === 'connected' ? 'ok' : 'err'}`}><span className="dot"/>{s.status === 'connected' ? 'Connected' : 'Error'}</span>
                  <button className="btn-ghost">Manage</button>
                </>
              ) : (
                <button className="btn btn-secondary"><Icon name="plus" size={12}/>Connect</button>
              )}
            </div>
          ))}
        </div>

        <div style={{display:'flex', flexDirection:'column', gap: 10}}>
          <div className="panel">
            <div className="panel-head"><h3>Workspace defaults</h3></div>
            <div className="panel-body" style={{display:'flex', flexDirection:'column', gap: 14, fontSize: 13}}>
              <Field label="Default reporting period" value="Last 30 days"/>
              <Field label="Compare to" value="Previous period"/>
              <Field label="Country" value="Philippines"/>
              <Field label="Device" value="Desktop"/>
              <Field label="Currency" value="PHP ₱"/>
              <Field label="Time zone" value="Asia / Manila"/>
            </div>
          </div>

          <div className="panel">
            <div className="panel-head"><h3>Client portal access</h3></div>
            <div className="panel-body" style={{fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.6}}>
              <p>The client view is white-label by default. Toggle the agency wordmark on or off in workspace settings, or assign a custom subdomain.</p>
              <div style={{marginTop: 14, display:'flex', flexDirection:'column', gap: 8}}>
                <div style={{display:'flex', alignItems:'center', gap: 10}}>
                  <div className="sb-avatar" style={{width: 26, height: 26, fontSize: 9}}>SR</div>
                  <div style={{flex: 1, minWidth: 0}}>
                    <div style={{fontSize: 13, color:'var(--text)'}}>Sofia Reyes</div>
                    <div className="mono-label" style={{fontSize: 9}}>OWNER · KARATENATION.PH</div>
                  </div>
                  <span className="status ok"><span className="dot"/>Active</span>
                </div>
                <div style={{display:'flex', alignItems:'center', gap: 10}}>
                  <div className="sb-avatar" style={{width: 26, height: 26, fontSize: 9}}>MJ</div>
                  <div style={{flex: 1, minWidth: 0}}>
                    <div style={{fontSize: 13, color:'var(--text)'}}>Miguel Javier</div>
                    <div className="mono-label" style={{fontSize: 9}}>VIEWER</div>
                  </div>
                  <span className="status off"><span className="dot"/>Pending</span>
                </div>
              </div>
              <button className="btn btn-secondary" style={{marginTop: 14}}><Icon name="plus" size={12}/>Invite client user</button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function Field({ label, value }) {
  return (
    <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', padding: '6px 0', borderBottom:'1px solid var(--border-light)'}}>
      <span className="mono-label">{label}</span>
      <span style={{color:'var(--text)'}}>{value}</span>
    </div>
  );
}

window.SettingsView = SettingsView;
