// GEO — Generative Engine Optimization
// Tracks brand visibility and citation rates across AI-powered search engines

const GEOScreen = () => {
  const [scanning, setScanning] = React.useState(false);
  const [scanToast, setScanToast] = React.useState(null);
  const [lastScanned, setLastScanned] = React.useState('2 hours ago');
  const [activeTab, setActiveTab] = React.useState('visibility');

  // ── Mock data ─────────────────────────────────────────────────────────────────

  const ENGINES = [
    { id: 'chatgpt',    label: 'ChatGPT',    icon: '🟢', score: 68, trend: +4,  queries: 142, citations: 97,  },
    { id: 'perplexity', label: 'Perplexity', icon: '🔵', score: 74, trend: +11, queries: 89,  citations: 66,  },
    { id: 'gemini',     label: 'Gemini',     icon: '🔶', score: 52, trend: -3,  queries: 114, citations: 59,  },
    { id: 'copilot',    label: 'Copilot',    icon: '⬡',  score: 61, trend: +2,  queries: 76,  citations: 46,  },
    { id: 'claude',     label: 'Claude',     icon: '🟠', score: 71, trend: +8,  queries: 63,  citations: 45,  },
  ];

  const QUERIES = [
    { query: 'best customer journey analytics platform 2026', cited: true,  engines: ['chatgpt','perplexity','claude'], volume: 'high' },
    { query: 'agentic marketing software',                    cited: true,  engines: ['perplexity','chatgpt'],          volume: 'high' },
    { query: 'identity resolution for marketers',             cited: true,  engines: ['gemini','copilot','perplexity'], volume: 'med'  },
    { query: 'real-time event ingestion tools',               cited: false, engines: [],                                volume: 'med'  },
    { query: 'AI marketing decision support',                 cited: true,  engines: ['claude','chatgpt'],              volume: 'high' },
    { query: 'markov chain journey mapping tool',             cited: false, engines: [],                                volume: 'low'  },
    { query: 'marketing data unification platform',           cited: true,  engines: ['perplexity'],                   volume: 'high' },
    { query: 'customer data platform vs marketing OS',        cited: false, engines: [],                                volume: 'high' },
    { query: 'anomaly detection marketing analytics',         cited: true,  engines: ['gemini'],                       volume: 'med'  },
    { query: 'AI-powered audience segmentation 2026',         cited: false, engines: [],                                volume: 'high' },
  ];

  const COMPETITORS = [
    { name: 'AstraReach', avg: 65, chatgpt: 68, perplexity: 74, gemini: 52, copilot: 61, claude: 71, isUs: true  },
    { name: 'Segment',    avg: 78, chatgpt: 82, perplexity: 75, gemini: 79, copilot: 71, claude: 83, isUs: false },
    { name: 'Amplitude',  avg: 71, chatgpt: 74, perplexity: 70, gemini: 68, copilot: 72, claude: 71, isUs: false },
    { name: 'Mixpanel',   avg: 64, chatgpt: 66, perplexity: 63, gemini: 65, copilot: 60, claude: 66, isUs: false },
    { name: 'mParticle',  avg: 43, chatgpt: 45, perplexity: 40, gemini: 44, copilot: 41, claude: 45, isUs: false },
  ];

  const RECS = [
    {
      priority: 'high', engine: 'Gemini', impact: '+16 pts',
      title: 'Add structured FAQ schema to /docs/journey-maps',
      detail: 'Gemini cites structured Q&A pages 2.4× more than prose docs. Adding FAQ schema to your journey map documentation is estimated to increase citation rate from 52% → ~68%.',
    },
    {
      priority: 'high', engine: 'All', impact: '+new query',
      title: 'Publish comparison page: Marketing OS vs CDP',
      detail: '"Customer data platform vs marketing OS" is a high-volume uncited query. A dedicated comparison page citing first-party data would capture this query across all 5 engines.',
    },
    {
      priority: 'med', engine: 'ChatGPT', impact: '+8 pts',
      title: 'Add citations to your /blog/markov-journey-mapping post',
      detail: 'ChatGPT prefers content that references academic or industry sources. Adding 3–5 references to your Markov chain post would improve citation rates for related queries.',
    },
    {
      priority: 'med', engine: 'Copilot', impact: '+5 pts',
      title: 'Register AstraReach on Bing Webmaster Tools',
      detail: 'Copilot pulls heavily from Bing index signals. Verifying your domain and submitting a sitemap correlates directly with Copilot citation rates.',
    },
    {
      priority: 'low', engine: 'Perplexity', impact: '+3 pts',
      title: 'Increase update cadence on /changelog',
      detail: 'Perplexity heavily weights recency. Publishing changelog entries ≥2× per week correlates with 18% higher citation rates for product queries.',
    },
  ];

  // ── KPIs ─────────────────────────────────────────────────────────────────────

  const avgScore  = Math.round(ENGINES.reduce((s, e) => s + e.score, 0) / ENGINES.length);
  const totalCite = ENGINES.reduce((s, e) => s + e.citations, 0);
  const citedQ    = QUERIES.filter(q => q.cited).length;

  // ── Run scan ──────────────────────────────────────────────────────────────────

  const runScan = () => {
    setScanning(true);
    arFetch('/v1/geo/scan', { method: 'POST' })
      .then(() => { setLastScanned('just now'); setScanToast('GEO scan complete — visibility data refreshed'); })
      .catch(() => { setLastScanned('just now'); setScanToast('Demo mode — GEO scan simulated across 5 AI engines'); })
      .finally(() => { setScanning(false); setTimeout(() => setScanToast(null), 3500); });
  };

  // ── Small components ──────────────────────────────────────────────────────────

  const ScoreBar = ({ score, width }) => (
    <div style={{ width: width || '100%', height: 6, background: 'var(--surface-2)', borderRadius: 3, overflow: 'hidden' }}>
      <div style={{
        width: `${score}%`, height: '100%', borderRadius: 3,
        background: score >= 70 ? '#10B981' : score >= 55 ? '#F59E0B' : '#F43F5E',
        transition: 'width 0.4s ease',
      }} />
    </div>
  );

  const Trend = ({ val }) => (
    <span style={{ fontSize: 11, fontWeight: 600, color: val >= 0 ? '#10B981' : '#F43F5E' }}>
      {val >= 0 ? '↑' : '↓'}{Math.abs(val)}pp
    </span>
  );

  const PBadge = ({ p }) => {
    const cfg = { high: ['#F43F5E','rgba(244,63,94,0.1)'], med: ['#F59E0B','rgba(245,158,11,0.1)'], low: ['#6B7489','rgba(107,116,137,0.1)'] };
    const [c, bg] = cfg[p] || cfg.low;
    return <span style={{ fontSize: 10, fontWeight: 700, color: c, background: bg, border: `1px solid ${c}40`, borderRadius: 4, padding: '2px 7px', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{p}</span>;
  };

  // ── Render ────────────────────────────────────────────────────────────────────

  return (
    <div style={{ padding: '24px 28px', maxWidth: 1100, color: 'var(--text-1)' }}>

      {/* Spin keyframe */}
      <style>{`@keyframes geo-spin { to { transform: rotate(360deg); } }`}</style>

      {/* Toast */}
      {scanToast && (
        <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 2000, background: 'rgba(16,185,129,0.92)', color: '#fff', padding: '10px 18px', borderRadius: 8, fontSize: 13, fontWeight: 500, boxShadow: '0 4px 20px rgba(0,0,0,0.35)' }}>
          {scanToast}
        </div>
      )}

      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 24 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
            <h1 style={{ fontSize: 20, fontWeight: 700, margin: 0 }}>Generative Engine Optimization</h1>
            <span style={{ fontSize: 11, fontWeight: 700, background: 'rgba(6,182,212,0.15)', color: '#06B6D4', border: '1px solid rgba(6,182,212,0.3)', borderRadius: 4, padding: '2px 8px', letterSpacing: '0.04em' }}>BETA</span>
          </div>
          <p style={{ fontSize: 13, color: 'var(--text-3)', margin: 0 }}>
            Monitor brand citation rates across ChatGPT, Perplexity, Gemini, Copilot, and Claude.
            <span style={{ color: 'var(--text-4)', marginLeft: 8, fontSize: 11 }}>Last scanned {lastScanned}</span>
          </p>
        </div>
        <button className="btn primary" onClick={runScan} disabled={scanning} style={{ opacity: scanning ? 0.7 : 1, cursor: scanning ? 'not-allowed' : 'pointer', flexShrink: 0 }}>
          {scanning
            ? <span style={{ width: 13, height: 13, border: '2px solid rgba(255,255,255,0.3)', borderTopColor: '#fff', borderRadius: '50%', display: 'inline-block', animation: 'geo-spin 0.7s linear infinite' }} />
            : <Icon name="refresh" size={13} />
          }
          {scanning ? 'Scanning…' : 'Run Scan'}
        </button>
      </div>

      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 24 }}>
        {[
          { label: 'Avg Visibility Score', value: `${avgScore}%`, sub: 'across 5 AI engines',        color: avgScore >= 70 ? '#10B981' : '#F59E0B' },
          { label: 'Citations This Week',  value: totalCite,       sub: '+23 vs last week',           color: '#8B5CF6' },
          { label: 'Queries Tracked',      value: QUERIES.length,  sub: `${citedQ} cited, ${QUERIES.length - citedQ} gaps`, color: '#06B6D4' },
          { label: 'Competitors Tracked',  value: COMPETITORS.length - 1, sub: 'Segment leads at 78%', color: 'var(--text-3)' },
        ].map(k => (
          <div key={k.label} className="card" style={{ padding: '16px 18px' }}>
            <div style={{ fontSize: 11, color: 'var(--text-4)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6 }}>{k.label}</div>
            <div style={{ fontSize: 26, fontWeight: 700, color: k.color, marginBottom: 2 }}>{k.value}</div>
            <div style={{ fontSize: 11, color: 'var(--text-4)' }}>{k.sub}</div>
          </div>
        ))}
      </div>

      {/* Tab strip */}
      <div style={{ display: 'flex', borderBottom: '1px solid var(--border)', marginBottom: 20 }}>
        {[
          { id: 'visibility',      label: 'Engine Visibility'     },
          { id: 'queries',         label: 'Query Tracking'        },
          { id: 'competitors',     label: 'Competitor Benchmarks' },
          { id: 'recommendations', label: 'Recommendations'       },
        ].map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)} style={{
            padding: '8px 16px', fontSize: 13, fontWeight: 500, background: 'none', border: 'none',
            borderBottom: activeTab === t.id ? '2px solid var(--accent)' : '2px solid transparent',
            color: activeTab === t.id ? 'var(--text-1)' : 'var(--text-3)',
            cursor: 'pointer', marginBottom: -1,
          }}>{t.label}</button>
        ))}
      </div>

      {/* ── Engine Visibility ─────────────────────────────────────────────────── */}
      {activeTab === 'visibility' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 12 }}>
          {ENGINES.map(eng => (
            <div key={eng.id} className="card" style={{ padding: '18px 20px' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 18 }}>{eng.icon}</span>
                  <span style={{ fontWeight: 600, fontSize: 14 }}>{eng.label}</span>
                </div>
                <Trend val={eng.trend} />
              </div>
              <div style={{ fontSize: 32, fontWeight: 700, color: eng.score >= 70 ? '#10B981' : eng.score >= 55 ? '#F59E0B' : '#F43F5E', marginBottom: 8 }}>
                {eng.score}<span style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-4)' }}>%</span>
              </div>
              <ScoreBar score={eng.score} />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 14 }}>
                <div style={{ background: 'var(--surface-2)', borderRadius: 6, padding: '7px 10px' }}>
                  <div style={{ fontSize: 10, color: 'var(--text-4)', marginBottom: 2 }}>QUERIES</div>
                  <div style={{ fontSize: 16, fontWeight: 600 }}>{eng.queries}</div>
                </div>
                <div style={{ background: 'var(--surface-2)', borderRadius: 6, padding: '7px 10px' }}>
                  <div style={{ fontSize: 10, color: 'var(--text-4)', marginBottom: 2 }}>CITATIONS</div>
                  <div style={{ fontSize: 16, fontWeight: 600, color: '#10B981' }}>{eng.citations}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* ── Query Tracking ────────────────────────────────────────────────────── */}
      {activeTab === 'queries' && (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 80px 200px 70px', borderBottom: '1px solid var(--border)', padding: '9px 16px' }}>
            {['Query', 'Volume', 'Cited By', 'Status'].map(h => (
              <div key={h} style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-4)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{h}</div>
            ))}
          </div>
          {QUERIES.map((q, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 80px 200px 70px', padding: '11px 16px', borderBottom: '1px solid var(--border)', alignItems: 'center' }}>
              <div style={{ fontSize: 13, paddingRight: 12 }}>{q.query}</div>
              <div>
                <span style={{
                  fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 4, textTransform: 'uppercase', letterSpacing: '0.04em',
                  background: q.volume === 'high' ? 'rgba(139,92,246,0.12)' : q.volume === 'med' ? 'rgba(245,158,11,0.1)' : 'var(--surface-2)',
                  color: q.volume === 'high' ? '#c4b5fd' : q.volume === 'med' ? '#F59E0B' : 'var(--text-4)',
                }}>{q.volume}</span>
              </div>
              <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', alignItems: 'center' }}>
                {q.cited
                  ? q.engines.map(eid => {
                      const e = ENGINES.find(x => x.id === eid);
                      return <span key={eid} title={e?.label} style={{ fontSize: 15 }}>{e?.icon}</span>;
                    })
                  : <span style={{ fontSize: 11, color: 'var(--text-4)' }}>—</span>
                }
              </div>
              <div>
                {q.cited
                  ? <span style={{ fontSize: 11, fontWeight: 600, color: '#10B981' }}>✓ Cited</span>
                  : <span style={{ fontSize: 11, fontWeight: 600, color: '#F43F5E' }}>✗ Gap</span>
                }
              </div>
            </div>
          ))}
        </div>
      )}

      {/* ── Competitor Benchmarks ─────────────────────────────────────────────── */}
      {activeTab === 'competitors' && (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '130px 70px 90px 100px 80px 80px 80px', borderBottom: '1px solid var(--border)', padding: '9px 16px' }}>
            {['Brand', 'Avg', 'ChatGPT', 'Perplexity', 'Gemini', 'Copilot', 'Claude'].map(h => (
              <div key={h} style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-4)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{h}</div>
            ))}
          </div>
          {COMPETITORS.map(c => (
            <div key={c.name} style={{
              display: 'grid', gridTemplateColumns: '130px 70px 90px 100px 80px 80px 80px',
              padding: '12px 16px', borderBottom: '1px solid var(--border)', alignItems: 'center',
              background: c.isUs ? 'rgba(139,92,246,0.04)' : 'transparent',
            }}>
              <div style={{ fontWeight: c.isUs ? 700 : 500, fontSize: 13, display: 'flex', alignItems: 'center', gap: 6 }}>
                {c.isUs && <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', display: 'inline-block', flexShrink: 0 }} />}
                {c.name}
              </div>
              {[c.avg, c.chatgpt, c.perplexity, c.gemini, c.copilot, c.claude].map((v, i) => (
                <div key={i}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: v >= 70 ? '#10B981' : v >= 55 ? '#F59E0B' : '#F43F5E', marginBottom: 3 }}>{v}%</div>
                  <ScoreBar score={v} width={52} />
                </div>
              ))}
            </div>
          ))}
        </div>
      )}

      {/* ── Recommendations ───────────────────────────────────────────────────── */}
      {activeTab === 'recommendations' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {RECS.map((r, i) => (
            <div key={i} className="card" style={{ padding: '16px 20px', display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, alignItems: 'start' }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                  <PBadge p={r.priority} />
                  <span style={{ fontSize: 11, color: 'var(--text-4)', background: 'var(--surface-2)', padding: '2px 8px', borderRadius: 4 }}>{r.engine}</span>
                </div>
                <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 5 }}>{r.title}</div>
                <div style={{ fontSize: 13, color: 'var(--text-3)', lineHeight: 1.55 }}>{r.detail}</div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <div style={{ fontSize: 11, color: 'var(--text-4)', marginBottom: 2 }}>Est. impact</div>
                <div style={{ fontSize: 16, fontWeight: 700, color: '#10B981' }}>{r.impact}</div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

window.GEOScreen = GEOScreen;
