/* global React */
const { useEffect, useRef, useState } = React;
const { Panel, EngineIcon } = window.Promptive;

// ---------- Sparkline ----------
function Sparkline({ data, labels, color = '#1E1A14', height = 100, onHover }) {
  const w = 300, h = height;
  const max = Math.max(...data), min = Math.min(...data);
  const [hover, setHover] = useState(null);
  const coords = data.map((v, i) => {
    const x = (i/(data.length-1)) * (w-20) + 10;
    const y = h - 12 - ((v - min)/(max-min || 1)) * (h - 32);
    return { x, y, v, label: labels?.[i] };
  });
  const points = coords.map(p => `${p.x},${p.y}`).join(' ');
  function handleMove(e) {
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * w;
    let best = 0, bestD = Infinity;
    coords.forEach((c, i) => { const d = Math.abs(c.x - x); if (d < bestD) { bestD = d; best = i; } });
    setHover(best);
    onHover && onHover(best, coords[best]);
  }
  function handleLeave() { setHover(null); onHover && onHover(null, null); }
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="sparkline" preserveAspectRatio="none"
         onMouseMove={handleMove} onMouseLeave={handleLeave} style={{cursor:'crosshair'}}>
      {[0,1,2,3].map(i => (
        <line key={i} x1="10" x2={w-10} y1={10 + i*(h-24)/3} y2={10 + i*(h-24)/3} stroke="#1E1A14" strokeWidth="1" strokeDasharray="2 3" opacity="0.25"/>
      ))}
      <polyline fill="none" stroke={color} strokeWidth="2" points={points}/>
      {coords.map((p, i) => (
        <rect key={i} x={p.x-2} y={p.y-2} width="4" height="4" fill={color}/>
      ))}
      {hover != null && (
        <g>
          <line x1={coords[hover].x} x2={coords[hover].x} y1="8" y2={h-8} stroke={color} strokeWidth="1" strokeDasharray="2 2"/>
          <rect x={coords[hover].x-4} y={coords[hover].y-4} width="8" height="8" fill={color}/>
        </g>
      )}
    </svg>
  );
}

function Triad() {
  const vis = [12, 18, 17, 24, 30, 28, 36, 44, 48, 55, 62, 71];
  const visLabels = ['W-11','W-10','W-9','W-8','W-7','W-6','W-5','W-4','W-3','W-2','W-1','now'];
  const [visHover, setVisHover] = useState(null);

  // Position data — real tool names for clarity
  const positions = [
    { rank:'01', name:'Promptive',   score:91, rest:9,  me:true, domain:null,     color:'#F08A2B' },
    { rank:'02', name:'Searchable',  score:84, rest:16, domain:'searchable.ai',  color:'#3DA874' },
    { rank:'03', name:'Peec',        score:62, rest:38, domain:'peec.ai',         color:'#8B6BAE' },
    { rank:'04', name:'Profound',    score:49, rest:51, domain:'tryprofound.com', color:'#4A8FBD' },
    { rank:'05', name:'Scrunch',     score:37, rest:63, domain:'scrunchai.com',   color:'#D14F3C' },
  ];
  const [posHover, setPosHover] = useState(0);

  const sentiments = [
    { k:'chatgpt',    v:0.62, phrase:'"reliable"',        domain:'chatgpt.com'       },
    { k:'claude',     v:0.71, phrase:'"enterprise-grade"', domain:'claude.ai'       },
    { k:'gemini',     v:0.44, phrase:'"well-reviewed"',   domain:'gemini.google.com' },
    { k:'perplexity', v:0.58, phrase:'"recommended"',     domain:'perplexity.ai'    },
    { k:'avg',        v:0.42, phrase:'"reliable"',        domain:null            },
  ];
  const [sentHover, setSentHover] = useState(4);
  const s = sentiments[sentHover];
  const needlePct = 50 + s.v * 50;

  const visValue = visHover != null ? vis[visHover] : 71;
  const visLabel = visHover != null ? visLabels[visHover] : 'now';

  return (
    <div className="triad">
      {/* ---- Visibility ---- */}
      <Panel title="Visibility.exe">
        <div className="tri-headline">Visibility</div>
        <p className="tri-body">How often your brand surfaces in AI answers across engines and prompts.</p>
        <div className="tri-viz">
          <Sparkline data={vis} labels={visLabels} color="#F08A2B" height={160} onHover={(i) => setVisHover(i)}/>
          <div style={{position:'absolute', top:10, left:14, fontSize:11, color:'#6B5E4A', letterSpacing:'.1em', textTransform:'uppercase'}}>
            Share of Voice · {visLabel}
          </div>
          <div style={{position:'absolute', bottom:10, right:14, fontFamily:'var(--fs-display)', fontSize:28}}>
            {visValue}<span style={{fontSize:14, color:'#6B5E4A'}}>%</span>
          </div>
        </div>
      </Panel>

      {/* ---- Position ---- */}
      <Panel title="Position.exe">
        <div className="tri-headline">Position</div>
        <p className="tri-body">Where you rank inside generative answers — first mention, top list, or buried below the fold.</p>
        <div className="tri-viz pos-viz">
          <div className="pos-caption">
            <span className="pos-prompt">prompt · "best LLM visibility platform"</span>
            <span className="pos-active">{positions[posHover].name} · <b>{positions[posHover].score}</b></span>
          </div>
          <ul className="rank-list">
            {positions.map((p, i) => (
              <li key={p.rank} className={`${p.me?'me':''} ${posHover===i?'hover':''}`}
                  onMouseEnter={()=>setPosHover(i)}>
                <span className="n">{p.rank}</span>
                <span className="pos-name">
                  <span style={{
                    display:'inline-block', width:8, height:8, borderRadius:1, verticalAlign:'middle',
                    marginRight:5, background: p.color, flexShrink:0
                  }}/>
                  {p.name}
                </span>
                <span className="bar" style={{'--rest': `${p.rest}%`, '--bar-color': p.me ? 'var(--orange)' : p.color}}/>
                <span className="v">{p.score}</span>
              </li>
            ))}
          </ul>
        </div>
      </Panel>

      {/* ---- Sentiment ---- */}
      <Panel title="Sentiment.exe">
        <div className="tri-headline">Sentiment</div>
        <p className="tri-body">The tone AI systems use when describing you — and the exact phrases that keep repeating.</p>
        <div className="tri-viz">
          <div className="gauge-wrap">
            <div style={{display:'flex', justifyContent:'space-between', fontSize:11, color:'#6B5E4A', textTransform:'uppercase', letterSpacing:'.1em'}}>
              <span>negative</span><span>neutral</span><span>positive</span>
            </div>
            <div className="gauge"><div className="needle" style={{left: `${needlePct}%`, transition:'left .25s ease'}}/></div>
            <div style={{display:'flex', gap:6, flexWrap:'wrap', marginTop:4}}>
              {sentiments.map((x, i) => (
                <button key={x.k}
                  onMouseEnter={()=>setSentHover(i)}
                  style={{
                    fontFamily:'var(--fs-mono)', fontSize:10, padding:'3px 7px',
                    border:'1px solid var(--ink)', background: sentHover===i ? 'var(--orange)' : 'var(--cream)',
                    cursor:'pointer', textTransform:'uppercase', letterSpacing:'.06em',
                    display:'inline-flex', alignItems:'center', gap:4
                  }}>
                  {x.k !== 'avg' && <EngineIcon name={x.k} size={11} invert={sentHover===i}/>}
                  {x.k}
                </button>
              ))}
            </div>
            <div style={{display:'flex', justifyContent:'space-between', fontFamily:'var(--fs-mono)', fontSize:12, marginTop:4}}>
              <span>{s.phrase}</span><span>{s.v >= 0 ? '+' : ''}{s.v.toFixed(2)}</span>
            </div>
          </div>
        </div>
      </Panel>
    </div>
  );
}

// ---------- Citations table ----------
const ENGINE_ROWS = [
  { name: 'ChatGPT',    sigil: 'G',  domain: 'chatgpt.com',       color: '#3DA874', citations: 1842, rate: 28, sentiment: 0.62, trend: '+12%' },
  { name: 'Claude',     sigil: 'C',  domain: 'claude.ai',         color: '#F08A2B', citations: 1320, rate: 31, sentiment: 0.71, trend: '+8%'  },
  { name: 'Gemini',     sigil: 'Ge', domain: 'gemini.google.com', color: '#4A8FBD', citations:  908, rate: 22, sentiment: 0.44, trend: '-3%'  },
  { name: 'Perplexity', sigil: 'P',  domain: 'perplexity.ai',     color: '#1A6B6B', citations:  712, rate: 26, sentiment: 0.58, trend: '+4%'  },
];

function Citations() {
  const asciiArt = `┌──────────────────────┐
│  >  search           │
│  ────────────────    │
│  >  answer    ◉      │
│  ────────────────    │
│  cite:[1][2][3]      │
└──────────────────────┘
      │     │     │
      ▼     ▼     ▼
 [ source · source · source ]`;

  return (
    <Panel title="Citations.txt" bodyClass="compact">
      <div className="cite-split">
        <div className="cite-left">
          <div className="eyebrow">Platform Performance</div>
          <table className="cite-table" style={{marginTop: 12}}>
            <thead>
              <tr>
                <th>Engine</th>
                <th style={{textAlign:'right'}}>Citations</th>
                <th style={{textAlign:'right'}}>Rate</th>
                <th style={{textAlign:'right'}}>Sentiment</th>
                <th style={{textAlign:'right'}}>90d</th>
              </tr>
            </thead>
            <tbody>
              {ENGINE_ROWS.map(r => (
                <tr key={r.name}>
                  <td>
                    <span className="brand-cell">
                      <span className="dot" style={{
                        background: r.color,
                        display:'inline-flex', alignItems:'center', justifyContent:'center',
                        width:26, height:26, padding:3, flexShrink:0, borderRadius:3
                      }}>
                        <EngineIcon name={r.name} size={18} invert={true}/>
                      </span>
                      {r.name}
                    </span>
                  </td>
                  <td className="num">{r.citations.toLocaleString()}</td>
                  <td className="num">{r.rate}%</td>
                  <td className="num">{r.sentiment >= 0 ? '+' : ''}{r.sentiment.toFixed(2)}</td>
                  <td className="num" style={{color: r.trend.startsWith('-') ? 'var(--red)' : 'var(--green)'}}>{r.trend}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="cite-right">
          <pre className="ascii-art">{asciiArt}</pre>
          <h3 className="display" style={{fontSize:40, marginTop:14, lineHeight:1}}>
            The blue link<br/>is no longer<br/>the end goal.
          </h3>
          <p className="mono" style={{marginTop:12, color:'#2B241B'}}>
            The answer is. Promptive shows you every mention, every rank, every time a model speaks your name.
          </p>
          <div style={{marginTop:20, paddingTop:18, borderTop:'1px dashed var(--ink)', display:'grid', gap:9, fontFamily:'var(--fs-mono)', fontSize:12}}>
            <div style={{display:'flex', justifyContent:'space-between'}}>
              <span style={{color:'var(--dim)'}}>% of searches ending in AI answer</span>
              <b style={{color:'var(--orange)'}}>58%</b>
            </div>
            <div style={{display:'flex', justifyContent:'space-between'}}>
              <span style={{color:'var(--dim)'}}>avg answers read before click</span>
              <b>2.3</b>
            </div>
            <div style={{display:'flex', justifyContent:'space-between'}}>
              <span style={{color:'var(--dim)'}}>citations we see daily · you</span>
              <b style={{color:'var(--green)'}}>336</b>
            </div>
            <div style={{display:'flex', justifyContent:'space-between'}}>
              <span style={{color:'var(--dim)'}}>citations we see daily · top competitor</span>
              <b style={{color:'var(--red)'}}>412</b>
            </div>
          </div>
        </div>
      </div>
    </Panel>
  );
}

window.Promptive = Object.assign(window.Promptive || {}, { Triad, Citations, Sparkline });
