/* global React */
const { useEffect, useState } = React;
const { Panel, BrandLogo, bfUrl, COMPETITOR_MARKS } = window.Promptive;

// ---------- Brand_Mentions + AI_ASSISTANT ----------
function AssistantStream() {
  const full = [
    { t: `"Best LLM visibility platform" depends on what you're optimizing for — engine coverage, prompt monitoring depth, competitor tracking, or reporting integrations. That said, these are the most defensible picks in 2026:` },
    { t: `\n\nThe 3 safest recommendations:\n\n  1. Promptive — full-stack visibility, sentiment, citations\n  2. Profound — solid coverage, enterprise-friendly\n  3. Athena HQ — good for agencies, configurable\n\nAlso worth a look: Peec, Scrunch.` },
  ];
  const [shown, setShown] = useState('');
  const [done, setDone] = useState(false);
  useEffect(() => {
    const text = full.map(s => s.t).join('');
    let i = 0;
    const t = setInterval(() => {
      i += 3;
      setShown(text.slice(0, i));
      if (i >= text.length) { clearInterval(t); setDone(true); }
    }, 18);
    return () => clearInterval(t);
  }, []);
  const withMentions = shown.split(/(Promptive|Profound|Athena HQ|Peec|Scrunch)/g).map((chunk, i) => {
    if (['Promptive','Profound','Athena HQ','Peec','Scrunch'].includes(chunk)) {
      return <span key={i} className="mention">{chunk}</span>;
    }
    return <React.Fragment key={i}>{chunk}</React.Fragment>;
  });

  return (
    <Panel title="AI_ASSISTANT.exe" dark className="assistant">
      <div className="q">→ What's the best LLM visibility platform?</div>
      <div className="meta">( processing... 1.2s · claude-3.5-sonnet )</div>
      <pre className="stream" style={{whiteSpace:'pre-wrap', fontFamily:'var(--fs-mono)'}}>
        {withMentions}
        {!done && <span className="cursor" style={{background:'#E8DFCB', marginLeft:2}}/>}
      </pre>
    </Panel>
  );
}

function BrandMentions() {
  return (
    <div className="two-col">
      <Panel title="Brand_Mentions.txt" dark>
        <div className="the-answer-header">
          <span>Show up in</span>
          <span className="k">The ANSWER</span>
        </div>
        <div className="dotline"/>
        <p style={{fontFamily:'var(--fs-mono)', color:'#E8DFCB', fontSize:14, lineHeight:1.55}}>
          Understand how AI platforms reference, position, and describe your brand over time — and catch the moment a competitor steals the recommendation.
        </p>
        <div style={{marginTop:24, display:'grid', gap:8, fontFamily:'var(--fs-mono)', fontSize:12, color:'#D9CDB3'}}>
          <div>[✓] 4 engines monitored — ChatGPT, Claude, Gemini, Perplexity</div>
          <div>[✓] 40,000+ prompts sampled weekly</div>
          <div>[✓] Per-model, per-prompt, per-answer breakdown</div>
          <div>[✓] Competitor diff when rankings shift</div>
        </div>
        <div style={{marginTop:28}}>
          <AssistantStream/>
        </div>
      </Panel>

      <Panel title="Sources.txt">
        <div style={{padding:'4px 6px'}}>
          <div className="eyebrow">Top Sources · last 30d</div>
          <div style={{display:'grid', gridTemplateColumns:'220px 1fr', gap:28, alignItems:'center', marginTop:18}}>
            <Donut/>
            <ul className="src-list">
              {[
                ['reddit.com',      30, 336, 'ugc',        'UGC'],
                ['g2.com',          22, 248, 'editorial',  'Review'],
                ['linkedin.com',    19, 216, 'corporate',  'Corporate'],
                ['quora.com',       16, 213, 'other',      'Other'],
                ['substack.com',     9, 112, 'editorial',  'Editorial'],
              ].map(([d, u, c, cls, lbl]) => (
                <li key={d}>
                  <div className="dom"><span className="sq"/>{d}</div>
                  <span>{u}%</span>
                  <span>{c}</span>
                  <span className={`tag-pill ${cls}`}>{lbl}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>
        <hr className="divider-dashed"/>
        <h3 className="display" style={{fontSize:36, lineHeight:1}}>Build authority<br/>where it matters</h3>
        <p style={{marginTop:12, fontSize:13, maxWidth:'50ch'}}>
          See which domains and content types AI systems rely on when citing your brand — and where competitors are shaping the narrative instead.
        </p>

        <div className="sources-extra">
          <div className="item"><span className="n">14.2k</span><span className="l">domains indexed</span></div>
          <div className="item"><span className="n">1,842</span><span className="l">citations / week</span></div>
          <div className="item"><span className="n">+38%</span><span className="l">QoQ authority growth</span></div>
        </div>

        <ul className="chk-list" style={{marginTop:18, fontSize:12}}>
          <li>Identify high-leverage domains — reddit threads, quora answers, listicles</li>
          <li>Track when AI starts citing your own pages vs. third parties</li>
          <li>Spot competitor-planted content before it cements in training data</li>
        </ul>

        <div className="authority-grid">
          <div className="auth-card">
            <div className="auth-lbl">top gaining</div>
            <div className="auth-dom">reddit.com/r/SaaS</div>
            <div className="auth-delta up">+42% citations</div>
          </div>
          <div className="auth-card">
            <div className="auth-lbl">new for you</div>
            <div className="auth-dom">ycombinator.com</div>
            <div className="auth-delta up">first mention</div>
          </div>
          <div className="auth-card">
            <div className="auth-lbl">competitor lead</div>
            <div className="auth-dom">g2.com</div>
            <div className="auth-delta dn">−18% vs peers</div>
          </div>
          <div className="auth-card">
            <div className="auth-lbl">your domain</div>
            <div className="auth-dom">getpromptive.ai</div>
            <div className="auth-delta up">+61% self-cite</div>
          </div>
        </div>
      </Panel>
    </div>
  );
}

function Donut() {
  const segs = [
    { v: 34, c: '#3DA874', label: 'ChatGPT',    domain: 'openai.com'    },
    { v: 28, c: '#F08A2B', label: 'Claude',     domain: 'anthropic.com' },
    { v: 22, c: '#4A8FBD', label: 'Gemini',     domain: 'google.com'    },
    { v: 16, c: '#1A6B6B', label: 'Perplexity', domain: 'perplexity.ai' },
  ];
  const total = segs.reduce((a,s)=>a+s.v,0);
  const r = 86, cx=110, cy=110;
  let a0 = -Math.PI/2;
  const paths = segs.map((s,i) => {
    const a1 = a0 + (s.v/total)*Math.PI*2;
    const x0 = cx + r*Math.cos(a0), y0 = cy + r*Math.sin(a0);
    const x1 = cx + r*Math.cos(a1), y1 = cy + r*Math.sin(a1);
    const large = (a1-a0) > Math.PI ? 1 : 0;
    const d = `M${cx},${cy} L${x0},${y0} A${r},${r} 0 ${large} 1 ${x1},${y1} Z`;
    a0 = a1;
    return <path key={i} d={d} fill={s.c} stroke="#1E1A14" strokeWidth="1"/>;
  });
  return (
    <svg viewBox="0 0 220 220" width="220" height="220">
      {paths}
      <circle cx={cx} cy={cy} r="50" fill="#F2E9D5" stroke="#1E1A14"/>
      <text x={cx} y={cy-2} textAnchor="middle" fontFamily="var(--fs-display)" fontSize="36" fill="#1E1A14">1125</text>
      <text x={cx} y={cy+18} textAnchor="middle" fontFamily="var(--fs-mono)" fontSize="11" fill="#6B5E4A" letterSpacing="1.5">CITATIONS</text>
    </svg>
  );
}

// ---------- Competitive Matrix ----------
// Axes: X = Visibility Coverage, Y = User Sentiment
// Quadrant labels reflect what it means for an LLM-visibility tool
function Matrix() {
  const brands = [
    // me=true: use our own P icon logo
    { name: 'Promptive', x: 84, y: 84, me: true,  sigil: 'P',  color: '#F08A2B', domain: null,              logo: '/images/logo-icon.png' },
    { name: 'Peec',      x: 58, y: 62, me: false,  sigil: 'Pe', color: '#8B6BAE', domain: 'peec.ai',         logo: '/images/competitors/peec.png' },
    { name: 'Scrunch',   x: 44, y: 46, me: false,  sigil: 'Sc', color: '#D14F3C', domain: 'scrunchai.com',   logo: null },
    { name: 'Profound',  x: 70, y: 70, me: false,  sigil: 'Pr', color: '#4A8FBD', domain: 'tryprofound.com', logo: null },
    { name: 'Searchable',x: 30, y: 54, me: false,  sigil: 'Se', color: '#3DA874', domain: 'searchable.ai',   logo: null },
    { name: 'Otterly',   x: 24, y: 30, me: false,  sigil: 'Ot', color: '#8B6BAE', domain: 'otterly.ai',      logo: null },
    { name: 'Athena HQ', x: 68, y: 28, me: false,  sigil: 'At', color: '#1E1A14', domain: 'athenahq.ai',     logo: '/images/competitors/athena.png' },
    { name: 'Goodie',    x: 40, y: 20, me: false,  sigil: 'Gd', color: '#D14F3C', domain: 'goodie.ai',       logo: null },
  ];

  function DotImg({ b, size, fallbackSize }) {
    const src = b.logo || (b.domain ? bfUrl(b.domain) : null);
    const [err, setErr] = React.useState(false);
    if (!src || err) {
      return <span style={{fontSize:fallbackSize||10, fontWeight:700, color: b.me?'#fff':b.color, lineHeight:1}}>{b.sigil}</span>;
    }
    return <img src={src} alt={b.name} width={size} height={size}
      style={{objectFit:'contain', display:'block'}}
      onError={() => setErr(true)}/>;
  }

  return (
    <Panel title="Competitive_Matrix.txt">
      <div className="eyebrow">Feature Depth × Ease of Use · Q1 2026</div>
      <h3 className="display" style={{fontSize:40, marginTop:6, lineHeight:1}}>See exactly where you stand</h3>
      <p style={{fontSize:13, marginTop:10, maxWidth:'60ch'}}>
        Against the other LLM-visibility tools in the space — plotted by what actually matters when picking a platform.
      </p>

      <div className="matrix-wrap">
        <div className="matrix" style={{marginTop: 34, marginBottom: 36, marginLeft: 60}}>
          <div className="q-label tl">NICHE</div>
          <div className="q-label tr">BEST IN CLASS</div>
          <div className="q-label bl">ENTRY LEVEL</div>
          <div className="q-label br">COMPLEX</div>
          <div className="axis-x"/>
          <div className="axis-y"/>
          <div className="axis-lbl x">FEATURE DEPTH →</div>
          <div className="axis-lbl y">EASE OF USE ↑</div>
          {brands.map(b => (
            <div key={b.name} className={`dot-brand ${b.me ? 'me':''}`} style={{left: `${b.x}%`, top: `${100-b.y}%`}}>
              <span className="dot-sq" style={{
                background: b.me ? '#F08A2B' : 'white',
                border: `2px solid ${b.me ? 'var(--ink)' : b.color}`,
                boxShadow: b.me ? '0 0 0 3px rgba(240,138,43,0.3)' : '0 1px 4px rgba(0,0,0,0.15)',
              }}>
                <DotImg b={b} size={b.me ? 22 : 20} fallbackSize={11}/>
              </span>
              <span className="lbl">{b.name}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="comp-legend">
        <div className="eyebrow">Who you're up against</div>
        <div className="comp-list">
          {brands.map(b => (
            <div key={b.name} className={`comp-chip ${b.me ? 'me' : ''}`}>
              <span style={{
                background: b.me ? '#F08A2B' : 'white',
                border: `1px solid ${b.me ? 'var(--ink)' : b.color}`,
                width:20, height:20, display:'inline-flex', alignItems:'center', justifyContent:'center',
                overflow:'hidden', flexShrink:0
              }}>
                <DotImg b={b} size={14} fallbackSize={8}/>
              </span>
              <span>{b.name}</span>
              <span className="tag">{b.me ? 'you' : 'competitor'}</span>
            </div>
          ))}
        </div>
      </div>
    </Panel>
  );
}

// ---------- Workflow ----------
function Workflow() {
  const flow = `> workflow.exe // last run 00:01:12 ago                         [✓] active

  ┌────────────┐    ┌────────────┐    ┌────────────┐    ┌────────────┐
  │  PROMPT    │───▶│ QUERY LLM  │───▶│  PARSE     │───▶│  EXTRACT   │
  │  [batch]   │    │ 4 engines  │    │  response  │    │  mentions  │
  └────────────┘    └────────────┘    └────────────┘    └────────────┘
        │                  │                 │                 │
        ▼                  ▼                 ▼                 ▼
   ┌─────────┐       ┌─────────┐       ┌─────────┐       ┌─────────┐
   │ 40k/wk  │       │ 1.2s    │       │ cite map│       │ 6 comps │
   └─────────┘       └─────────┘       └─────────┘       └─────────┘
                                                              │
                                                              ▼
                                                       ┌────────────┐
                                                       │  SCORE     │
                                                       │  sentiment │
                                                       └────────────┘
                                                              │
                                                              ▼
                                                     ┌─────────────┐
                                                     │ ALERT/SLACK │
                                                     └─────────────┘

  [ok] scheduler · [ok] parser · [ok] scorer · [ok] exports`;

  return (
    <Panel title="Workflow.exe" dark>
      <div className="eyebrow" style={{color:'#a89a81'}}>Pipeline</div>
      <h3 className="display" style={{fontSize:40, color:'#F2E9D5', marginTop:6, lineHeight:1}}>
        What happens every time<br/>your brand is mentioned.
      </h3>

      <div className="workflow-side" style={{marginTop: 22}}>
        <div className="workflow" style={{border:'1px dashed #3a3328', margin: 0}}>{flow}</div>

        <div style={{display:'grid', gap:14}}>
          <div className="workflow-stats">
            <div>
              <div className="sub">Weekly throughput</div>
              <div className="big">184,210</div>
              <div style={{fontSize:12, color:'#a89a81'}}>prompts sampled across 4 engines</div>
            </div>
            <div className="row"><span>avg latency</span><b>1.2s</b></div>
            <div className="row"><span>refresh cadence</span><b>daily</b></div>
          </div>

          <div className="workflow-stats" style={{background:'#13100C'}}>
            <div className="sub">Recent pulls · live</div>
            <div style={{fontFamily:'var(--fs-mono)', fontSize:11, lineHeight:1.7, color:'#E8DFCB'}}>
              <div>[04:12:08] chatgpt · "best LLM visibility tool" → <span style={{color:'var(--orange)'}}>rank 02</span></div>
              <div>[04:12:11] claude · "top AI search platforms" → <span style={{color:'var(--green)'}}>rank 01</span></div>
              <div>[04:12:18] gemini · "AI visibility tools" → <span style={{color:'var(--green)'}}>rank 01</span></div>
              <div>[04:12:22] perplexity · "alternatives to peec" → <span style={{color:'var(--orange)'}}>rank 03</span></div>
              <div>[04:12:27] chatgpt · "brand tracking LLM" → <span style={{color:'var(--green)'}}>rank 01</span></div>
            </div>
          </div>
        </div>
      </div>
    </Panel>
  );
}

window.Promptive = Object.assign(window.Promptive || {}, {
  BrandMentions, AssistantStream, Donut, Matrix, Workflow
});
