/* global React */
const { useState, useEffect, useRef } = React;

/* ---------- animated line chart ---------- */
function LineChart({ pts, max = 10, from = 'S1', to = 'S6', delta }) {
  const W = 320, H = 116;
  const ref = useRef(null);
  const [len, setLen] = useState(0);
  const [shown, setShown] = useState(false);
  const path = pts.map((p, i) =>
    `${i ? 'L' : 'M'} ${(i / (pts.length - 1)) * W} ${H - (p / max) * (H - 16) - 8}`).join(' ');
  useEffect(() => {
    if (ref.current) setLen(ref.current.getTotalLength());
    const t = setTimeout(() => setShown(true), 60);
    return () => clearTimeout(t);
  }, []);
  const lastX = W, lastY = H - (pts[pts.length - 1] / max) * (H - 16) - 8;
  return (
    <div style={{ marginTop: 14, background: 'var(--sage-50)', border: '1px solid var(--line-soft)', borderRadius: 13, padding: '14px 16px' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
        <span style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.06em' }}>Stakeholder confidence (self-rated)</span>
        {delta && <span style={{ marginLeft: 'auto', fontSize: 12.5, fontWeight: 700, color: 'var(--green-600)' }}>▲ {delta}</span>}
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none" style={{ overflow: 'visible' }}>
        {[0.25, 0.5, 0.75].map((g) => (
          <line key={g} x1="0" x2={W} y1={H * g} y2={H * g} stroke="var(--line)" strokeWidth="1" strokeDasharray="3 4" />
        ))}
        <path d={`${path} L ${W} ${H} L 0 ${H} Z`} fill="url(#lg)" style={{ opacity: shown ? 1 : 0, transition: 'opacity 1s ease .5s' }} />
        <path ref={ref} d={path} fill="none" stroke="var(--green-500)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"
          style={{ strokeDasharray: len, strokeDashoffset: shown ? 0 : len, transition: 'stroke-dashoffset 1.3s cubic-bezier(.4,0,.2,1)' }} />
        <circle cx={lastX} cy={lastY} r="5" fill="var(--green-600)" stroke="#fff" strokeWidth="2"
          style={{ opacity: shown ? 1 : 0, transition: 'opacity .4s ease 1.2s' }} />
      </svg>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: 'var(--faint)', marginTop: 4 }}>
        <span>{from}</span><span>{to}</span>
      </div>
      <defs />
      <svg width="0" height="0"><defs><linearGradient id="lg" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stopColor="var(--green-400)" stopOpacity=".5" /><stop offset="1" stopColor="var(--green-400)" stopOpacity="0" />
      </linearGradient></defs></svg>
    </div>
  );
}

/* ---------- animated horizontal bars ---------- */
function Bars({ items }) {
  const [shown, setShown] = useState(false);
  useEffect(() => { const t = setTimeout(() => setShown(true), 80); return () => clearTimeout(t); }, []);
  return (
    <div style={{ marginTop: 14, display: 'grid', gap: 10 }}>
      {items.map((it, i) => (
        <div key={it.label}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 5 }}>
            <span style={{ color: 'var(--ink-soft)', fontWeight: 500 }}>{it.label}</span>
            <span style={{ color: 'var(--muted)' }}>{it.note}</span>
          </div>
          <div style={{ height: 8, borderRadius: 5, background: 'var(--sage-100)', overflow: 'hidden' }}>
            <div style={{ height: '100%', borderRadius: 5, width: shown ? it.pct + '%' : '0%',
              background: it.warn ? 'var(--clay)' : 'var(--green-500)',
              transition: `width 1s cubic-bezier(.4,0,.2,1) ${i * 0.12}s` }} />
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------- scripted answers ---------- */
const ANSWERS = {
  progress: {
    q: "How is Devon progressing on his leadership goals?",
    body: (<>Across 4 sessions, Devon's <b style={{ color: 'var(--ink)' }}>stakeholder confidence climbed from 3 → 7 / 10</b>. He now leads client retros solo. The one area still flagged: giving upward feedback to senior peers.</>),
    chart: <LineChart pts={[3, 3.5, 4.5, 5, 6, 7]} delta="+4.0" />,
  },
  risk: {
    q: "Who's at risk of disengaging?",
    body: (<>Two pairings show <b style={{ color: 'var(--ink)' }}>declining momentum</b> - fewer sessions and shorter notes. I'd nudge these this week.</>),
    chart: <Bars items={[
      { label: 'Priya × Sam', note: '2 sessions in 6 wks', pct: 28, warn: true },
      { label: 'Leo × Aisha', note: '1 session in 5 wks', pct: 16, warn: true },
      { label: 'Programme avg', note: 'on track', pct: 82 },
    ]} />,
  },
  themes: {
    q: "What themes came up across sessions this quarter?",
    body: (<>The dominant threads from <b style={{ color: 'var(--ink)' }}>142 sessions</b>, ranked by frequency:</>),
    chart: <Bars items={[
      { label: 'Stakeholder communication', note: '38%', pct: 38 },
      { label: 'Imposter syndrome', note: '24%', pct: 24 },
      { label: 'Career navigation', note: '21%', pct: 21 },
      { label: 'Giving feedback', note: '17%', pct: 17 },
    ]} />,
  },
  impact: {
    q: "Summarise the programme's impact so far",
    body: (<>Strong signal this quarter - engagement and confidence both up, and managers are seeing it land in performance reviews.</>),
    chart: (
      <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
        {[['+34%', 'avg confidence'], ['91%', 'session attendance'], ['4.7', 'mentee NPS-equiv']].map(([n, l]) => (
          <div key={l} style={{ background: 'var(--sage-50)', border: '1px solid var(--line-soft)', borderRadius: 12, padding: '14px 12px', textAlign: 'center' }}>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 26, color: 'var(--green-700)', lineHeight: 1 }}>{n}</div>
            <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 6 }}>{l}</div>
          </div>
        ))}
      </div>
    ),
  },
};
const SUGGESTIONS = ['progress', 'risk', 'themes', 'impact'];
const SUGG_LABEL = { progress: "Devon's progress", risk: 'Who\u2019s at risk?', themes: 'Top themes', impact: 'Programme impact' };

function matchAnswer(text) {
  const t = text.toLowerCase();
  if (/risk|disengag|drop|losing|inactive/.test(t)) return 'risk';
  if (/theme|topic|pattern|common|across/.test(t)) return 'themes';
  if (/impact|roi|summar|overall|result|working/.test(t)) return 'impact';
  if (/progress|devon|goal|confidence|improv/.test(t)) return 'progress';
  return 'progress';
}

/* ---------- the chat demo ---------- */
function ChatDemo() {
  const [msgs, setMsgs] = useState([
    { role: 'ai', body: (<>Hi - I'm your programme co-pilot. I've read every session across <b style={{ color: 'var(--ink)' }}>Acme's mentorship programme</b>. Ask me anything, or try a suggestion below.</>) },
  ]);
  const [typing, setTyping] = useState(false);
  const [input, setInput] = useState('');
  const [used, setUsed] = useState([]);
  const scroller = useRef(null);

  useEffect(() => {
    if (scroller.current) scroller.current.scrollTop = scroller.current.scrollHeight;
  }, [msgs, typing]);

  function ask(key, rawText) {
    if (typing) return;
    const a = ANSWERS[key];
    const userText = rawText || a.q;
    setMsgs((m) => [...m, { role: 'user', body: userText }]);
    setInput('');
    setUsed((u) => (u.includes(key) ? u : [...u, key]));
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setMsgs((m) => [...m, { role: 'ai', body: a.body, chart: a.chart }]);
    }, 1100);
  }

  function submit(e) {
    e.preventDefault();
    if (!input.trim() || typing) return;
    ask(matchAnswer(input), input.trim());
  }

  const remaining = SUGGESTIONS.filter((s) => !used.includes(s));

  return (
    <div className="mck" style={{ width: '100%', maxWidth: 560, overflow: 'hidden', display: 'flex', flexDirection: 'column', height: 560 }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '15px 18px', borderBottom: '1px solid var(--line-soft)' }}>
        <div style={{ width: 30, height: 30, borderRadius: 9, background: 'var(--sage-100)', display: 'grid', placeItems: 'center' }}><Sprout size={17} /></div>
        <div>
          <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: '-.01em' }}>Ask your programme</div>
          <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>Acme · 142 sessions indexed</div>
        </div>
        <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--green-600)', fontWeight: 600 }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--green-500)' }} />live
        </span>
      </div>
      {/* messages */}
      <div ref={scroller} style={{ flex: 1, overflowY: 'auto', padding: '18px', display: 'flex', flexDirection: 'column', gap: 14, background: 'var(--paper)' }}>
        {msgs.map((m, i) => m.role === 'user' ? (
          <div key={i} style={{ alignSelf: 'flex-end', background: 'var(--green-600)', color: '#fff', padding: '10px 14px', borderRadius: '14px 14px 4px 14px', fontSize: 14, maxWidth: '82%', boxShadow: 'var(--shadow-sm)' }}>{m.body}</div>
        ) : (
          <div key={i} style={{ display: 'flex', gap: 10, maxWidth: '94%' }}>
            <div style={{ width: 26, height: 26, borderRadius: 8, background: 'var(--sage-100)', display: 'grid', placeItems: 'center', flex: 'none', marginTop: 2 }}><Sprout size={14} /></div>
            <div style={{ background: 'var(--card)', border: '1px solid var(--line-soft)', borderRadius: '14px 14px 14px 4px', padding: '12px 15px', fontSize: 14, lineHeight: 1.55, color: 'var(--ink-soft)', boxShadow: 'var(--shadow-sm)' }}>
              {m.body}{m.chart}
            </div>
          </div>
        ))}
        {typing && (
          <div style={{ display: 'flex', gap: 10 }}>
            <div style={{ width: 26, height: 26, borderRadius: 8, background: 'var(--sage-100)', display: 'grid', placeItems: 'center', flex: 'none' }}><Sprout size={14} /></div>
            <div style={{ background: 'var(--card)', border: '1px solid var(--line-soft)', borderRadius: '14px 14px 14px 4px', padding: '14px 16px', display: 'flex', gap: 5 }}>
              {[0, 1, 2].map((d) => <span key={d} className="td" style={{ animationDelay: d * 0.16 + 's' }} />)}
            </div>
          </div>
        )}
      </div>
      {/* suggested prompts (no free input — this is a demo) */}
      <div style={{ padding: '14px 16px 16px', borderTop: '1px solid var(--line-soft)', background: 'var(--card)' }}>
        <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--faint)', marginBottom: 10 }}>Try asking</div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {SUGGESTIONS.map((s) => (
            <button key={s} onClick={() => ask(s)} disabled={typing} style={{ fontFamily: 'var(--sans)', cursor: typing ? 'default' : 'pointer', textAlign: 'left',
              fontSize: 13, fontWeight: 500, color: 'var(--ink-soft)', background: 'var(--paper)', border: '1px solid var(--line)',
              borderRadius: 10, padding: '9px 13px', display: 'inline-flex', alignItems: 'center', gap: 9, opacity: typing ? .5 : 1,
              transition: 'border-color .2s, background .2s' }}
              onMouseEnter={(e) => { if (!typing) { e.currentTarget.style.borderColor = 'var(--green-400)'; e.currentTarget.style.background = 'var(--sage-50)'; } }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.background = 'var(--paper)'; }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ flex: 'none', color: 'var(--green-600)' }}>
                <path d="M9 10 5 14l4 4M5 14h10a4 4 0 0 0 4-4V6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              <span>{ANSWERS[s].q}</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ChatDemo });
