/* Chip — savings chat assistant in Chip's green identity. 4 example question
   cards → tap → streaming answer with a breakdown,
   plus the fee-comparison flow that offers an ISA transfer to Chip.
   Relies on globals from chip.jsx (CHIP, CHIP_ACT, CHIP_ACT_DEEP, CHIP_INK, CHIP_LIME,
   PI, ChipMark, gbp, chipIconBtn) and Logo from collect-widget.jsx. */

function chipGbp(n) {
  return '£' + Math.round(n).toLocaleString('en-GB');
}

const CHIP_PROMPTS = [
{ id: 'diversification', q: 'How diversified are my savings?' },
{ id: 'rate', q: 'Where do I get the best interest rate?' },
{ id: 'split', q: 'How is my money split?' },
{ id: 'monthly', q: 'What do I save monthly?' }];

const FEES_PROMPT = { id: 'fees', q: 'How much would I save in fees moving my ISAs to Chip?' };


function buildChipAnswer(item, accounts) {
  const list = accounts && accounts.length ? accounts : [];
  const n = list.length;
  const banks = n === 1 ? 'account' : 'accounts';
  const total = list.reduce((s, p) => s + (p.balance || 0), 0);

  if (n === 0) {
    return {
      empty: true,
      intro: "I can't answer that just yet — I can't see any accounts from elsewhere. Connect one and I'll have the numbers ready.",
      lead: '', rows: [], total: null, close: ''
    };
  }

  if (item.id === 'free') {
    return {
      info: true,
      intro: `Good question. Right now I can pull exact figures on your total saved, your rates, how your money splits by type, and your monthly deposits — tap one of those suggestions and I'll get you the numbers.`,
      lead: '', rows: [], total: null, close: ''
    };
  }

  if (item.id === 'diversification') {
    const byType = {};
    list.forEach((p) => {
      const subs = p.accounts && p.accounts.length ? p.accounts : [{ type: p.accountType || 'Other', balance: p.balance || 0 }];
      subs.forEach((s) => {byType[s.type] = (byType[s.type] || 0) + (s.balance || 0);});
    });
    const rows = Object.entries(byType).sort((a, b) => b[1] - a[1]).map(([type, bal]) => ({ label: type, sub: `${Math.round(bal / total * 100)}% of portfolio`, value: chipGbp(bal) }));
    const top = rows[0];
    const topShare = top ? Math.round(byType[top.label] / total * 100) : 0;
    const provNames = list.map((p) => p.name);
    const provLabel = provNames.length > 2 ? `${provNames.slice(0, 2).join(', ')} and ${provNames.length - 2} more` : provNames.join(' and ');
    return {
      intro: `Your ${chipGbp(total)} sits across ${list.length} provider${list.length !== 1 ? 's' : ''} (${provLabel}) and ${rows.length} account type${rows.length !== 1 ? 's' : ''} — the largest slice is ${top ? top.label : 'one type'} at ${topShare}%. Want the full breakdown?`,
      lead: "Here's how your savings are diversified:",
      rows,
      total: { label: 'Total saved', value: chipGbp(total) },
      close: topShare > 50 ? `Over half sits in ${top.label}, so you're fairly concentrated in one type. Want ideas to spread it out?` : `That's a fairly balanced spread across your providers. Want me to suggest where to top up next?`
    };
  }

  if (item.id === 'fees') {
    const CHIP_FEE = 0.0045; // Chip flat fee
    const rows = list
    .map((p) => {
      const saving = (p.balance || 0) * Math.max(0, (p.feeRate || 0) - CHIP_FEE);
      return { provider: p, label: p.name, sub: `${((p.feeRate || 0) * 100).toFixed(2)}% → 0.45%`, value: chipGbp(saving) + '/yr', _saving: saving };
    })
    .filter((r) => r._saving > 0)
    .sort((a, b) => b._saving - a._saving);
    const totalSaving = rows.reduce((s, r) => s + r._saving, 0);
    const top = rows[0];
    const maxFee = Math.max(0, ...list.map((p) => p.feeRate || 0));
    const isaSubs = [];
    list.forEach((p) => {
      const subs = p.accounts && p.accounts.length ? p.accounts : [{ type: p.accountType || '', balance: p.balance || 0 }];
      subs.forEach((s) => {if (/ISA/i.test(s.type)) isaSubs.push({ provider: p.name, type: s.type, balance: s.balance || 0 });});
    });
    const isaValue = isaSubs.reduce((s, x) => s + (x.balance || 0), 0);
    return {
      transfer: true,
      isaCount: isaSubs.length,
      isaValue,
      isaList: isaSubs,
      intro: `Across ${list.length} provider${list.length !== 1 ? 's' : ''} you're paying up to ${(maxFee * 100).toFixed(2)}% in fees. Move your ISAs to Chip's flat 0.45% and you'd save about ${chipGbp(totalSaving)} a year. Want me to break it down by provider?`,
      lead: "Here's where the savings come from:",
      rows,
      total: { label: 'Total saved a year', value: chipGbp(totalSaving) },
      close: `Over 10 years that's roughly ${chipGbp(totalSaving * 10)}, with the biggest saving on your ${top ? top.label : 'priciest'} account. I can move your ${isaSubs.length} ISA${isaSubs.length !== 1 ? 's' : ''} (${chipGbp(isaValue)}) across to Chip for you.`
    };
  }

  if (item.id === 'rate') {
    const rows = list.map((p) => ({ provider: p, label: p.name, sub: p.isaTerm || 'Variable', value: `${(p.isaRate || 4.0).toFixed(2)}%` }));
    const best = list.reduce((a, b) => (a.isaRate || 0) >= (b.isaRate || 0) ? a : b, list[0] || {});
    return {
      intro: `Your best rate right now is ${(best.isaRate || 0).toFixed(2)}% with ${best.name}. Want me to compare them all?`,
      lead: 'Here are your rates, best first:',
      rows: rows.sort((a, b) => parseFloat(b.value) - parseFloat(a.value)),
      total: null,
      close: `Moving more savings into ${best.name} could earn you the most. Want me to set that up?`
    };
  }

  if (item.id === 'split') {
    const byType = {};
    list.forEach((p) => {
      const subs = p.accounts && p.accounts.length ? p.accounts : [{ type: p.accountType || 'Other', balance: p.balance || 0 }];
      subs.forEach((s) => {byType[s.type] = (byType[s.type] || 0) + (s.balance || 0);});
    });
    const rows = Object.entries(byType).sort((a, b) => b[1] - a[1]).map(([type, bal]) => ({
      label: type, sub: `${Math.round(bal / total * 100)}% of total`, value: chipGbp(bal)
    }));
    const topType = rows[0];
    return {
      intro: `Your ${chipGbp(total)} is spread across ${rows.length} account types. Want the full breakdown?`,
      lead: 'Here it is by type:',
      rows,
      total: { label: 'Total', value: chipGbp(total) },
      close: `Most of it sits in ${topType ? topType.label : 'one type'}. Want me to check if you're using your ISA allowance fully?`
    };
  }

  if (item.id === 'monthly') {
    const rows = list.map((p) => ({ provider: p, label: p.name, sub: 'Monthly deposit', value: chipGbp(p.monthly || 0) + '/mo' }));
    const monthly = list.reduce((s, p) => s + (p.monthly || 0), 0);
    const top = list.reduce((a, b) => (a.monthly || 0) >= (b.monthly || 0) ? a : b, list[0] || {});
    return {
      intro: `You're putting away about ${chipGbp(monthly)} a month across your ${banks}. Want the split?`,
      lead: "Here's the monthly split:",
      rows,
      total: { label: 'Total a month', value: chipGbp(monthly) },
      close: `That's about ${chipGbp(monthly * 12)} a year, mostly into ${top.name}. Want me to suggest where new savings would grow fastest?`
    };
  }

  return { intro: '', lead: '', rows: [], total: null, close: '' };
}

function useChipTyping(text, active, speed = 15) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {if (!active) setN(0);}, [active]);
  React.useEffect(() => {
    if (!active || n >= text.length) return;
    const t = setTimeout(() => setN((v) => v + 1), speed);
    return () => clearTimeout(t);
  }, [active, n, text, speed]);
  return { shown: text.slice(0, n), done: active && n >= text.length };
}

function ChipDots() {
  return (
    <span style={{ display: 'inline-flex', gap: 5, alignItems: 'center', padding: '6px 0' }}>
      {[0, 1, 2].map((i) =>
      <span key={i} style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--neutral-7)', display: 'inline-block', animation: 'chipBlink 1.2s infinite', animationDelay: i * 0.18 + 's' }} />
      )}
    </span>);

}

function ChipBreakdown({ rows, total }) {
  return (
    <div style={{ marginTop: 14, background: '#fff', border: '1px solid var(--neutral-4)', borderRadius: 16, padding: '4px 16px' }}>
      {rows.map((r, i) =>
      <div key={i} className="chip-row-in" style={{ animationDelay: i * 0.1 + 's', display: 'flex', alignItems: 'center', gap: 12, justifyContent: 'space-between', padding: '13px 0', borderBottom: total || i < rows.length - 1 ? '1px solid var(--neutral-4)' : 'none' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 11, minWidth: 0 }}>
            {r.provider ? <Logo p={r.provider} size={32} /> :
          <span style={{ width: 9, height: 9, borderRadius: '50%', background: CHIP_ACT, flexShrink: 0, marginLeft: 2, marginRight: 2 }} />}
            <span style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
              <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15, color: CHIP_INK, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.label}</span>
              {r.sub && <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 12.5, color: 'var(--neutral-9)' }}>{r.sub}</span>}
            </span>
          </span>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15, color: CHIP_INK, flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>{r.value}</span>
        </div>
      )}
      {total &&
      <div className="chip-row-in" style={{ animationDelay: rows.length * 0.1 + 's', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '13px 0' }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15, color: CHIP_INK }}>{total.label}</span>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 17, color: CHIP_ACT, fontVariantNumeric: 'tabular-nums' }}>{total.value}</span>
        </div>
      }
    </div>);

}

function ChipPromptCard({ item, onTap, wide }) {
  const [press, setPress] = React.useState(false);
  return (
    <button onMouseDown={() => setPress(true)} onMouseUp={() => setPress(false)} onMouseLeave={() => setPress(false)} onClick={() => onTap(item)}
    style={{ gridColumn: wide ? '1 / -1' : 'auto', appearance: 'none', border: '1px solid var(--neutral-4)', background: press ? 'var(--mint-2)' : '#fff', borderRadius: 20, padding: '18px 18px 20px', minHeight: 150, cursor: 'pointer', textAlign: 'left', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 18, transition: 'background 180ms cubic-bezier(0.2,0.7,0.2,1)' }}>
      <span style={{ width: 38, height: 38, borderRadius: 12, background: 'var(--mint-1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <PI size={21} c={CHIP_ACT} w={2}><path d="M21 11.5a8.4 8.4 0 0 1-9 8.4 9 9 0 0 1-3.8-.8L3 20l1.3-3.9A8.4 8.4 0 0 1 3.5 11.5 8.5 8.5 0 0 1 12 3a8.5 8.5 0 0 1 9 8.5z" /></PI>
      </span>
      <span style={{ fontFamily: 'var(--font-body)', fontSize: 17, lineHeight: '23px', fontWeight: 600, color: CHIP_INK, letterSpacing: '-0.2px' }}>{item.q}</span>
    </button>);

}

function ChipChip({ label, onClick, primary }) {
  const [press, setPress] = React.useState(false);
  return (
    <button onMouseDown={() => setPress(true)} onMouseUp={() => setPress(false)} onMouseLeave={() => setPress(false)} onClick={onClick}
    style={{
      appearance: 'none', cursor: 'pointer', borderRadius: 1000, padding: '13px 20px',
      fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15.5, letterSpacing: '-0.1px', whiteSpace: 'nowrap',
      border: primary ? 'none' : '1px solid var(--neutral-5)',
      background: primary ? (press ? CHIP_ACT_DEEP : CHIP_ACT) : press ? 'var(--neutral-3)' : '#fff',
      color: primary ? '#fff' : CHIP_INK,
      transition: 'background 180ms cubic-bezier(0.2,0.7,0.2,1)'
    }}>{label}</button>);

}

function ChipChatScreen({ accounts, onBack, onConnect, onTransfer }) {
  const [item, setItem] = React.useState(null);
  const [draft, setDraft] = React.useState('');
  const hasAccounts = accounts && accounts.length > 0;

  const submit = () => {
    const q = draft.trim();
    if (!q) return;
    setItem({ id: 'free', q });
    setDraft('');
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff' }}>
      {/* header */}
      <div style={{ flexShrink: 0, paddingTop: 58, padding: '58px 20px 14px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--neutral-4)' }}>
        <button onClick={item ? () => setItem(null) : onBack} aria-label="Back" style={{ ...chipIconBtn }}>
          <PI size={26} c={CHIP_INK} w={2.1}><path d="M15 5l-7 7 7 7" /></PI>
        </button>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 30, height: 30, borderRadius: '50%', background: CHIP, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><ChipMark size={19} c="#fff" ring={CHIP_LIME} /></span>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 18, color: CHIP_INK }}>Chip Assistant</span>
        </span>
      </div>

      {item ? <ChipConversation key={item.q} item={item} accounts={accounts} onConnect={onConnect} onTransfer={onTransfer} /> :
      <div style={{ flex: 1, overflowY: 'auto', padding: '22px 20px 28px' }}>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 300, fontSize: 32, lineHeight: '37px', letterSpacing: '-0.02em', color: CHIP_INK, margin: 0 }}>Ask me anything<br />about your savings</h1>
          <p style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 15, lineHeight: '21px', color: 'var(--neutral-9)', marginTop: 10 }}>{hasAccounts ? `I can see your ${accounts.length} connected account${accounts.length !== 1 ? 's' : ''}. Try one of these, or just ask below:` : 'Try one of these, or just ask below:'}</p>
          <div style={{ marginTop: 20, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {CHIP_PROMPTS.map((p) => <ChipPromptCard key={p.id} item={p} onTap={setItem} />)}
            <ChipPromptCard item={FEES_PROMPT} onTap={setItem} wide />
          </div>
        </div>}

      {/* ask-anything input */}
      <div style={{ flexShrink: 0, borderTop: '1px solid var(--neutral-4)', background: '#fff', padding: '12px 16px 26px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <input value={draft} onChange={(e) => setDraft(e.target.value)} onKeyDown={(e) => {if (e.key === 'Enter') submit();}} placeholder="Ask anything…"
        style={{ flex: 1, height: 48, border: '1px solid var(--neutral-5)', borderRadius: 1000, padding: '0 18px', fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 15.5, color: CHIP_INK, outline: 'none', background: '#fff' }} />
        <button onClick={submit} aria-label="Send" disabled={!draft.trim()} style={{ width: 48, height: 48, borderRadius: '50%', border: 'none', flexShrink: 0, cursor: draft.trim() ? 'pointer' : 'default', background: draft.trim() ? CHIP_ACT : 'var(--neutral-5)', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'background 180ms cubic-bezier(0.2,0.7,0.2,1)' }}>
          <PI size={20} c="#fff" w={2.3}><path d="M5 12h13M12 6l6 6-6 6" /></PI>
        </button>
      </div>
    </div>);

}

function ChipConversation({ item, accounts, onConnect, onTransfer }) {
  const ans = React.useMemo(() => buildChipAnswer(item, accounts), [item, accounts]);
  const [thinking, setThinking] = React.useState(true);
  const [choice, setChoice] = React.useState(null);
  const [aStage, setAStage] = React.useState(0);
  const scRef = React.useRef(null);

  React.useEffect(() => {const t = setTimeout(() => setThinking(false), 800);return () => clearTimeout(t);}, []);
  const intro = useChipTyping(ans.intro, !thinking);

  React.useEffect(() => {if (choice === 'yes') setAStage(1);}, [choice]);
  const lead = useChipTyping(ans.lead, choice === 'yes' && aStage >= 1);
  React.useEffect(() => {if (lead.done && aStage === 1) {const t = setTimeout(() => setAStage(2), 200);return () => clearTimeout(t);}}, [lead.done, aStage]);
  React.useEffect(() => {
    if (aStage === 2) {const delay = ans.rows ? 280 + (ans.rows.length + (ans.total ? 1 : 0)) * 120 : 60;const t = setTimeout(() => setAStage(3), delay);return () => clearTimeout(t);}
  }, [aStage]);
  const close = useChipTyping(ans.close, choice === 'yes' && aStage >= 3);
  const noReply = useChipTyping("No problem. I'm here whenever you want to dig in.", choice === 'no');

  React.useEffect(() => {if (scRef.current) scRef.current.scrollTop = scRef.current.scrollHeight;});

  const qFlat = item.q.replace(/\n/g, ' ');
  const answerP = { fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 18, lineHeight: '26px', color: CHIP_INK, letterSpacing: '-0.2px' };

  return (
    <div ref={scRef} style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 20, padding: '22px 20px 24px' }}>
      {/* user */}
      <div className="chip-msg-in" style={{ alignSelf: 'flex-end', maxWidth: '82%', background: CHIP_ACT, borderRadius: '20px 20px 6px 20px', padding: '13px 17px' }}>
        <div style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 16.5, lineHeight: '22px', color: '#fff', letterSpacing: '-0.1px' }}>{qFlat}</div>
      </div>

      {/* assistant */}
      <div className="chip-msg-in" style={{ alignSelf: 'stretch' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
          <span style={{ width: 22, height: 22, borderRadius: '50%', background: CHIP, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><ChipMark size={14} c="#fff" ring={CHIP_LIME} /></span>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14.5, color: 'var(--neutral-9)' }}>Chip</span>
        </div>

        {thinking ? <ChipDots /> :
        <React.Fragment>
            <p style={{ ...answerP, margin: 0 }}>{intro.shown}{!intro.done && <span className="chip-caret" />}</p>

            {intro.done && !choice && ans.empty &&
          <button onClick={onConnect} style={{ marginTop: 18, height: 50, padding: '0 24px', borderRadius: 1000, border: 'none', cursor: 'pointer', background: CHIP_ACT, color: '#fff', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15.5 }}>Connect an account</button>}

            {intro.done && !choice && !ans.empty && !ans.info &&
          <div style={{ display: 'flex', gap: 10, marginTop: 18, flexWrap: 'wrap' }}>
                <ChipChip label="Yes, break it down" primary onClick={() => setChoice('yes')} />
                <ChipChip label="No, thanks" onClick={() => setChoice('no')} />
              </div>}

            {choice === 'yes' &&
          <React.Fragment>
                <p style={{ ...answerP, marginTop: 16, marginBottom: 0 }}>{lead.shown}{!lead.done && <span className="chip-caret" />}</p>
                {aStage >= 2 && ans.rows && <ChipBreakdown rows={ans.rows} total={ans.total} />}
                {aStage >= 3 && <p style={{ ...answerP, marginTop: 16, marginBottom: 0 }}>{close.shown}{!close.done && <span className="chip-caret" />}</p>}
                {aStage >= 3 && close.done && ans.transfer &&
              <button onClick={() => onTransfer && onTransfer({ isaList: ans.isaList, isaValue: ans.isaValue, isaCount: ans.isaCount })} style={{ marginTop: 18, width: '100%', height: 54, borderRadius: 1000, border: 'none', cursor: 'pointer', background: CHIP_ACT, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16.5 }}>
                    <PI size={20} c="#fff" w={2.1}><path d="M4 12h13M11 6l6 6-6 6" /></PI>
                    <span>{`Move my ISA${ans.isaCount !== 1 ? 's' : ''} to Chip`}</span>
                  </button>}
              </React.Fragment>}

            {choice === 'no' && <p style={{ ...answerP, marginTop: 16, marginBottom: 0 }}>{noReply.shown}{!noReply.done && <span className="chip-caret" />}</p>}
          </React.Fragment>}
      </div>
    </div>);

}

function TransferScreen({ data, onClose }) {
  const list = (data && data.isaList) || [];
  const steps = ['Review', 'Confirm', 'Transfer'];
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff' }}>
      {/* header */}
      <div style={{ flexShrink: 0, paddingTop: 58, padding: '58px 20px 14px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--neutral-4)' }}>
        <button onClick={onClose} aria-label="Close" style={{ ...chipIconBtn }}>
          <PI size={26} c={CHIP_INK} w={2.1}><path d="M6 6l12 12M18 6L6 18" /></PI>
        </button>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 18, color: CHIP_INK }}>Transfer to Chip</span>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '24px 20px 28px' }}>
        {/* step indicator */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 24 }}>
          {steps.map((s, i) =>
          <React.Fragment key={s}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ width: 26, height: 26, borderRadius: '50%', flexShrink: 0, background: i === 0 ? CHIP_ACT : 'var(--neutral-3)', color: i === 0 ? '#fff' : 'var(--neutral-9)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13 }}>{i + 1}</span>
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13.5, color: i === 0 ? CHIP_INK : 'var(--neutral-9)' }}>{s}</span>
              </div>
              {i < steps.length - 1 && <span style={{ flex: 1, height: 1.5, background: 'var(--neutral-4)' }} />}
            </React.Fragment>
          )}
        </div>

        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 300, fontSize: 30, lineHeight: '36px', letterSpacing: '-0.02em', color: CHIP_INK, margin: 0 }}>Review your transfer</h1>
        <p style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 15, lineHeight: '21px', color: 'var(--neutral-9)', marginTop: 10 }}>
          {data && data.isaCount} ISA{data && data.isaCount !== 1 ? 's' : ''} will move to your Chip account. Your existing providers stay open until the cash lands.
        </p>

        <div style={{ marginTop: 20, border: '1px solid var(--neutral-4)', borderRadius: 16, padding: '4px 16px' }}>
          {list.map((a, i) =>
          <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '15px 0', borderBottom: i < list.length - 1 ? '1px solid var(--neutral-4)' : 'none' }}>
              <span style={{ minWidth: 0, display: 'flex', flexDirection: 'column', gap: 3 }}>
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16, color: CHIP_INK, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.type}</span>
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13, color: 'var(--neutral-9)' }}>{a.provider}</span>
              </span>
              <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16, color: CHIP_INK, flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>{chipGbp(a.balance || 0)}</span>
            </div>
          )}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '15px 0', borderTop: list.length ? '1px solid var(--neutral-4)' : 'none' }}>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16, color: CHIP_INK }}>Total transferring</span>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 18, color: CHIP_ACT, fontVariantNumeric: 'tabular-nums' }}>{chipGbp((data && data.isaValue) || 0)}</span>
          </div>
        </div>

        <div style={{ marginTop: 18, display: 'flex', alignItems: 'flex-start', gap: 10, background: 'var(--mint-2)', borderRadius: 14, padding: '14px 16px' }}>
          <PI size={19} c={CHIP_ACT} w={2}><circle cx="12" cy="12" r="9" /><path d="M12 16v-4M12 8h.01" /></PI>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13.5, lineHeight: '19px', color: CHIP_INK }}>Transfers are handled provider-to-provider and usually complete in about 14 minutes. You keep your full ISA allowance.</span>
        </div>
      </div>

      {/* footer CTA (placeholder) */}
      <div style={{ flexShrink: 0, borderTop: '1px solid var(--neutral-4)', background: '#fff', padding: '14px 20px 28px' }}>
        <button style={{ width: '100%', height: 56, borderRadius: 1000, border: 'none', cursor: 'pointer', background: CHIP_ACT, color: '#fff', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 17 }}>Start transfer</button>
      </div>
    </div>);

}

Object.assign(window, { ChipChatScreen, TransferScreen });
