// Detailed report — verdict, signal cards, chart, holders, plan

const Report = ({ coin, aiReport, aiError, aiLoading, onAnalyzeAi, onChat, onNew, onRerun, onToggleWatch, onCopy, isWatched }) => {
  const c = coin || window.SAMPLE_COIN;

  // Merge AI report fields over the coin's market-data fields. AI fields win where present.
  const score      = numberOr(aiReport?.score,      c.score);
  const verdict    = aiReport?.verdict    || c.verdict;
  const riskLevel  = aiReport?.riskLevel  || c.riskLevel  || 'Unknown';
  const conviction = aiReport?.conviction || c.conviction || 'Unknown';
  // entry/stop/target may be explicitly null when verdict is Avoid/Caution.
  // Distinguish "AI said null" (no plan) from "AI hasn't run" (use sample fallback).
  const aiHasPlan  = aiReport && (aiReport.entry || aiReport.stopLoss || aiReport.target);
  const entry      = aiReport ? (aiReport.entry      || null) : (c.entry      || null);
  const stopLoss   = aiReport ? (aiReport.stopLoss   || null) : (c.stopLoss   || null);
  const target     = aiReport ? (aiReport.target     || null) : (c.target     || null);
  const verdictNeg = (aiReport?.verdict || '').toLowerCase().includes('avoid')
                  || (aiReport?.verdict || '').toLowerCase().includes('caution');
  const narrative  = aiReport?.narrative  || null;
  const signals    = (Array.isArray(aiReport?.signals) && aiReport.signals.length > 0)
    ? aiReport.signals
    : window.SIGNAL_CARDS;

  const verdictTone = (() => {
    const v = (verdict || '').toLowerCase();
    if (v.includes('strong buy') || v === 'buy') return 'green';
    if (v.includes('avoid')) return 'red';
    if (v.includes('caution')) return 'amber';
    return 'purple';
  })();

  return (
    <div style={{ flex: 1, overflowY: 'auto' }}>
      <div style={{ maxWidth: 1480, margin: '0 auto', padding: '14px 28px 28px' }}>

        {/* Compact toolbar */}
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginBottom: 12 }}>
          <button onClick={onRerun} style={btnGhost}><Icon name="refresh" size={13} /> Re-run</button>
          <button onClick={onToggleWatch} style={{
            ...btnGhost,
            color: isWatched ? 'var(--purple-glow)' : 'var(--ink-2)',
            borderColor: isWatched ? 'rgba(168,130,255,0.4)' : 'var(--line-2)',
            background: isWatched ? 'rgba(124,77,255,0.14)' : 'rgba(168,130,255,0.06)',
          }}>
            <Icon name="star" size={13} /> {isWatched ? 'Watching' : 'Watchlist'}
          </button>
          <button onClick={onChat} style={btnSolid}><Icon name="message" size={13} /> Ask Sixclaw</button>
        </div>

        {/* Chart (full bleed) + Analyze sidebar */}
        <div className="oracle-chart-row" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 2.6fr) minmax(320px, 1fr)', gap: 20, marginBottom: 20, alignItems: 'stretch' }}>
          <ChartCard coin={c} />

          <AnalyzeSidebar
            aiReport={aiReport}
            aiLoading={aiLoading}
            aiError={aiError}
            onAnalyzeAi={onAnalyzeAi}
            score={score}
            verdict={verdict}
            verdictTone={verdictTone}
            verdictNeg={verdictNeg}
            riskLevel={riskLevel}
            conviction={conviction}
            entry={entry}
            stopLoss={stopLoss}
            target={target}
            narrative={narrative}
          />
        </div>

      </div>
    </div>
  );
};

// Wikicoin-style chart card: gradient accent bar, "Price Performance" title,
// fullscreen toggle, then the embedded chart filling the rest.
const ChartCard = ({ coin }) => {
  const c = coin;
  const [full, setFull] = React.useState(false);

  // Lock body scroll while in fullscreen.
  React.useEffect(() => {
    if (!full) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setFull(false); };
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = prev; window.removeEventListener('keydown', onKey); };
  }, [full]);

  const inner = (
    <>
      {/* Top accent bar — wikicoin's signature gradient line */}
      <div style={{
        height: 2, flexShrink: 0,
        background: 'linear-gradient(90deg, var(--purple-3), var(--purple-glow), var(--purple-2))',
      }} />
      <div style={{
        padding: '18px 22px', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
        flexWrap: 'wrap', gap: 12, flexShrink: 0,
      }}>
        <div style={{ minWidth: 0 }}>
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: -0.3 }}>Price Performance</h2>
          <div style={{ marginTop: 4, fontSize: 12, color: 'var(--ink-3)' }}>
            Real-time market data from DexScreener
            {c.dexId && <span style={{ marginLeft: 8, color: 'var(--ink-4)' }}>· {c.dexId}</span>}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 18, fontWeight: 600 }}>
            {c.priceUsd != null ? formatPriceCell(c.priceUsd) : '—'}
          </span>
          {c.change24h != null && (
            <Badge tone={c.change24h >= 0 ? 'green' : 'red'} size="sm">
              {c.change24h >= 0 ? '+' : ''}{c.change24h.toFixed(1)}% 24h
            </Badge>
          )}
          {c.change1h != null && (
            <Badge tone={c.change1h >= 0 ? 'purple' : 'red'} size="sm">
              {c.change1h >= 0 ? '+' : ''}{c.change1h.toFixed(1)}% 1h
            </Badge>
          )}
          <button
            onClick={() => setFull(f => !f)}
            title={full ? 'Exit fullscreen (Esc)' : 'Expand chart'}
            style={{
              width: 32, height: 32, borderRadius: 2,
              display: 'grid', placeItems: 'center',
              color: 'var(--ink-3)', background: 'rgba(168,130,255,0.06)',
              border: '1px solid var(--line-2)',
              transition: 'background 0.15s, color 0.15s',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(168,130,255,0.14)'; e.currentTarget.style.color = 'var(--purple-glow)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = 'rgba(168,130,255,0.06)'; e.currentTarget.style.color = 'var(--ink-3)'; }}
          >
            {full ? (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M9 9H4M9 9V4M15 9h5M15 9V4M9 15H4M9 15v5M15 15h5M15 15v5"/>
              </svg>
            ) : (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>
              </svg>
            )}
          </button>
        </div>
      </div>
      <div style={{ flex: 1, position: 'relative', minHeight: full ? 0 : 'calc(100vh - 220px)' }}>
        <LiveChart pairAddress={c.pairAddress} ca={c.ca} />
      </div>
    </>
  );

  if (full) {
    return (
      <div style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(10,7,15,0.96)',
        backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
        padding: 16, display: 'flex',
      }}>
        <Card padding={0} style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column', flex: 1 }}>
          {inner}
        </Card>
      </div>
    );
  }

  return (
    <Card padding={0} style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      {inner}
    </Card>
  );
};

// Live chart — embeds DexScreener's chart iframe (same data source pump.fun uses).
// Falls back to a deep-link if there's no pair address yet.
const LiveChart = ({ pairAddress, ca }) => {
  if (!pairAddress) {
    return (
      <div style={{
        height: 420, display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexDirection: 'column', gap: 12, color: 'var(--ink-3)', fontSize: 13,
      }}>
        <Icon name="trend" size={28} />
        <span>Pair address not available — open on DexScreener:</span>
        <a href={`https://dexscreener.com/solana/${ca}`} target="_blank" rel="noreferrer"
           style={{ color: 'var(--purple-glow)', textDecoration: 'none', borderBottom: '1px dashed var(--purple)' }}>
          dexscreener.com/solana/{ca?.slice(0,6)}…
        </a>
      </div>
    );
  }
  // embed=1 strips the DexScreener chrome; theme=dark matches our palette;
  // trades=0&info=0 hides the trade ticker + token info panels so we just get the chart.
  const src = `https://dexscreener.com/solana/${pairAddress}?embed=1&theme=dark&trades=0&info=0`;
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg-1)' }}>
      <iframe
        src={src}
        title="Live price chart"
        loading="lazy"
        style={{ width: '100%', height: '100%', border: 0, display: 'block' }}
      />
    </div>
  );
};

const AnalyzeSidebar = ({ aiReport, aiLoading, aiError, onAnalyzeAi, score, verdict, verdictTone, verdictNeg, riskLevel, conviction, entry, stopLoss, target, narrative }) => {
  // Empty state — big purple CTA
  if (!aiReport) {
    return (
      <Card padding={20} glow style={{
        position: 'relative', overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
        minHeight: 'calc(100vh - 220px)',
      }}>
        <div style={{
          position: 'absolute', top: -80, right: -60, width: 240, height: 240,
          background: 'radial-gradient(circle, rgba(124,77,255,0.22), transparent 70%)',
          pointerEvents: 'none',
        }} />
        <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', height: '100%' }}>
          <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1.4, fontWeight: 600, marginBottom: 8 }}>
            Sixclaw AI · idle
          </div>
          <h2 style={{ fontFamily: 'var(--serif)', fontSize: 26, fontWeight: 400, margin: '0 0 10px', letterSpacing: -0.3, lineHeight: 1.15 }}>
            Worth buying into?
          </h2>
          <p style={{ margin: 0, fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.55 }}>
            Hit Analyze. Six AI agents read the chart, market cap, liquidity, and
            24h flow, then give you a score, a verdict, and a concrete entry / stop /
            target plan.
          </p>

          {aiError && (
            <div style={{ marginTop: 12, padding: '10px 12px', borderRadius: 2, background: 'rgba(255,93,122,0.10)', border: '1px solid rgba(255,93,122,0.25)', color: 'var(--red)', fontSize: 12 }}>
              {aiError}
            </div>
          )}

          <div style={{ flex: 1 }} />

          <button
            onClick={onAnalyzeAi}
            disabled={aiLoading}
            className="ob"
            style={{
              width: '100%', height: 44, marginTop: 18,
              fontSize: 14, fontWeight: 600,
            }}
          >
            {aiLoading ? (
              <>
                <span style={{
                  width: 12, height: 12, borderRadius: 99,
                  border: '2px solid rgba(168,130,255,0.4)',
                  borderTopColor: 'var(--purple-glow)',
                  animation: 'spin 0.8s linear infinite',
                  display: 'inline-block',
                }} />
                Analyzing…
              </>
            ) : 'Analyze with Sixclaw'}
          </button>
          <div style={{ marginTop: 10, fontSize: 10, color: 'var(--ink-4)', textAlign: 'center', fontFamily: 'var(--mono)' }}>
            powered by claude
          </div>
        </div>
      </Card>
    );
  }

  // Filled state — verdict + plan rows live in the rail
  return (
    <Card padding={22} glow style={{ position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column', minHeight: 560 }}>
      <div style={{
        position: 'absolute', top: -80, right: -60, width: 240, height: 240,
        background: 'radial-gradient(circle, rgba(124,77,255,0.22), transparent 70%)',
        pointerEvents: 'none',
      }} />
      <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 14 }}>
          <ScoreRing score={score} size={96} stroke={7} animate={false} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1.4, fontWeight: 600 }}>Verdict</div>
            <div style={{ fontSize: 20, fontWeight: 700, marginTop: 2 }}>{verdict}</div>
            <div style={{ marginTop: 6, fontSize: 10, color: 'var(--ink-4)', fontFamily: 'var(--mono)', letterSpacing: 0.5 }}>
              6 agents · claude
            </div>
          </div>
        </div>

        {/* Agent chips — one per signal */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6, marginBottom: 14 }}>
          {window.SUB_AGENTS.map(a => {
            const sig = (Array.isArray(aiReport?.signals) ? aiReport.signals : []).find(s => s.id === a.id);
            const sc = sig?.score;
            const tone = sc == null ? 'idle' : sc >= 70 ? 'safe' : sc >= 40 ? 'caution' : 'risk';
            const colors = {
              idle:    { fg: 'var(--ink-3)', border: 'var(--line-2)',           bg: 'transparent' },
              safe:    { fg: 'var(--green)', border: 'rgba(108,230,164,0.40)',  bg: 'rgba(108,230,164,0.06)' },
              caution: { fg: 'var(--amber)', border: 'rgba(255,184,77,0.40)',   bg: 'rgba(255,184,77,0.06)' },
              risk:    { fg: 'var(--red)',   border: 'rgba(255,93,122,0.40)',   bg: 'rgba(255,93,122,0.06)' },
            }[tone];
            return (
              <div key={a.id} title={`${a.name}${sc != null ? ` · ${sc}/100` : ''}`} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6,
                padding: '6px 8px', borderRadius: 2,
                border: `1px solid ${colors.border}`, background: colors.bg,
                fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 600,
                color: colors.fg, letterSpacing: 0.3,
              }}>
                <span style={{ color: 'var(--ink-2)', textTransform: 'lowercase' }}>{shortAgent(a.id)}</span>
                <span>{sc != null ? sc : '—'}</span>
              </div>
            );
          })}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
          <KV k="Conviction" v={conviction} tone="var(--purple-glow)" mono={false} />
          <KV k="Risk" v={riskLevel} tone="var(--amber)" mono={false} />
        </div>

        {verdictNeg || (!entry && !stopLoss && !target) ? (
          <div style={{
            padding: '14px 14px', marginBottom: 14,
            border: '1px solid rgba(255,93,122,0.30)',
            borderRadius: 3,
            background: 'rgba(255,93,122,0.06)',
            display: 'flex', gap: 10, alignItems: 'flex-start',
          }}>
            <span style={{ color: 'var(--red)', flexShrink: 0, marginTop: 1 }}>
              <Icon name="x" size={16} stroke={2} />
            </span>
            <div>
              <div style={{ fontSize: 12, color: 'var(--red)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1 }}>
                No trade plan
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 4, lineHeight: 1.5 }}>
                Sixclaw says sit this one out. No entry, no stop, no target — there is no setup worth playing here.
              </div>
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
            {entry    && <PlanRow label="Entry zone" value={entry}    tone="var(--green)"       icon="arrow-down" />}
            {stopLoss && <PlanRow label="Stop loss"  value={stopLoss} tone="var(--red)"         icon="x" />}
            {target   && <PlanRow label="Target"     value={target}   tone="var(--purple-glow)" icon="arrow-up" />}
          </div>
        )}

        {narrative && (
          <div style={{
            fontSize: 12, lineHeight: 1.6, color: 'var(--ink-2)',
            paddingTop: 14, borderTop: '1px solid var(--line)',
            overflowY: 'auto', flex: 1, minHeight: 0,
          }}
            dangerouslySetInnerHTML={{ __html: narrative }} />
        )}

        <button
          onClick={onAnalyzeAi}
          disabled={aiLoading}
          className="ob ob-sm"
          style={{ marginTop: 14, width: '100%', borderColor: 'var(--line-2)', color: 'var(--ink-2)' }}
        >
          <Icon name="refresh" size={12} /> {aiLoading ? 'Re-analyzing…' : 'Re-analyze'}
        </button>
      </div>
    </Card>
  );
};

function shortAgent(id) {
  return ({
    contract: 'contract',
    liquidity: 'liquidity',
    holders: 'holders',
    chart: 'chart',
    social: 'social',
    pattern: 'pattern',
  })[id] || id;
}

function numberOr(v, fallback) {
  const n = Number(v);
  return Number.isFinite(n) ? n : fallback;
}
function formatPriceCell(n) {
  if (n >= 1) return '$' + n.toFixed(4);
  if (n >= 0.01) return '$' + n.toFixed(5);
  if (n >= 0.0001) return '$' + n.toFixed(7);
  return '$' + n.toExponential(2);
}
function signalSummary(signals) {
  const total = signals.length;
  let pass = 0, caution = 0;
  for (const s of signals) {
    if (s.status === 'safe' || (s.score != null && s.score >= 70)) pass++;
    else if (s.status === 'risk' || (s.score != null && s.score < 50)) {} // counted in 'else'
    else caution++;
  }
  const risk = total - pass - caution;
  return `${total} signals · ${pass} pass · ${caution} caution${risk ? ` · ${risk} risk` : ''}`;
}

const PlanRow = ({ label, value, tone, icon }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 10,
    padding: '10px 12px',
    border: '1px solid var(--line-2)',
    borderRadius: 3,
    background: 'rgba(168,130,255,0.04)',
  }}>
    <div style={{ width: 26, height: 26, borderRadius: 2, background: 'rgba(168,130,255,0.08)', display: 'grid', placeItems: 'center', color: tone }}>
      <Icon name={icon} size={13} stroke={2} />
    </div>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1, fontWeight: 600 }}>{label}</div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 12, color: tone, fontWeight: 600, marginTop: 2 }}>{value}</div>
    </div>
  </div>
);

const btnGhost = {
  display: 'inline-flex', alignItems: 'center', gap: 6,
  padding: '8px 12px', borderRadius: 3,
  background: 'transparent', border: '1px solid var(--line-2)',
  color: 'var(--ink-2)', fontSize: 12, fontWeight: 500,
  cursor: 'pointer',
  transition: 'border-color 0.15s, color 0.15s, background 0.15s',
};
const btnSolid = {
  display: 'inline-flex', alignItems: 'center', gap: 6,
  padding: '8px 14px', borderRadius: 3,
  background: 'transparent', border: '1px solid var(--purple)',
  color: 'var(--purple-glow)', fontSize: 12, fontWeight: 600,
  cursor: 'pointer',
  transition: 'background 0.15s, color 0.15s, border-color 0.15s',
};

window.Report = Report;
