// SCREEN: AI Visibility (GEO — Generative Engine Optimization)
// Monitor how AI assistants cite AstraReach. Surface intent gaps.

// ---------------------------------------------------------------------------
// MOCK DATA
// ---------------------------------------------------------------------------
const CONTEXT_MOCK = {
  summary: {
    brand_name: 'AstraReach',
    brand_category: 'Agentic Marketing OS',
    brand_value_props: [
      'Unified customer journey graph',
      'AI-powered marketing decisions',
      'Durable memory across sessions',
      'Real-time anomaly detection',
      'Multi-source event ingestion',
    ],
    schema_version: 'v2.1',
    last_updated: '2026-05-04T12:00:00Z',
  },
  performance: {
    query_count: 142,
    avg_visibility_score: 0.67,
    uncited_queries: 23,
    top_queries: [
      { query: 'best marketing attribution tool',     visibility: 82, cited: true,  sources_count: 4, last_detected: '2h ago' },
      { query: 'customer journey analytics software', visibility: 71, cited: true,  sources_count: 3, last_detected: '4h ago' },
      { query: 'agentic marketing platform',          visibility: 88, cited: true,  sources_count: 6, last_detected: '30m ago' },
      { query: 'replace segment CDP',                 visibility: 45, cited: true,  sources_count: 2, last_detected: '8h ago' },
      { query: 'AI marketing OS',                     visibility: 61, cited: false, sources_count: 0, last_detected: '1d ago' },
    ],
  },
  intentGaps: {
    gaps: [
      { query: 'what is agentic marketing',        gap_type: 'missing_citation',     suggested_content: 'Create definitional blog post',  priority: 'HIGH' },
      { query: 'AI marketing platform comparison', gap_type: 'competitor_dominated', suggested_content: 'Update comparison page',          priority: 'HIGH' },
      { query: 'marketing attribution models',     gap_type: 'weak_citation',        suggested_content: 'Strengthen docs with examples',  priority: 'MED'  },
      { query: 'CDP vs journey analytics',         gap_type: 'missing_citation',     suggested_content: 'New landing page needed',         priority: 'MED'  },
      { query: 'customer data platform pricing',   gap_type: 'weak_citation',        suggested_content: 'Add pricing comparison content',  priority: 'LOW'  },
    ],
    total_gaps: 5,
  },
  platforms: [
    { name: 'ChatGPT',            score: 72, freq: 'frequent',      lastSeen: '2h ago',  color: 'var(--emerald)' },
    { name: 'Perplexity',         score: 81, freq: 'very frequent', lastSeen: '45m ago', color: 'var(--emerald)' },
    { name: 'Google AI Overview', score: 54, freq: 'occasional',    lastSeen: '6h ago',  color: 'var(--amber)'   },
    { name: 'Claude',             score: 68, freq: 'frequent',      lastSeen: '1h ago',  color: 'var(--emerald)' },
  ],
};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

// Grade letter from 0–100 score
const scoreGrade = (s) => s >= 91 ? 'A+' : s >= 71 ? 'A' : s >= 51 ? 'B' : s >= 31 ? 'C' : 'D';

// Context label from 0–100 score
const scoreLabel = (s) => s > 90 ? 'Dominant' : s > 70 ? 'Strong' : s > 40 ? 'Moderate' : 'Low';

// Color from 0–100 score
const scoreColor = (s) => s > 70 ? 'var(--emerald)' : s > 40 ? 'var(--amber)' : 'var(--rose)';

// Gap type display config
const GAP_TYPE_CONFIG = {
  missing_citation:     { color: 'var(--rose)',   label: 'Missing Citation' },
  weak_citation:        { color: 'var(--amber)',  label: 'Weak Citation' },
  competitor_dominated: { color: '#fb923c',       label: 'Competitor Dominated' },
};

// Priority badge
const PriorityBadge = ({ priority }) => {
  const map = {
    HIGH: { bg: 'rgba(244,63,94,0.12)',   color: 'var(--rose)',   border: 'rgba(244,63,94,0.3)' },
    MED:  { bg: 'rgba(245,158,11,0.12)',  color: 'var(--amber)',  border: 'rgba(245,158,11,0.3)' },
    LOW:  { bg: 'rgba(107,116,137,0.14)', color: 'var(--text-3)', border: 'rgba(107,116,137,0.28)' },
  };
  const s = map[priority] || map.LOW;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      fontSize: 9, fontWeight: 700, letterSpacing: '0.07em',
      color: s.color, background: s.bg,
      border: `1px solid ${s.border}`, borderRadius: 4,
      padding: '2px 7px',
    }}>{priority}</span>
  );
};

// Circular SVG gauge showing a 270° arc
const ScoreGauge = ({ score }) => {
  const r    = 56;
  const circ = 2 * Math.PI * r;
  const arc  = circ * 0.75;           // 270° of the full circle
  const fill = arc * (score / 100);
  const color = scoreColor(score);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
      <div style={{ position: 'relative', width: 160, height: 160 }}>
        {/* SVG rotated so the gap faces bottom-center */}
        <svg width="160" height="160" viewBox="0 0 160 160"
          style={{ transform: 'rotate(135deg)', display: 'block' }}>
          {/* Background track */}
          <circle cx="80" cy="80" r={r} fill="none"
            stroke="var(--bg-3)" strokeWidth="12"
            strokeDasharray={`${arc} ${circ}`} strokeLinecap="round" />
          {/* Filled arc */}
          <circle cx="80" cy="80" r={r} fill="none"
            stroke={color} strokeWidth="12"
            strokeDasharray={`${fill} ${circ}`} strokeLinecap="round"
            style={{ filter: `drop-shadow(0 0 8px ${color})`, transition: 'stroke-dasharray .6s ease' }} />
        </svg>
        {/* Centred score text */}
        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          gap: 1,
        }}>
          <div style={{ fontSize: 40, fontWeight: 800, letterSpacing: '-0.04em', color, lineHeight: 1 }}>
            {score}
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-3)', fontFamily: 'var(--mono)' }}>/100</div>
        </div>
      </div>
      {/* Grade badge + label below gauge */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{
          fontSize: 18, fontWeight: 800, color,
          background: color + '18', border: `1px solid ${color}44`,
          borderRadius: 7, padding: '2px 12px',
        }}>{scoreGrade(score)}</span>
        <span style={{ fontSize: 14, color: 'var(--text-2)', fontWeight: 500 }}>{scoreLabel(score)}</span>
      </div>
    </div>
  );
};

// ---------------------------------------------------------------------------
// ContextScreen
// ---------------------------------------------------------------------------
const ContextScreen = () => {
  // State: loaded from API, fall back to MOCK on error
  const [summary,    setSummary]    = React.useState(CONTEXT_MOCK.summary);
  const [perf,       setPerf]       = React.useState(CONTEXT_MOCK.performance);
  const [gaps,       setGaps]       = React.useState(CONTEXT_MOCK.intentGaps);
  const [platforms,  setPlatforms]  = React.useState(CONTEXT_MOCK.platforms);
  const [rawSummary, setRawSummary] = React.useState(null);

  // JSON preview toggle
  const [jsonExpanded, setJsonExpanded] = React.useState(false);

  // Toast for "Create Content" CTA
  const [toast, setToast] = React.useState(null);

  // ---------------------------------------------------------------------------
  // Fetch from API on mount; keep MOCK data silently on any error
  // ---------------------------------------------------------------------------
  React.useEffect(() => {
    arFetch('/v1/context/summary')
      .then(data => { if (data && !data.error) { setSummary(data); setRawSummary(data); } })
      .catch(() => {});

    arFetch('/v1/context/performance')
      .then(data => {
        if (data && !data.error) {
          setPerf(data);
          if (data.platform_breakdown && Object.keys(data.platform_breakdown).length > 0) {
            setPlatforms(data.platform_breakdown);
          }
        }
      })
      .catch(() => {});

    arFetch('/v1/context/intent-gaps')
      .then(data => { if (data && !data.error) setGaps(data); })
      .catch(() => {});
  }, []);

  // ---------------------------------------------------------------------------
  // Derived display values
  // ---------------------------------------------------------------------------
  const visScore    = Math.round((perf.avg_visibility_score || 0) * 100);
  const totalQ      = perf.query_count || 0;
  const citedPct    = totalQ > 0
    ? Math.round(((totalQ - perf.uncited_queries) / totalQ) * 100)
    : 0;

  // ---------------------------------------------------------------------------
  // Toast helper
  // ---------------------------------------------------------------------------
  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 2600);
  };

  // ---------------------------------------------------------------------------
  // Render
  // ---------------------------------------------------------------------------
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>

      {/* ── Floating toast ── */}
      {toast && (
        <div style={{
          position: 'fixed', bottom: 28, left: '50%', transform: 'translateX(-50%)',
          background: 'var(--bg-3)', border: '1px solid var(--border)',
          borderRadius: 10, padding: '10px 22px',
          fontSize: 13, color: 'var(--text-1)',
          boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
          zIndex: 500, display: 'flex', alignItems: 'center', gap: 8,
          pointerEvents: 'none',
        }}>
          <span style={{ color: 'var(--emerald)' }}>✓</span> {toast}
        </div>
      )}

      {/* ── Page header ── */}
      <div>
        <div style={{
          fontSize: 11, color: 'var(--text-3)', fontFamily: 'var(--mono)',
          textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6,
        }}>Platform / AI Visibility</div>
        <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em' }}>AI Visibility</div>
        <div style={{ fontSize: 13, color: 'var(--text-3)', marginTop: 2 }}>
          Monitor how AI assistants (ChatGPT, Perplexity, Google AI Overview, Claude) cite AstraReach.
          Optimize for generative engine search.
        </div>
      </div>

      {/* ── Section 1: Visibility Score Hero ── */}
      <div className="card" style={{
        background: 'linear-gradient(135deg, rgba(139,92,246,0.07) 0%, var(--bg-2) 60%)',
        border: '1px solid rgba(139,92,246,0.25)',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          gap: 56, flexWrap: 'wrap', padding: '8px 0 12px',
        }}>
          {/* Gauge */}
          <ScoreGauge score={visScore} />

          {/* Sub-stats column */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ fontSize: 13, color: 'var(--text-3)', marginBottom: 4 }}>
              Across <strong style={{ color: 'var(--text-1)' }}>{totalQ}</strong> tracked AI queries
            </div>

            {[
              {
                label: 'Cited Queries',
                value: citedPct + '%',
                sub: `${totalQ - perf.uncited_queries} of ${totalQ}`,
                color: 'var(--emerald)',
              },
              {
                label: 'Uncited Queries',
                value: perf.uncited_queries,
                sub: 'need content action',
                color: 'var(--rose)',
              },
              {
                label: 'Schema Version',
                value: summary.schema_version,
                sub: 'structured data active',
                color: 'var(--cyan)',
                mono: true,
              },
            ].map(({ label, value, sub, color, mono }) => (
              <div key={label} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                gap: 48, padding: '9px 14px',
                background: 'var(--bg-1)', border: '1px solid var(--border)',
                borderRadius: 8, minWidth: 290,
              }}>
                <span style={{ fontSize: 12, color: 'var(--text-3)' }}>{label}</span>
                <div style={{ textAlign: 'right' }}>
                  <div style={{
                    fontSize: 19, fontWeight: 700, color,
                    fontFamily: mono ? 'var(--mono)' : 'inherit',
                    lineHeight: 1.1,
                  }}>{value}</div>
                  <div style={{ fontSize: 10, color: 'var(--text-4)', marginTop: 1 }}>{sub}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ── Section 2: AI Platform Breakdown (4 cards) ── */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {(Array.isArray(platforms) ? platforms : Object.values(platforms)).map(pl => (
          <div key={pl.name} className="card" style={{ padding: 16 }}>

            {/* Platform name + status dot */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              <span style={{
                width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
                background: pl.color,
                boxShadow: `0 0 6px ${pl.color}`,
              }} />
              <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-1)', lineHeight: 1.2 }}>
                {pl.name}
              </span>
            </div>

            {/* Score bar + number */}
            <div style={{ marginBottom: 10 }}>
              <div style={{ height: 5, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden', marginBottom: 5 }}>
                <div style={{
                  width: pl.score + '%', height: '100%',
                  background: pl.color, borderRadius: 3,
                  transition: 'width .5s ease',
                }} />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span style={{ fontSize: 24, fontWeight: 700, color: pl.color, letterSpacing: '-0.02em' }}>
                  {pl.score}
                </span>
                <span style={{ fontSize: 10, color: 'var(--text-3)', fontFamily: 'var(--mono)' }}>/100</span>
              </div>
            </div>

            {/* Meta rows */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11 }}>
                <span style={{ color: 'var(--text-3)' }}>Citation freq.</span>
                <span style={{ color: 'var(--text-2)', fontWeight: 500 }}>{pl.freq}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11 }}>
                <span style={{ color: 'var(--text-3)' }}>Last seen</span>
                <span style={{ color: 'var(--text-2)' }}>{pl.lastSeen}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Section 3 + 4: Queries Table (55%) | Intent Gaps (45%) ── */}
      <div style={{ display: 'grid', gridTemplateColumns: '55fr 45fr', gap: 14 }}>

        {/* Top Performing Queries */}
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--border)' }}>
            <div className="card-title">Top Performing Queries</div>
            <div className="card-sub">{perf.top_queries.length} of {totalQ} tracked queries</div>
          </div>

          <div style={{ overflowX: 'auto' }}>
            <table className="data-table">
              <thead>
                <tr>
                  <th>Query</th>
                  <th style={{ textAlign: 'center' }}>Visibility</th>
                  <th style={{ textAlign: 'center' }}>Cited</th>
                  <th style={{ textAlign: 'center' }}>Sources</th>
                  <th>Last Detected</th>
                </tr>
              </thead>
              <tbody>
                {perf.top_queries.map((q, i) => (
                  <tr key={i} style={{
                    background: !q.cited ? 'rgba(244,63,94,0.04)' : undefined,
                  }}>
                    {/* Query text (truncated + tooltip) */}
                    <td style={{
                      fontSize: 12, color: 'var(--text-1)', fontWeight: 500,
                      maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }} title={q.query}>
                      {q.query}
                    </td>

                    {/* Visibility score + mini bar */}
                    <td style={{ textAlign: 'center' }}>
                      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3 }}>
                        <span style={{
                          fontFamily: 'var(--mono)', fontSize: 13, fontWeight: 700,
                          color: scoreColor(q.visibility),
                        }}>{q.visibility}</span>
                        <div style={{ width: 48, height: 3, background: 'var(--bg-3)', borderRadius: 2, overflow: 'hidden' }}>
                          <div style={{
                            width: q.visibility + '%', height: '100%',
                            background: scoreColor(q.visibility),
                          }} />
                        </div>
                      </div>
                    </td>

                    {/* Cited checkmark */}
                    <td style={{ textAlign: 'center', fontSize: 15 }}>
                      <span style={{ color: q.cited ? 'var(--emerald)' : 'var(--rose)' }}>
                        {q.cited ? '✓' : '✗'}
                      </span>
                    </td>

                    {/* Sources count */}
                    <td style={{ textAlign: 'center', fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--text-2)' }}>
                      {q.sources_count}
                    </td>

                    {/* Last detected */}
                    <td style={{ fontSize: 11, color: 'var(--text-3)' }}>
                      {q.last_detected}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Intent Gaps */}
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--border)' }}>
            <div className="card-title">Intent Gaps</div>
            <div className="card-sub">
              {gaps.total_gaps} gaps ·{' '}
              <span style={{ color: 'var(--rose)' }}>
                {gaps.gaps.filter(g => g.priority === 'HIGH').length} high priority
              </span>
            </div>
          </div>

          <div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {gaps.gaps.map((gap, i) => {
              const tc = GAP_TYPE_CONFIG[gap.gap_type] || GAP_TYPE_CONFIG.weak_citation;
              return (
                <div key={i} style={{
                  padding: 12,
                  background: 'var(--bg-1)', border: '1px solid var(--border)',
                  borderRadius: 8, borderLeft: `3px solid ${tc.color}`,
                }}>
                  {/* Priority + gap type badges */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6, flexWrap: 'wrap' }}>
                    <PriorityBadge priority={gap.priority} />
                    <span style={{
                      fontSize: 10, color: tc.color,
                      background: tc.color + '14',
                      border: `1px solid ${tc.color}30`,
                      borderRadius: 4, padding: '2px 7px', fontWeight: 500,
                    }}>{tc.label}</span>
                  </div>

                  {/* Query text */}
                  <div style={{
                    fontSize: 12, fontWeight: 600, color: 'var(--text-1)',
                    fontStyle: 'italic', marginBottom: 4, lineHeight: 1.4,
                  }}>"{gap.query}"</div>

                  {/* Suggested action */}
                  <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 8 }}>
                    → {gap.suggested_content}
                  </div>

                  {/* Create Content CTA */}
                  <button
                    className="btn"
                    style={{
                      fontSize: 11, padding: '4px 10px',
                      color: 'var(--cyan)', borderColor: 'rgba(34,211,238,0.3)',
                      width: '100%', justifyContent: 'center',
                    }}
                    onClick={() => {
                      if (!window.AR_NAVIGATE) return;
                      const CONTENT_DEST = {
                        competitor_dominated: 'organic',
                        missing_citation: 'creator',
                        weak_citation: 'creator',
                      };
                      const dest = CONTENT_DEST[gap.gap_type] || 'video';
                      window.AR_NAVIGATE(dest);
                    }}>
                    <Icon name="plus" size={11} /> Create Content
                  </button>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* ── Section 5: Context Broadcasting Status (bottom strip) ── */}
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>

        {/* Status strip */}
        <div style={{
          padding: '12px 16px',
          display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap',
        }}>
          {/* Live pulse */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <span className="dot pulse" style={{
              width: 8, height: 8,
              background: 'var(--emerald)',
              boxShadow: '0 0 8px var(--emerald)',
            }} />
            <span style={{ fontSize: 12, color: 'var(--emerald)', fontWeight: 500 }}>
              Broadcasting Active
            </span>
          </div>

          <div style={{ width: 1, height: 16, background: 'var(--border)', flexShrink: 0 }} />

          {/* Schema version */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-3)' }}>
            Schema
            <span style={{
              fontFamily: 'var(--mono)', fontSize: 11,
              color: 'var(--cyan)',
              background: 'rgba(34,211,238,0.1)', border: '1px solid rgba(34,211,238,0.25)',
              borderRadius: 4, padding: '1px 7px',
            }}>{summary.schema_version}</span>
          </div>

          <div style={{ width: 1, height: 16, background: 'var(--border)', flexShrink: 0 }} />

          {/* Last updated */}
          <div style={{ fontSize: 12, color: 'var(--text-3)' }}>
            Updated:{' '}
            <span style={{ color: 'var(--text-2)' }}>
              {summary.last_updated
                ? new Date(summary.last_updated).toLocaleString('en-US', {
                    month: 'short', day: 'numeric',
                    hour: 'numeric', minute: '2-digit',
                  })
                : '—'}
            </span>
          </div>

          <div style={{ width: 1, height: 16, background: 'var(--border)', flexShrink: 0 }} />

          {/* Endpoint health */}
          <div style={{ fontSize: 12, color: 'var(--text-3)' }}>
            <span className="mono" style={{ fontSize: 11 }}>GET /v1/context/summary</span>
            {'  '}
            <span style={{ color: 'var(--emerald)' }}>● Healthy</span>
          </div>

          {/* Info note (right-aligned) */}
          <div style={{
            marginLeft: 'auto', fontSize: 11, color: 'var(--text-4)',
            maxWidth: 260, textAlign: 'right', lineHeight: 1.4,
          }}>
            These 3 endpoints are publicly accessible to AI web crawlers and assistants
          </div>

          {/* JSON preview toggle */}
          <button
            className="btn ghost"
            style={{ fontSize: 11, padding: '4px 10px', borderColor: 'var(--border)', flexShrink: 0 }}
            onClick={() => setJsonExpanded(v => !v)}>
            {jsonExpanded ? '▲ Hide' : '▼ What AI assistants see'}
          </button>
        </div>

        {/* Collapsible raw JSON preview */}
        {jsonExpanded && (
          <div style={{ borderTop: '1px solid var(--border)' }}>
            <div style={{
              padding: '6px 16px', background: 'var(--bg-3)',
              fontSize: 10, color: 'var(--text-3)', fontFamily: 'var(--mono)',
            }}>
              GET /v1/context/summary — response visible to AI crawlers
            </div>
            <div className="json-view" style={{
              fontSize: 11, lineHeight: 1.65,
              maxHeight: 280, overflowY: 'auto',
              borderRadius: 0,
            }}>
              {rawSummary ? JSON.stringify(rawSummary, null, 2) : JSON.stringify({
                brand_name: summary.brand_name,
                brand_category: summary.brand_category,
                brand_value_props: summary.brand_value_props,
                schema_version: summary.schema_version,
              }, null, 2)}
            </div>
          </div>
        )}
      </div>

    </div>
  );
};

window.ContextScreen = ContextScreen;
