const COPILOT_SEED = [
  { role: "user", text: "Why is profit decreasing in Q2?" },
  { role: "assistant", streaming: false, text: "Q2 net profit is down **4.2%** vs Q1, but the story is nuanced — this is a **margin compression story, not a revenue story**. Here's the decomposition:", charts: ["waterfall"], sources: ["gem_transactions", "state_revenue_daily", "vendor_master"], followups: ["Which department contributed most?", "Show forecast for Q3", "Compare with FY25 Q2"] },
];

function CopilotScreen() {
  const [messages, setMessages] = useState(COPILOT_SEED);
  const [input, setInput] = useState("");
  const [streaming, setStreaming] = useState(false);
  const scrollRef = useRef(null);

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' });
  }, [messages, streaming]);

  const send = (text) => {
    const q = text || input;
    if (!q.trim()) return;
    setMessages(m => [...m, { role: "user", text: q }]);
    setInput("");
    setStreaming(true);
    setTimeout(() => {
      setMessages(m => [...m, {
        role: "assistant",
        text: "Analyzing across **3 datasets**, executing federated query on ClickHouse + PostgreSQL…",
        charts: ["line"],
        sources: ["gem_transactions", "vendor_master"],
        followups: ["Break this down by department", "Forecast next 90 days", "Export as PDF report"]
      }]);
      setStreaming(false);
    }, 900);
  };

  return (
    <div className="screen" style={{ display: 'flex', gap: 16, height: 'calc(100vh - 56px)', padding: 20 }}>
      {/* Left: history / examples */}
      <div style={{ width: 220, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <button className="btn primary" style={{ justifyContent: 'center' }}><Icon name="plus"/>New chat</button>
        <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-4)', fontWeight: 600, marginTop: 6 }}>Recent</div>
        {[
          "Q2 profit decrease analysis",
          "State-wise procurement report",
          "Vendor risk assessment",
          "GeM Q1 vs Q2 comparison",
          "Predict Q3 tender volumes",
        ].map((h, i) => (
          <div key={i} className="nav-item" style={{ fontSize: 12, padding: '6px 10px', background: i === 0 ? 'var(--panel-2)' : 'transparent', border: i === 0 ? '1px solid var(--border)' : '1px solid transparent' }}>
            <Icon name="sparkles" size={12} style={{ color: 'var(--accent-2)' }}/>
            <span className="nav-label">{h}</span>
          </div>
        ))}
        <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-4)', fontWeight: 600, marginTop: 10 }}>Data Scope</div>
        <div style={{ padding: 10, background: 'var(--panel-2)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 11.5 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-2)', marginBottom: 4 }}><Icon name="database" size={11}/><b>4 datasets</b> selected</div>
          <div style={{ color: 'var(--ink-3)', fontSize: 11 }}>gem_transactions · vendor_master · state_revenue_daily · scheme_disbursement</div>
        </div>
      </div>

      {/* Main chat */}
      <div className="card" style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div className="card-head" style={{ borderBottom: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 28, height: 28, borderRadius: 8, background: 'linear-gradient(140deg, var(--primary), var(--accent))', display: 'grid', placeItems: 'center' }}>
              <Icon name="sparkles" size={14} style={{ color: 'white' }}/>
            </div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 13.5 }}>VyaparBI Copilot</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Multi-agent · RAG over 12 datasets · Multilingual (हिन्दी, English, 22 Indian langs)</div>
            </div>
          </div>
          <div className="card-actions">
            <span className="tag ok"><Icon name="shield" size={10}/>XAI Enabled</span>
            <button className="btn sm"><Icon name="download" size={12}/>Export chat</button>
            <button className="icon-btn"><Icon name="moreH"/></button>
          </div>
        </div>

        <div className="scroll" ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: 20 }}>
          {messages.map((m, i) => (
            <Message key={i} m={m} onFollowup={send}/>
          ))}
          {streaming && (
            <div style={{ display: 'flex', gap: 12, marginBottom: 20 }}>
              <div style={{ width: 30, height: 30, borderRadius: 8, background: 'linear-gradient(140deg, var(--primary), var(--accent))', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                <Icon name="sparkles" size={14} style={{ color: 'white' }}/>
              </div>
              <div style={{ padding: '10px 14px', background: 'var(--panel-2)', borderRadius: 10, color: 'var(--ink-3)', fontSize: 12, display: 'flex', alignItems: 'center', gap: 6 }}>
                <span className="live-dot"/>
                <span>Planning query… routing to <span className="mono" style={{ color: 'var(--primary)' }}>ClickHouse</span> and <span className="mono" style={{ color: 'var(--primary)' }}>Postgres</span></span>
              </div>
            </div>
          )}
        </div>

        <div style={{ padding: 14, borderTop: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 10 }}>
            {["Try:", "Explain revenue anomalies", "Compare states YoY", "Predict Q3 volumes", "Vendor risk scores"].map((c, i) => (
              i === 0 ? <span key={i} style={{ fontSize: 11, color: 'var(--ink-3)', alignSelf: 'center' }}>{c}</span> :
              <button key={i} className="btn sm" onClick={() => send(c)}>{c}</button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end', border: '1px solid var(--border-strong)', borderRadius: 12, padding: 10, background: 'var(--panel-2)' }}>
            <button className="icon-btn" title="Attach"><Icon name="plus" size={16}/></button>
            <textarea value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }}}
              placeholder="Ask about your data… e.g. 'Show me GeM procurement trends for the last 6 months by state'"
              rows={1}
              style={{ flex: 1, resize: 'none', border: 'none', background: 'transparent', color: 'var(--ink)', fontFamily: 'inherit', fontSize: 13, outline: 'none', lineHeight: 1.5, minHeight: 20, maxHeight: 100 }}
            />
            <button className="icon-btn" title="Voice"><Icon name="mic" size={16}/></button>
            <button className="btn primary sm" style={{ height: 30 }} onClick={() => send()}><Icon name="send" size={12}/>Send</button>
          </div>
          <div style={{ marginTop: 8, fontSize: 10.5, color: 'var(--ink-4)', display: 'flex', gap: 12, alignItems: 'center' }}>
            <span><Icon name="shield" size={10} style={{ verticalAlign: 'middle' }}/> Answers cite source rows. Numbers verified against live database.</span>
            <span className="spacer"/>
            <span>Model: <span className="mono">vyapar-agent-v3</span> · Tokens: 4.2K/1M</span>
          </div>
        </div>
      </div>

      {/* Right: analytical trace */}
      <div style={{ width: 260, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div className="card">
          <div className="card-head" style={{ padding: '10px 12px' }}>
            <h3 style={{ fontSize: 12 }}>Reasoning Trace</h3>
            <span className="tag primary" style={{ fontSize: 10 }}>XAI</span>
          </div>
          <div className="card-body" style={{ padding: 12, fontSize: 11.5 }}>
            <TraceStep num="1" title="Intent recognized" body="Root cause analysis · profit metric · Q2 scope" ok/>
            <TraceStep num="2" title="Retrieved schema" body="9 tables, 42 columns — semantic layer" ok/>
            <TraceStep num="3" title="Generated SQL" body="3 CTEs, joins on vendor_id + state_code" ok/>
            <TraceStep num="4" title="Executed federated" body="ClickHouse (218ms) + Postgres (94ms)" ok/>
            <TraceStep num="5" title="Anomaly check" body="Isolation Forest — 2 outliers flagged" ok/>
            <TraceStep num="6" title="Composed answer" body="Grounded in 3 datasets, 218 rows" ok last/>
          </div>
        </div>
        <div className="card">
          <div className="card-head" style={{ padding: '10px 12px' }}>
            <h3 style={{ fontSize: 12 }}>Cited Sources</h3>
          </div>
          <div className="card-body" style={{ padding: 12, fontSize: 11.5, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {["gem_transactions (208 rows)", "vendor_master (18 rows)", "state_revenue_daily (92 rows)"].map((s, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '5px 8px', background: 'var(--panel-2)', borderRadius: 6 }}>
                <Icon name="database" size={12} style={{ color: 'var(--primary)' }}/>
                <span className="mono" style={{ fontSize: 11 }}>{s}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function TraceStep({ num, title, body, ok, last }) {
  return (
    <div style={{ display: 'flex', gap: 8, paddingBottom: last ? 0 : 10, position: 'relative' }}>
      {!last && <div style={{ position: 'absolute', left: 8, top: 18, bottom: 0, width: 1, background: 'var(--border)' }}/>}
      <div style={{ width: 17, height: 17, borderRadius: 50, background: ok ? 'var(--ok)' : 'var(--border-strong)', color: 'white', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 600, flexShrink: 0, zIndex: 1 }}>
        {ok ? <Icon name="check" size={10}/> : num}
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 11.5 }}>{title}</div>
        <div style={{ color: 'var(--ink-3)', fontSize: 10.5, marginTop: 1 }}>{body}</div>
      </div>
    </div>
  );
}

function Message({ m, onFollowup }) {
  if (m.role === "user") {
    return (
      <div style={{ display: 'flex', gap: 12, marginBottom: 20, justifyContent: 'flex-end' }}>
        <div style={{ maxWidth: '70%', padding: '10px 14px', background: 'var(--primary)', color: 'white', borderRadius: '14px 14px 4px 14px', fontSize: 13, lineHeight: 1.55 }}>
          {m.text}
        </div>
        <div className="avatar" style={{ width: 30, height: 30, fontSize: 11 }}>AR</div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', gap: 12, marginBottom: 20 }}>
      <div style={{ width: 30, height: 30, borderRadius: 8, background: 'linear-gradient(140deg, var(--primary), var(--accent))', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
        <Icon name="sparkles" size={14} style={{ color: 'white' }}/>
      </div>
      <div style={{ flex: 1, maxWidth: '85%' }}>
        <div style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--ink)' }} dangerouslySetInnerHTML={{ __html: m.text.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>') }}/>

        {m.charts?.includes("waterfall") && (
          <div className="card" style={{ marginTop: 12 }}>
            <div className="card-body">
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600 }}>Q1 → Q2 Profit Bridge (₹ Cr)</div>
              <Waterfall items={[
                { label: "Q1 Profit", value: 428, kind: "start" },
                { label: "Revenue ↑", value: 84, kind: "up" },
                { label: "COGS ↑", value: -62, kind: "down" },
                { label: "Vendor cost ↑", value: -38, kind: "down" },
                { label: "Ops savings", value: 24, kind: "up" },
                { label: "FX loss", value: -18, kind: "down" },
                { label: "Q2 Profit", value: 418, kind: "end" },
              ]}/>
              <div style={{ marginTop: 10, padding: 10, background: 'var(--accent-tint)', borderRadius: 6, fontSize: 11.5, color: 'var(--ink)', borderLeft: '3px solid var(--accent)' }}>
                <b>Root cause:</b> Vendor cost inflation (+₹38 Cr) driven by 3 large steel & electronics contracts renegotiated at higher rates. Revenue growth was healthy but couldn't fully offset input costs.
              </div>
            </div>
          </div>
        )}

        {m.charts?.includes("line") && (
          <div className="card" style={{ marginTop: 12 }}>
            <div className="card-body">
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600 }}>Revenue Trend — Last 6 Months</div>
              <LineChart series={[{ name: "Revenue", data: [232,240,252,268,275,288] }]} labels={["Feb","Mar","Apr","May","Jun","Jul"]} h={180}/>
            </div>
          </div>
        )}

        {m.sources && (
          <div style={{ marginTop: 10, display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
            <span style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600 }}>Sources:</span>
            {m.sources.map((s, i) => (
              <span key={i} className="tag primary" style={{ fontSize: 10.5 }}><Icon name="database" size={10}/>{s}</span>
            ))}
          </div>
        )}

        {m.followups && (
          <div style={{ marginTop: 12, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {m.followups.map((f, i) => (
              <button key={i} className="btn sm" onClick={() => onFollowup(f)}><Icon name="sparkles" size={11}/>{f}</button>
            ))}
          </div>
        )}

        <div style={{ marginTop: 10, display: 'flex', gap: 4, color: 'var(--ink-3)' }}>
          <button className="icon-btn" title="Helpful" style={{ width: 24, height: 24 }}><Icon name="check" size={12}/></button>
          <button className="icon-btn" title="Not helpful" style={{ width: 24, height: 24 }}><Icon name="close" size={12}/></button>
          <button className="icon-btn" title="Copy" style={{ width: 24, height: 24 }}><Icon name="share" size={12}/></button>
          <button className="icon-btn" title="Regenerate" style={{ width: 24, height: 24 }}><Icon name="refresh" size={12}/></button>
        </div>
      </div>
    </div>
  );
}

function Waterfall({ items }) {
  const values = items.map(i => i.value);
  const cumulative = [];
  let running = 0;
  items.forEach((it, i) => {
    if (it.kind === "start") { cumulative.push({ base: 0, height: it.value, isFloat: false }); running = it.value; }
    else if (it.kind === "end") { cumulative.push({ base: 0, height: it.value, isFloat: false }); }
    else if (it.kind === "up") { cumulative.push({ base: running, height: it.value, isFloat: true }); running += it.value; }
    else { cumulative.push({ base: running + it.value, height: -it.value, isFloat: true }); running += it.value; }
  });
  const max = Math.max(...cumulative.map(c => c.base + c.height));
  const h = 160, pad = 32, w = 560;
  const iw = w - 20; // account for padding
  const barW = iw / items.length * 0.65;
  const gap = iw / items.length * 0.35;

  return (
    <svg width="100%" height={h + 40} viewBox={`0 0 ${w} ${h + 40}`} preserveAspectRatio="none">
      {items.map((it, i) => {
        const x = 10 + i * (barW + gap) + gap / 2;
        const c = cumulative[i];
        const barHeight = (c.height / max) * h;
        const y = h - ((c.base + c.height) / max) * h;
        const color = it.kind === "start" || it.kind === "end" ? "var(--primary)" : it.kind === "up" ? "var(--ok)" : "var(--danger)";
        return (
          <g key={i}>
            <rect x={x} y={y} width={barW} height={barHeight} rx="2" fill={color}/>
            <text x={x + barW/2} y={y - 4} fontSize="10" fill="var(--ink-2)" fontFamily="JetBrains Mono" textAnchor="middle">
              {it.value > 0 && (it.kind === 'up') ? '+' : ''}{it.value}
            </text>
            <text x={x + barW/2} y={h + 14} fontSize="10" fill="var(--ink-3)" textAnchor="middle">{it.label}</text>
          </g>
        );
      })}
    </svg>
  );
}

// Floating drawer copilot
function CopilotDrawer({ onClose }) {
  const [messages, setMessages] = useState([
    { role: "assistant", text: "Hi Aditi 👋 I've reviewed today's dashboards. **Delhi NCR is up 22.1%** — want me to dig into what's driving it?", followups: ["Yes, break it down", "Show anomalies today", "Summarize this week"] }
  ]);
  const [input, setInput] = useState("");
  const scrollRef = useRef(null);
  useEffect(() => { scrollRef.current?.scrollTo({ top: 9999 }); }, [messages]);
  const send = (t) => {
    const q = t || input;
    if (!q.trim()) return;
    setMessages(m => [...m, { role: "user", text: q }]);
    setInput("");
    setTimeout(() => setMessages(m => [...m, { role: "assistant", text: "Running federated query… Delhi NCR growth is driven by **3 large IT infrastructure tenders** from CDAC and NIC totaling ₹42 Cr.", followups: ["Show the tenders", "Compare with Mumbai", "Export as PDF"] }]), 700);
  };
  return (
    <div className="copilot-drawer">
      <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 26, height: 26, borderRadius: 7, background: 'linear-gradient(140deg, var(--primary), var(--accent))', display: 'grid', placeItems: 'center' }}>
          <Icon name="sparkles" size={13} style={{ color: 'white' }}/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 600, fontSize: 13 }}>Copilot</div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>Grounded on this page's data</div>
        </div>
        <button className="icon-btn" onClick={onClose}><Icon name="close" size={14}/></button>
      </div>
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: 14 }}>
        {messages.map((m, i) => (
          m.role === "user" ? (
            <div key={i} style={{ textAlign: 'right', marginBottom: 12 }}>
              <div style={{ display: 'inline-block', background: 'var(--primary)', color: 'white', padding: '8px 12px', borderRadius: '12px 12px 4px 12px', fontSize: 12.5 }}>{m.text}</div>
            </div>
          ) : (
            <div key={i} style={{ marginBottom: 12 }}>
              <div style={{ background: 'var(--panel-2)', padding: '10px 12px', borderRadius: '12px 12px 12px 4px', fontSize: 12.5, lineHeight: 1.55 }} dangerouslySetInnerHTML={{ __html: m.text.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>') }}/>
              {m.followups && (
                <div style={{ marginTop: 6, display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                  {m.followups.map((f, j) => (
                    <button key={j} className="btn sm" style={{ height: 22, fontSize: 10.5 }} onClick={() => send(f)}>{f}</button>
                  ))}
                </div>
              )}
            </div>
          )
        ))}
      </div>
      <div style={{ padding: 10, borderTop: '1px solid var(--border)', display: 'flex', gap: 6, alignItems: 'center' }}>
        <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()}
          placeholder="Ask about this page…"
          style={{ flex: 1, border: '1px solid var(--border)', background: 'var(--panel-2)', borderRadius: 8, padding: '8px 10px', fontSize: 12, color: 'var(--ink)', fontFamily: 'inherit', outline: 'none' }}
        />
        <button className="btn primary sm" onClick={() => send()}><Icon name="send" size={12}/></button>
      </div>
    </div>
  );
}

Object.assign(window, { CopilotScreen, CopilotDrawer });
