// views_agency.jsx — agency delivery console: Dashboard, Clients, Compare,
// Visibility tests, Knowledge & widget, Integrations & publishing, White-label.
(function () {
  const { useState } = React;
  const D = window.JS_DATA;

  const scoreRingColor = s => s >= 75 ? 'var(--lime)' : s >= 50 ? 'var(--gold)' : 'var(--coral)';
  const needAudit = () => !D.AUDIT || !D.AUDIT.id;
  async function runAction(label, action, setStatus) {
    if (setStatus) setStatus(`${label} running…`);
    try {
      const result = await action();
      if (setStatus) setStatus(`${label} completed`);
      return result;
    } catch (e) {
      if (setStatus) setStatus(`${label} failed: ${e.message}`);
      return null;
    }
  }

  // ---- EngineTrends: per-engine citation small-multiples -----------------
  // Replaces the old flat AI-source bars. Each engine gets its own trend so an
  // agency can say "we 2.3×'d your AI Overview citations" — not just a number.
  function EngineTrends({ compact }) {
    const rows = D.AI_SOURCE_HISTORY;
    return (
      <div className={'js-engtrends' + (compact ? ' is-compact' : '')}>
        {rows.map(s => {
          const accent = window.accentVar(s.accent);
          const first = s.series[0], last = s.series[s.series.length - 1];
          const mult = first ? (last / first) : 1;
          const up = s.trend >= 0;
          return (
            <div key={s.engine} className="js-engcard">
              <div className="ec-top">
                <span className="ec-name">{s.engine}</span>
                <span className="ec-trend" style={{ color: up ? 'var(--lime)' : 'var(--coral)' }}>{up ? '▴' : '▾'} {up ? '+' : ''}{s.trend}</span>
              </div>
              <div className="ec-figs">
                <span className="ec-cites" style={{ color: accent }}>{s.citations}</span>
                <span className="ec-unit">citations</span>
                {mult >= 1.3 && <span className="ec-mult">{mult.toFixed(1)}× since Jan</span>}
              </div>
              <div className="ec-spark"><MicroSpark values={s.series} accent={accent} h={compact ? 30 : 40} /></div>
              <div className="ec-foot"><span className="js-tag">{s.mentions} mentions</span><span className="js-tag">{Math.round(s.share * 100)}% share</span></div>
            </div>
          );
        })}
      </div>
    );
  }
  window.EngineTrends = EngineTrends;

  // ============================================================ DASHBOARD
  function AgencyDashboard({ go, startTour }) {
    const clients = D.CLIENTS;
    const avg = clients.length ? Math.round(clients.reduce((s, c) => s + c.score, 0) / clients.length) : 0;
    const attention = clients.filter(c => c.status !== 'active');
    return (
      <div className="js-view js-view--wide">
        <div className="js-pagehead">
          <div><p className="eyebrow">Agency workspace</p><h1>Delivery <em>console</em></h1>
            <p className="sub">{clients.length ? `${clients.length} backend client${clients.length === 1 ? '' : 's'} loaded across AI-search optimization.` : 'No backend clients are visible to this session yet.'}</p></div>
          <div className="js-head-actions">{startTour && <Btn kind="ghost" icon="sparkles" sm onClick={startTour}>Take the tour</Btn>}<Btn kind="ghost" icon="play" sm onClick={() => go('run-audit')}>Run audit</Btn><Btn icon="plus" onClick={() => go('clients')}>Add client</Btn></div>
        </div>

        <div className="js-stats" style={{ marginBottom: 22 }}>
          <Stat k="Portfolio avg" v={avg} sub="from backend clients" dir="flat" icon="gauge" />
          <Stat k="Active clients" v={clients.length} sub="backend clients" dir="up" icon="users" />
          <Stat k="Needs attention" v={attention.length} sub="backend status" dir="flat" icon="alert" />
          <Stat k="Audits loaded" v={(window.JS_LIVE_SUMMARY?.auditSummaries || []).length} sub="visible to session" dir="flat" icon="activity" />
        </div>

        <div className="js-cols-main">
          <Panel>
            <PanelHead eyebrow="Portfolio" title="Clients by JiffyScore">
              <span className="js-link-gold" onClick={() => go('clients')}>All clients <Icon name="arrow" size={14} /></span>
            </PanelHead>
            <div className="js-rows">
              {clients.length ? clients.slice(0, 6).map(c => <ClientRow key={c.id} c={c} go={go} />) : <EmptyState icon="users" title="No backend clients" desc="Create or seed clients before portfolio delivery metrics are shown." />}
            </div>
          </Panel>
          <div className="stack">
            <Panel raised>
              <PanelHead title="Needs attention" />
              <div className="stack" style={{ gap: 10 }}>
                {attention.length ? attention.map(c => (
                  <div key={c.id} className="row" style={{ justifyContent: 'space-between', cursor: 'pointer', gap: 12 }} onClick={() => go('results')}>
                    <div style={{ minWidth: 0, flex: 1 }}><div style={{ fontWeight: 600, fontSize: 14 }}>{c.name}</div><div className="rc-sub">{c.status === 'stale' ? 'Not audited in 2 weeks' : c.delta < 0 ? 'Score dropping' : 'High regret risk'}</div></div>
                    <span className="js-scorechip" style={{ flex: 'none' }}><span className="sc-ring" style={{ background: scoreRingColor(c.score) }} />{c.score}</span>
                  </div>
                )) : <div className="rc-sub">No backend clients currently need attention.</div>}
              </div>
            </Panel>
            <Panel className="js-artback" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <PanelHead title="In the answer" />
              <p style={{ fontSize: 13, color: 'var(--ink-soft)', margin: '-8px 0 4px', lineHeight: 1.5 }}>The old static answer theatre is retired. Use AI-source tracking and citation observations for backend evidence.</p>
              <Btn sm kind="gold" icon="bot" onClick={() => go('answer')}>Open answer preview</Btn>
            </Panel>
          </div>
        </div>

        {/* AI source share — trended small-multiples, full width so it breathes */}
        <Panel style={{ marginTop: 22 }}>
          <PanelHead eyebrow="Generative engines" title="AI source share over time"
            desc="Citations earned per answer engine across the portfolio, month by month — momentum, not a snapshot.">
            <span className="js-link-gold" onClick={() => go('integrations')}>Source tracking <Icon name="arrow" size={14} /></span>
          </PanelHead>
          <EmptyState icon="activity" title="No live AI-source run selected" desc="Run AI-source tracking from Integrations after creating an audit to populate engine trend data." action={<Btn sm kind="gold" icon="play" onClick={() => go('integrations')}>Open integrations</Btn>} />
        </Panel>
      </div>
    );
  }
  window.AgencyDashboard = AgencyDashboard;

  function ClientRow({ c, go }) {
    return (
      <div className="js-rowcard" style={{ gridTemplateColumns: 'auto 1fr auto auto auto' }} onClick={() => go('results')}>
        <div style={{ width: 40, height: 40, borderRadius: 11, background: 'var(--surface-2)', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--gold)', border: '1px solid var(--line-soft)' }}>{c.name[0]}</div>
        <div><div className="rc-title">{c.name}</div><div className="rc-sub">{c.domain} · {c.industry} · {c.lastRun}</div></div>
        <span className="js-num" style={{ fontSize: 12, color: c.delta >= 0 ? 'var(--lime)' : 'var(--coral)' }}>{c.delta >= 0 ? '+' : ''}{c.delta}</span>
        <RegretBadge level={c.regret} />
        <span className="js-scorechip"><span className="sc-ring" style={{ background: scoreRingColor(c.score) }} />{c.score}</span>
      </div>
    );
  }

  // ============================================================ CLIENTS
  function Clients({ go }) {
    const [q, setQ] = useState('');
    const [filter, setFilter] = useState('All');
    const filters = ['All', 'Active', 'Needs attention', 'Stale'];
    const list = D.CLIENTS.filter(c => (filter === 'All' || (filter === 'Active' && c.status === 'active') || (filter === 'Needs attention' && c.status === 'attention') || (filter === 'Stale' && c.status === 'stale')) && c.name.toLowerCase().includes(q.toLowerCase()));
    return (
      <div className="js-view js-view--wide">
        <div className="js-pagehead"><div><p className="eyebrow">Clients · {D.CLIENTS.length}</p><h1>Your <em>roster</em></h1>
          <p className="sub">Every client website you optimize for AI search. Open any to view its audit, recommendations, and monitoring.</p></div>
          <Btn icon="plus" onClick={() => go('run-audit')}>Add client</Btn></div>

        <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap', gap: 12 }}>
          <div className="search-input-wrap" style={{ maxWidth: 320 }}>
            <Icon name="search" className="lead" /><input className="search-input" placeholder="Search clients…" value={q} onChange={e => setQ(e.target.value)} />
          </div>
          <div className="seg">{filters.map(f => <button key={f} className={'seg-opt' + (filter === f ? ' is-active' : '')} onClick={() => setFilter(f)}>{f}</button>)}</div>
        </div>

        <Panel style={{ padding: 14 }}>
          <div className="js-rows">{list.length ? list.map(c => <ClientRow key={c.id} c={c} go={go} />) : <EmptyState icon="users" title="No clients match" desc="Try a different filter or search." />}</div>
        </Panel>
      </div>
    );
  }
  window.Clients = Clients;

  // ============================================================ COMPARE
  function Compare({ go, openSteal }) {
    const rows = D.COMPETITORS;
    const [status, setStatus] = useState('');
    const max = m => Math.max(...rows.map(r => r[m]));
    const cols = [['total', 'JiffyScore'], ['ai', 'AI readiness'], ['citation', 'Citation'], ['content', 'Content']];
    return (
      <div className="js-view js-view--wide">
        <div className="js-pagehead"><div><p className="eyebrow">Competitor compare</p><h1>Where you <em>stand</em></h1>
          <p className="sub">Run a backend competitor comparison against the selected audit. No static comparison result is shown until a run exists.</p></div>
          <Btn kind="ghost" icon="plus" sm onClick={() => needAudit() ? setStatus('Run an audit before competitor comparison.') : runAction('Competitor comparison', () => window.JS_API.growth.runCompetitors(D.AUDIT.id, rows.filter(r => !r.you).map(r => ({ name: r.name, url: `https://${r.name.toLowerCase().replace(/[^a-z0-9]+/g, '')}.com.au` }))), setStatus)}>Run comparison</Btn></div>

        <Panel style={{ marginBottom: 18 }}>
          <PanelHead eyebrow="Head to head" title="Scored on equal footing" />
          {cols.map(([key, label]) => (
            <div key={key} style={{ marginBottom: 22 }}>
              <div className="js-tag" style={{ marginBottom: 12 }}>{label}</div>
              <div className="stack" style={{ gap: 10 }}>
                {rows.map(r => (
                  <div key={r.name} className="row" style={{ gap: 14 }}>
                    <div style={{ width: 170, fontSize: 13, color: r.you ? 'var(--gold)' : 'var(--ink-soft)', fontWeight: r.you ? 600 : 400, flex: 'none' }}>{r.name}{r.you && ' · you'}</div>
                    <div style={{ flex: 1 }}><div className="track" style={{ height: 26, background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', overflow: 'hidden', position: 'relative' }}>
                      <div style={{ height: '100%', width: (r[key] / 100 * 100) + '%', background: r.you ? 'var(--lime-gradient)' : 'var(--surface-2)', borderRight: r.you ? 0 : '0', transition: 'width 1s var(--ease-out-expo)', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 10 }}>
                        <span className="js-num" style={{ fontSize: 12, color: r.you ? 'var(--on-lime)' : 'transparent' }}>{r[key]}</span>
                      </div>
                      {!r.you && <span className="js-num" style={{ position: 'absolute', left: (r[key]) + '%', top: '50%', transform: 'translate(8px,-50%)', fontSize: 12, color: 'var(--ink-soft)' }}>{r[key]}</span>}
                      {r[key] === max(key) && <span style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--gold)' }}><Icon name="star" size={14} /></span>}
                    </div></div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </Panel>

        {status && <div className="js-gap sev-low" style={{ marginBottom: 18 }}><p style={{ margin: 0 }}>{status}</p></div>}
        <div className="js-gap sev-medium">
          <h4><Icon name="target" size={16} style={{ color: 'var(--gold)' }} />The takeaway</h4>
          <p style={{ margin: '0 0 14px' }}>Run the backend comparison to calculate competitor gaps, schema coverage, risks, and the action plan for the selected audit.</p>
          <Btn sm kind="ghost" icon="quote" onClick={() => alert('Citation-steal storytelling is retired until backed by real citation observations and competitor evidence records.')}>Citation evidence decision</Btn>
        </div>
      </div>
    );
  }
  window.Compare = Compare;

  // ============================================================ VISIBILITY
  function Visibility({ go, openSteal }) {
    const [running, setRunning] = useState(false);
    const [status, setStatus] = useState('');
    const cited = D.VISIBILITY.filter(v => v.cited).length;
    const steal = openSteal || (() => {});
    const stealable = 0;
    return (
      <div className="js-view">
        <div className="js-pagehead"><div><p className="eyebrow">AI visibility</p><h1>Are you in the <em>answer</em>?</h1>
          <p className="sub">We pose the questions your buyers ask answer engines and check whether you’re mentioned, cited, and ranked.</p></div>
          <Btn icon={running ? null : 'play'} onClick={async () => { if (needAudit()) return setStatus('Run an audit before visibility testing.'); setRunning(true); await runAction('Visibility test', () => window.JS_API.growth.runVisibilityTest(D.AUDIT.id, D.VISIBILITY.map(v => v.query)), setStatus); setRunning(false); }}>{running ? <><span className="js-spin" style={{ marginRight: 8 }} />Testing…</> : 'Run test'}</Btn></div>
        {status && <div className="js-gap sev-low" style={{ marginBottom: 18 }}><p style={{ margin: 0 }}>{status}</p></div>}

        <div className="js-stats" style={{ marginBottom: 20, gridTemplateColumns: 'repeat(3,1fr)' }}>
          <Stat k="Queries tested" v={D.VISIBILITY.length} sub="across 3 engines" icon="bot" />
          <Stat k="Cited" v={cited} sub={'of ' + D.VISIBILITY.length + ' queries'} dir="up" icon="quote" />
          <Stat k="Mentioned" v={D.VISIBILITY.filter(v => v.mentioned).length} sub="incl. uncited" dir="flat" icon="eye" />
        </div>

        <Panel>
          <PanelHead eyebrow="Latest run" title="Query-by-query" desc="Cited means the engine named you as a source. Mentioned-but-uncited is the opportunity.">{stealable > 0 && <span className="js-tag" style={{ color: 'var(--gold)' }}>{stealable} citations to steal</span>}</PanelHead>
          <div className="js-rows">
            {D.VISIBILITY.map((v, i) => {
              const canSteal = false;
              return (
              <div key={i} className={'js-rowcard' + (canSteal ? ' js-steal-row' : '')} style={{ gridTemplateColumns: '1fr auto auto auto', cursor: canSteal ? 'pointer' : 'default' }} onClick={canSteal ? () => steal(v.query) : undefined}>
                <div><div className="rc-title" style={{ fontSize: 14 }}>{v.query}</div><div className="rc-sub">{v.engine} · {v.note}</div></div>
                {v.rank ? <span className="js-scorechip"><span className="sc-ring" style={{ background: 'var(--gold)' }} />#{v.rank}</span> : <span className="js-tag">unranked</span>}
                {v.cited ? <Pill tone="green">Cited</Pill> : v.mentioned ? <Pill tone="amber">Mentioned</Pill> : <Pill tone="coral">Absent</Pill>}
                {canSteal
                  ? <span className="js-steal-cta">Steal the citation <Icon name="arrow" size={14} /></span>
                  : <Icon name="chevronRight" size={16} style={{ color: 'var(--mute)' }} />}
              </div>
              );
            })}
          </div>
        </Panel>
      </div>
    );
  }
  window.Visibility = Visibility;

  // ============================================================ KNOWLEDGE & WIDGET
  function Knowledge({ go }) {
    const [built, setBuilt] = useState(true);
    const [status, setStatus] = useState('');
    const tools = [
      { t: 'Knowledge graph', d: 'A structured map of the client’s entities, services and relationships — the backbone for on-site AI search.', icon: 'layers', stat: 'Backend graph', cta: 'Rebuild graph', run: () => window.JS_API.platform.buildKnowledgeGraph(D.AUDIT.id) },
      { t: 'On-site AI search widget', d: 'An embeddable answer box that uses the graph to respond in the brand voice.', icon: 'bot', stat: 'Backend widget', cta: 'Create widget', run: () => window.JS_API.platform.createWidget(D.AUDIT.id, { name: 'JiffyScore answer widget' }) },
      { t: 'Deployment package', d: 'A static bundle of approved assets, ready to drop onto any host.', icon: 'box', stat: 'Backend deployment', cta: 'Create deployment', run: () => window.JS_API.platform.createDeployment(D.AUDIT.id, { type: 'static-package' }) },
    ];
    return (
      <div className="js-view">
        <div className="js-pagehead"><div><p className="eyebrow">Platform tools</p><h1>Knowledge &amp; <em>widget</em></h1>
          <p className="sub">Build the client’s knowledge graph, ship an on-site AI search widget, and package everything for deployment.</p></div></div>

        <div className="js-grid-3" style={{ marginBottom: 18 }}>
          {tools.map(t => (
            <Panel key={t.t} className="card--hover" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={{ width: 46, height: 46, borderRadius: 13, background: 'var(--surface-2)', border: '1px solid var(--line-soft)', display: 'grid', placeItems: 'center', color: 'var(--gold)' }}><Icon name={t.icon} size={22} /></div>
              <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 19, margin: 0, color: 'var(--ink)' }}>{t.t}</h4>
              <p style={{ fontSize: 13, color: 'var(--ink-soft)', margin: 0, lineHeight: 1.5, flex: 1 }}>{t.d}</p>
              <div className="js-tag">{t.stat}</div>
              <Btn sm kind="ghost" icon="arrow" onClick={() => needAudit() ? setStatus('Run an audit before platform tools.') : runAction(t.t, t.run, setStatus)}>{t.cta}</Btn>
            </Panel>
          ))}
        </div>
        {status && <div className="js-gap sev-low" style={{ marginBottom: 18 }}><p style={{ margin: 0 }}>{status}</p></div>}

        <Panel>
          <PanelHead eyebrow="Graph search" title="Test the knowledge graph" desc="Query the graph the way the on-site widget will." />
          <div className="search-input-wrap" style={{ marginBottom: 16 }}>
            <Icon name="search" className="lead" /><input className="search-input" defaultValue="What hot water system suits a 4-person home?" />
          </div>
          <div className="js-gap sev-low">
            <h4><Icon name="bot" size={16} style={{ color: 'var(--emerald)' }} />Widget answer</h4>
            <p style={{ margin: 0 }}>Create or search the backend knowledge graph to produce a live widget answer. This panel does not render sample answer copy when no graph result is selected.</p>
          </div>
        </Panel>
      </div>
    );
  }
  window.Knowledge = Knowledge;

  // ============================================================ INTEGRATIONS & PUBLISHING
  function Integrations({ role, go }) {
    const [status, setStatus] = useState('');
    const publishableConnections = (D.INTEGRATIONS || []).filter(c => ['wordpress-rest', 'woocommerce-store', 'shopify-admin', 'webflow-cms', 'wix-site', 'squarespace-commerce', 'generic-webhook'].includes(c.type));
    const createGeneric = () => window.JS_API.integrations.create({ type: 'generic-webhook', name: 'Generic webhook', webhookUrl: 'https://example.com/jiffyscore-webhook', status: 'configured' });
    const createWordPress = () => window.JS_API.integrations.create({ type: 'wordpress-rest', name: 'WordPress REST', siteUrl: 'https://example.com', username: 'placeholder', applicationPassword: 'placeholder', status: 'configured' });
    const createWoo = () => window.JS_API.integrations.create({ type: 'woocommerce-store', name: 'WooCommerce store', siteUrl: 'https://example.com', consumerKey: 'placeholder', consumerSecret: 'placeholder', status: 'configured' });
    const createShopify = () => window.JS_API.integrations.create({ type: 'shopify-admin', name: 'Shopify Admin', shop: 'example.myshopify.com', accessToken: 'placeholder', status: 'configured' });
    const createWix = () => window.JS_API.integrations.create({ type: 'wix-site', name: 'Wix site', siteUrl: 'https://example.com', status: 'guided' });
    const createSquarespace = () => window.JS_API.integrations.create({ type: 'squarespace-commerce', name: 'Squarespace commerce', siteUrl: 'https://example.com', status: 'guided' });
    return (
      <div className="js-view">
        <div className="js-pagehead"><div><p className="eyebrow">{role === 'super_admin' ? 'Platform integrations' : 'Integrations & publishing'}</p><h1>Live <em>connections</em></h1>
          <p className="sub">Sync real performance data in, push approved changes out. Secrets are stored server-side and never shown here.</p></div>
          <Btn icon="plus" onClick={() => runAction('Generic webhook connection', createGeneric, setStatus)}>New connection</Btn></div>

        <div className="row-wrap" style={{ marginBottom: 14 }}>
          <Btn sm kind="ghost" icon="code" onClick={() => runAction('WordPress connection', createWordPress, setStatus)}>Add WordPress</Btn>
          <Btn sm kind="ghost" icon="box" onClick={() => runAction('WooCommerce connection', createWoo, setStatus)}>Add WooCommerce</Btn>
          <Btn sm kind="ghost" icon="box" onClick={() => runAction('Shopify connection', createShopify, setStatus)}>Add Shopify</Btn>
          <Btn sm kind="ghost" icon="globe" onClick={() => runAction('Wix connection', createWix, setStatus)}>Add Wix</Btn>
          <Btn sm kind="ghost" icon="globe" onClick={() => runAction('Squarespace connection', createSquarespace, setStatus)}>Add Squarespace</Btn>
          {D.AUDIT?.id && <Btn sm kind="gold" icon="share" onClick={() => runAction('CMS publish', () => window.JS_API.integrations.publish(D.AUDIT.id, { provider: 'generic-webhook', dryRun: true }), setStatus)}>Run publish</Btn>}
        </div>
        {status && <div className="js-gap sev-low" style={{ marginBottom: 18 }}><p style={{ margin: 0 }}>{status}</p></div>}

        <div className="js-grid-2" style={{ marginBottom: 18 }}>
          {D.INTEGRATIONS.length ? D.INTEGRATIONS.map(c => (
            <div key={c.name} className="js-rowcard" style={{ gridTemplateColumns: 'auto 1fr auto', cursor: 'default' }}>
              <div style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--surface-2)', display: 'grid', placeItems: 'center', color: 'var(--gold)', border: '1px solid var(--line-soft)' }}><Icon name={c.kind} size={20} /></div>
              <div><div className="rc-title">{c.name}</div><div className="rc-sub">{c.type} · {c.detail}</div></div>
              {c.status === 'connected' ? <Pill tone="green">Connected</Pill> : c.status === 'attention' ? <Pill tone="amber">Action needed</Pill> : <Pill tone="coral" dot={false}>Off</Pill>}
            </div>
          )) : <EmptyState icon="puzzle" title="No live connections" desc="Create a provider connection to sync evidence or publish approved implementation assets." />}
        </div>

        <div className="js-cols-main">
          <Panel>
            <PanelHead eyebrow="CMS publishing" title="Push approved assets" desc="Dry-run shows the exact diff before anything goes live. Approved-only by default." />
            <div className="field"><label className="field-label">Target connection</label>
              <select className="select">
                {publishableConnections.length
                  ? publishableConnections.map(c => <option key={c.id || c.name}>{c.name} · {c.type}</option>)
                  : <option>No backend publish connection selected</option>}
              </select>
              <span className="field-hint">Wix and Squarespace connections are guided-mode unless direct provider write credentials are configured.</span></div>
            <div className="js-grid-2" style={{ gap: 12 }}>
              <div className="field" style={{ margin: 0 }}><label className="field-label">Mode</label><select className="select"><option>Dry run</option><option>Live publish</option></select></div>
              <div className="field" style={{ margin: 0 }}><label className="field-label">Scope</label><select className="select"><option>Approved only</option><option>Include drafts</option></select></div>
            </div>
            <Btn icon="share" style={{ marginTop: 18 }} onClick={() => D.AUDIT?.id ? runAction('CMS publish', () => window.JS_API.integrations.publish(D.AUDIT.id, { provider: 'generic-webhook', dryRun: true }), setStatus) : setStatus('Run an audit before publishing.')}>Run publish</Btn>
          </Panel>
          <Panel raised>
            <PanelHead title="AI source tracking" desc="Citations earned per engine, trended." />
            <EngineTrends compact />
          </Panel>
        </div>
      </div>
    );
  }
  window.Integrations = Integrations;

  // ============================================================ WHITE-LABEL
  function Whitelabel({ go }) {
    const [color, setColor] = useState('#E8B53C');
    const [status, setStatus] = useState('');
    const colors = ['#E8B53C', '#6FB0FF', '#7BDC8C', '#F08A6A', '#B6F26E'];
    return (
      <div className="js-view">
        <div className="js-pagehead"><div><p className="eyebrow">Brand</p><h1>White-label <em>output</em></h1>
          <p className="sub">Make every report and client portal look like yours. Branding flows into exports, the widget, and the agency report.</p></div>
          <Btn icon="check" onClick={() => runAction('Agency profile', () => window.JS_API.growth.updateAgencyProfile({ primaryColor: color }), setStatus)}>Save profile</Btn></div>
        {status && <div className="js-gap sev-low" style={{ marginBottom: 18 }}><p style={{ margin: 0 }}>{status}</p></div>}

        <div className="js-cols-main">
          <Panel>
            <PanelHead eyebrow="Agency profile" title="Report branding" />
            <div className="js-grid-2" style={{ gap: 14 }}>
              <div className="field" style={{ margin: 0 }}><label className="field-label">Agency name</label><input className="input" defaultValue="Northbeam Studio" /></div>
              <div className="field" style={{ margin: 0 }}><label className="field-label">Product name</label><input className="input" defaultValue="Northbeam Search Score" /></div>
              <div className="field" style={{ margin: 0 }}><label className="field-label">Support email</label><input className="input" defaultValue="hello@northbeam.studio" /></div>
              <div className="field" style={{ margin: 0 }}><label className="field-label">Website</label><input className="input" defaultValue="https://northbeam.studio" /></div>
            </div>
            <div className="field" style={{ marginTop: 14 }}><label className="field-label">Primary color</label>
              <div className="row-wrap">{colors.map(c => <button key={c} onClick={() => setColor(c)} style={{ width: 38, height: 38, borderRadius: 10, background: c, border: color === c ? '2px solid var(--ink)' : '1px solid var(--line)', cursor: 'pointer' }} />)}</div></div>
            <div className="field" style={{ marginTop: 14 }}><label className="field-label">Report footer</label><input className="input" defaultValue="Prepared by Northbeam Studio · Powered by JiffyScore" /></div>
          </Panel>
          <Panel raised>
            <PanelHead title="Preview" />
            <div style={{ background: 'var(--off)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: 22 }}>
              <div className="row" style={{ gap: 10, marginBottom: 16 }}>
                <div style={{ width: 34, height: 34, borderRadius: 9, background: color, display: 'grid', placeItems: 'center', color: 'var(--on-lime)', fontFamily: 'var(--font-display)', fontWeight: 700 }}>N</div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700 }}>Northbeam Search Score</div>
              </div>
              <div className="js-tag" style={{ marginBottom: 6 }}>{D.AUDIT?.clientName || 'Selected client'} · backend report preview</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 48, fontWeight: 700, color: color, lineHeight: 1 }}>71</div>
              <div className="rc-sub" style={{ marginTop: 4 }}>Composite JiffyScore</div>
              <hr className="js-divider" style={{ margin: '16px 0' }} />
              <div className="row-wrap"><span className="pill" style={{ background: 'var(--bg-2)' }}>Glass-box</span><span className="pill" style={{ background: 'var(--bg-2)' }}>6 dimensions</span></div>
            </div>
          </Panel>
        </div>
      </div>
    );
  }
  window.Whitelabel = Whitelabel;

})();
