/* Stratiphy — AI portfolio assistant. Reskin of the Chip assistant into
   Stratiphy's violet identity. Example question cards → streaming answer with a
   breakdown, plus the fee-comparison flow that offers an ISA transfer to Stratiphy.
   Relies on globals from stratiphy.jsx (STR_PURPLE, STR_PURPLE_DEEP, STR_INK,
   STR_GREEN, STR_PURPLE_SOFT, PI, StratAvatar, gbp, strIconBtn) and Logo from
   collect-widget.jsx. */

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

const STR_PROMPTS = [
{ id: 'diversification', q: 'How diversified is my portfolio?' },
{ id: 'rate', q: 'Where am I getting the best return?' },
{ id: 'split', q: 'How is my money split?' },
{ id: 'monthly', q: 'What do I invest monthly?' }];

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


function buildStratAnswer(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 invested, your returns, how your money splits by type, and your monthly contributions — 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: strGbp(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 ${strGbp(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 holdings are diversified:",
      rows,
      total: { label: 'Total invested', value: strGbp(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 STR_FEE = 0.0045; // Stratiphy flat fee
    const rows = list
    .map((p) => {
      const saving = (p.balance || 0) * Math.max(0, (p.feeRate || 0) - STR_FEE);
      return { provider: p, label: p.name, sub: `${((p.feeRate || 0) * 100).toFixed(2)}% → 0.45%`, value: strGbp(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 Stratiphy's flat 0.45% and you'd save about ${strGbp(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: strGbp(totalSaving) },
      close: `Over 10 years that's roughly ${strGbp(totalSaving * 10)}, with the biggest saving on your ${top ? top.label : 'priciest'} account. I can move your ${isaSubs.length} ISA${isaSubs.length !== 1 ? 's' : ''} (${strGbp(isaValue)}) across to Stratiphy for you.`
    };
  }

  if (item.id === 'rate') {
    const rows = list.map((p) => ({ provider: p, label: p.name, sub: `${(p.ytd || 0).toFixed(1)}% YTD`, value: `${(p.ytd || 0).toFixed(1)}%` }));
    const best = list.reduce((a, b) => (a.ytd || 0) >= (b.ytd || 0) ? a : b, list[0] || {});
    return {
      intro: `Your strongest return right now is ${(best.ytd || 0).toFixed(1)}% with ${best.name}. Want me to compare them all?`,
      lead: 'Here are your returns, best first:',
      rows: rows.sort((a, b) => parseFloat(b.value) - parseFloat(a.value)),
      total: null,
      close: `${best.name} is pulling ahead. Want me to model how a Stratiphy strategy would have tracked against it?`
    };
  }

  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: strGbp(bal)
    }));
    const topType = rows[0];
    return {
      intro: `Your ${strGbp(total)} is spread across ${rows.length} account types. Want the full breakdown?`,
      lead: 'Here it is by type:',
      rows,
      total: { label: 'Total', value: strGbp(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 contribution', value: strGbp(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 ${strGbp(monthly)} a month across your ${banks}. Want the split?`,
      lead: "Here's the monthly split:",
      rows,
      total: { label: 'Total a month', value: strGbp(monthly) },
      close: `That's about ${strGbp(monthly * 12)} a year, mostly into ${top.name}. Want me to suggest where new contributions would grow fastest?`
    };
  }

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

function useStrTyping(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 StrDots() {
  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 StrBreakdown({ 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: STR_PURPLE, 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: STR_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: STR_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: STR_INK }}>{total.label}</span>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 17, color: STR_PURPLE, fontVariantNumeric: 'tabular-nums' }}>{total.value}</span>
        </div>
      }
    </div>);

}

function StrPromptCard({ 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 ? STR_PURPLE_SOFT : '#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: STR_PURPLE_SOFT, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <PI size={21} c={STR_PURPLE} 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: STR_INK, letterSpacing: '-0.2px' }}>{item.q}</span>
    </button>);

}

function StrChip({ 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 ? STR_PURPLE_DEEP : STR_PURPLE) : press ? 'var(--neutral-3)' : '#fff',
      color: primary ? '#fff' : STR_INK,
      transition: 'background 180ms cubic-bezier(0.2,0.7,0.2,1)'
    }}>{label}</button>);

}

function StratiphyChatScreen({ 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, 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={{ ...strIconBtn }}>
          <PI size={26} c={STR_INK} w={2.1}><path d="M15 5l-7 7 7 7" /></PI>
        </button>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <StratAvatar size={30} />
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 18, color: STR_INK }}>Stratiphy Assistant</span>
        </span>
      </div>

      {item ? <StratiphyConversation 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: 700, fontSize: 32, lineHeight: '37px', letterSpacing: '-0.02em', color: STR_INK, margin: 0 }}>Ask me anything<br />about your portfolio</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 }}>
            {STR_PROMPTS.map((p) => <StrPromptCard key={p.id} item={p} onTap={setItem} />)}
            <StrPromptCard item={STR_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: STR_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() ? STR_PURPLE : '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 StratiphyConversation({ item, accounts, onConnect, onTransfer }) {
  const ans = React.useMemo(() => buildStratAnswer(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 = useStrTyping(ans.intro, !thinking);

  React.useEffect(() => {if (choice === 'yes') setAStage(1);}, [choice]);
  const lead = useStrTyping(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 = useStrTyping(ans.close, choice === 'yes' && aStage >= 3);
  const noReply = useStrTyping("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: STR_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: STR_PURPLE, 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 }}>
          <StratAvatar size={22} />
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14.5, color: 'var(--neutral-9)' }}>Stratiphy</span>
        </div>

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

            {intro.done && !choice && ans.empty &&
          <button onClick={onConnect} style={{ marginTop: 18, height: 50, padding: '0 24px', borderRadius: 1000, border: 'none', cursor: 'pointer', background: STR_PURPLE, 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' }}>
                <StrChip label="Yes, break it down" primary onClick={() => setChoice('yes')} />
                <StrChip 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" style={{ background: STR_PURPLE }} />}</p>
                {aStage >= 2 && ans.rows && <StrBreakdown rows={ans.rows} total={ans.total} />}
                {aStage >= 3 && <p style={{ ...answerP, marginTop: 16, marginBottom: 0 }}>{close.shown}{!close.done && <span className="chip-caret" style={{ background: STR_PURPLE }} />}</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: STR_PURPLE, 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 Stratiphy`}</span>
                  </button>}
              </React.Fragment>}

            {choice === 'no' && <p style={{ ...answerP, marginTop: 16, marginBottom: 0 }}>{noReply.shown}{!noReply.done && <span className="chip-caret" style={{ background: STR_PURPLE }} />}</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, padding: '58px 20px 14px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--neutral-4)' }}>
        <button onClick={onClose} aria-label="Close" style={{ ...strIconBtn }}>
          <PI size={26} c={STR_INK} w={2.1}><path d="M6 6l12 12M18 6L6 18" /></PI>
        </button>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 18, color: STR_INK }}>Transfer to Stratiphy</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 ? STR_PURPLE : '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 ? STR_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: 700, fontSize: 30, lineHeight: '36px', letterSpacing: '-0.02em', color: STR_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 Stratiphy account. Your existing providers stay open until the transfer 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: STR_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: STR_INK, flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>{strGbp(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: STR_INK }}>Total transferring</span>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 18, color: STR_PURPLE, fontVariantNumeric: 'tabular-nums' }}>{strGbp((data && data.isaValue) || 0)}</span>
          </div>
        </div>

        <div style={{ marginTop: 18, display: 'flex', alignItems: 'flex-start', gap: 10, background: STR_PURPLE_SOFT, borderRadius: 14, padding: '14px 16px' }}>
          <PI size={19} c={STR_PURPLE} 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: STR_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: STR_PURPLE, color: '#fff', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 17 }}>Start transfer</button>
      </div>
    </div>);

}

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