/* Stratiphy — AI investing app Portfolio home screen, recreated from product
   screenshots. Hosts the shared Insurely collect-data widget (collect-widget.jsx)
   plus a Stratiphy-skinned AI assistant + ISA transfer journey (stratiphy-chat.jsx).
   The "Stratiphy" UI here is a faithful mock for an Insurely integration demo. */

const STR_PURPLE = '#5B3DF5'; // brand violet — primary CTAs, strategy accents
const STR_PURPLE_DEEP = '#4A2ED6'; // pressed
const STR_PURPLE_SOFT = '#ECE7FE'; // light violet fills
const STR_GOLD = '#F7B500'; // amber — active tabs / highlights
const STR_GOLD_SOFT = '#FFF2CF';
const STR_GREEN = '#16BE72'; // gains, positive deltas
const STR_GREEN_SOFT = '#E0F6EC';
const STR_INK = '#16161D'; // near-black text

/* ---- inline icon helper (line, 2px, rounded — DS iconography) ---- */
function PI({ size = 24, c = STR_INK, w = 1.9, children }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
    stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
      {children}
    </svg>);

}

/* Stratiphy mark — three-segment donut (portfolio allocation). Used as the
   header glyph + brand avatar. */
function StratDonut({ size = 24, sw = 5 }) {
  const r = 9;
  const c = 2 * Math.PI * r;
  const seg = (f) => `${(c * f).toFixed(2)} ${(c - c * f).toFixed(2)}`;
  const off = (f) => (-c * f).toFixed(2);
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: 'block', transform: 'rotate(-90deg)' }}>
      <circle cx="12" cy="12" r={r} fill="none" stroke={STR_PURPLE} strokeWidth={sw} strokeDasharray={seg(0.55)} />
      <circle cx="12" cy="12" r={r} fill="none" stroke={STR_GOLD} strokeWidth={sw} strokeDasharray={seg(0.28)} strokeDashoffset={off(0.55)} />
      <circle cx="12" cy="12" r={r} fill="none" stroke={STR_GREEN} strokeWidth={sw} strokeDasharray={seg(0.17)} strokeDashoffset={off(0.83)} />
    </svg>);

}

/* Chat assistant avatar — purple circle with a white pie wedge */
function StratAvatar({ size = 30 }) {
  return (
    <span style={{ width: size, height: size, borderRadius: '50%', background: STR_PURPLE, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      <svg width={size * 0.58} height={size * 0.58} viewBox="0 0 24 24" style={{ display: 'block' }}>
        <circle cx="12" cy="12" r="8.4" fill="none" stroke="#fff" strokeWidth="2.2" />
        <path d="M12 12V3.6 A8.4 8.4 0 0 1 19.4 8.4 Z" fill="#fff" />
      </svg>
    </span>);

}

function gbp(n) {
  return '£' + n.toLocaleString('en-GB', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

/* big balance — whole large, pence raised + smaller */
function Money({ value, size = 44, color = STR_INK }) {
  const [whole, dec] = value.toFixed(2).split('.');
  return (
    <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, color, letterSpacing: '-1.2px', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
      <span style={{ fontSize: size }}>£{whole}</span>
      <span style={{ fontSize: size * 0.56, verticalAlign: 'baseline' }}>.{dec}</span>
    </span>);

}

/* ===================== PORTFOLIO HEADER + BALANCE ===================== */

function PortfolioHeader() {
  return (
    <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '4px 4px 2px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 19, color: STR_INK, letterSpacing: '-0.3px' }}>Portfolio</span>
        <span style={{ width: 17, height: 17, borderRadius: '50%', border: '1.5px solid var(--neutral-7)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 11, color: 'var(--neutral-8)' }}>i</span>
      </div>
      <span style={{ position: 'absolute', right: 2, top: '50%', transform: 'translateY(-50%)' }}><StratDonut size={26} sw={5.4} /></span>
    </div>);

}

function BalanceBlock({ total, pct, up }) {
  return (
    <div style={{ marginTop: 14 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <Money value={total} size={44} />
        <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 1, paddingTop: 4 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 18, color: STR_GREEN, fontVariantNumeric: 'tabular-nums' }}>+{pct}%</span>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13.5, color: 'var(--neutral-8)' }}>Return</span>
        </span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 9, whiteSpace: 'nowrap' }}>
        <PI size={14} c={STR_GREEN} w={2.6}><path d="M7 17L17 7M17 7H9M17 7v8" /></PI>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13.5, color: 'var(--neutral-9)' }}>Up by</span>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13.5, color: STR_GREEN, fontVariantNumeric: 'tabular-nums' }}>{gbp(up)}</span>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13.5, color: 'var(--neutral-9)' }}>since you began</span>
      </div>
    </div>);

}

/* ===================== PERFORMANCE CHART ===================== */

function PerfChart() {
  const line = 'M0,96 C18,86 34,73 54,80 C74,87 84,109 104,102 C122,96 132,85 152,90 C170,94 178,75 198,65 C214,56 222,73 242,57 C260,43 270,39 292,25 C302,20 312,16 320,13';
  const yLabels = [['10%', 8], ['8%', 41], ['6%', 74], ['4%', 107], ['2%', 140]];
  const xLabels = ['Jan 23', 'May 23', 'Sep 23', 'Jan 24'];
  return (
    <div style={{ marginTop: 16 }}>
      <div style={{ position: 'relative', height: 152 }}>
        <svg viewBox="0 0 320 152" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block', overflow: 'visible' }}>
          <path d={line} fill="none" stroke={STR_INK} strokeWidth="2.6" strokeLinejoin="round" strokeLinecap="round" />
        </svg>
        {yLabels.map(([t, top]) =>
        <span key={t} style={{ position: 'absolute', right: 0, top, transform: 'translateY(-50%)', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 11, color: 'var(--neutral-7)' }}>{t}</span>
        )}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 4px 0' }}>
        {xLabels.map((t) =>
        <span key={t} style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 11.5, color: 'var(--neutral-8)' }}>{t}</span>
        )}
      </div>
    </div>);

}

const PERIODS = ['1d', '1w', '1m', 'YTD', 'All Time'];

function PeriodTabs() {
  const [active, setActive] = React.useState('YTD');
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 6px 4px' }}>
      {PERIODS.map((p) => {
        const on = p === active;
        return (
          <button key={p} onClick={() => setActive(p)} style={{ appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, padding: '2px 4px' }}>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: on ? 700 : 500, fontSize: 14.5, color: on ? STR_INK : 'var(--neutral-8)' }}>{p}</span>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: on ? STR_GOLD : 'var(--neutral-4)' }} />
          </button>);

      })}
    </div>);

}

/* ===================== HOLDINGS ===================== */

function HoldingsToggle({ tab, setTab }) {
  const half = (id, label) => {
    const on = tab === id;
    return (
      <button onClick={() => setTab(id)} style={{ flex: 1, appearance: 'none', border: 'none', cursor: 'pointer', height: 42, borderRadius: 10, background: on ? STR_GOLD : 'transparent', color: STR_INK, fontFamily: 'var(--font-body)', fontWeight: on ? 700 : 600, fontSize: 15.5, transition: 'background 180ms cubic-bezier(0.2,0.7,0.2,1)' }}>{label}</button>);

  };
  return (
    <div style={{ marginTop: 18, display: 'flex', gap: 6, padding: 5, background: '#fff', border: '1px solid var(--neutral-4)', borderRadius: 14 }}>
      {half('holdings', 'Holdings')}
      {half('activity', 'Activity')}
    </div>);

}

const HOLDINGS = [
{ name: 'Starbucks', mono: 'S', color: '#0B6E4F', badge: 'Top Performance', emoji: '🚀', value: 1654.11, shares: '6 Shares', pct: '5.34' },
{ name: 'Nio', mono: 'N', color: '#00BEFF', badge: '#1 Environmental', emoji: '🌱', value: 526.12, shares: '6 Shares', pct: '3.21' },
{ name: 'Meta', mono: 'M', color: '#0866FF', badge: null, value: 526.12, shares: '6 Shares', pct: '1.78' }];


function GreenArrow() {
  return (
    <span style={{ width: 26, height: 26, borderRadius: '50%', background: STR_GREEN, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      <PI size={14} c="#fff" w={2.6}><path d="M7 17L17 7M17 7H9M17 7v8" /></PI>
    </span>);

}

function CashRow() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '15px 16px', borderBottom: '1px solid var(--neutral-4)' }}>
      <span style={{ width: 38, height: 38, borderRadius: '50%', background: STR_GOLD, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 19, color: '#fff' }}>£</span>
      <span style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 2 }}>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16.5, color: STR_INK }}>Cash</span>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13, color: 'var(--neutral-9)' }}>
          <span style={{ fontWeight: 600, color: STR_INK, fontVariantNumeric: 'tabular-nums' }}>£239.11</span> Available
        </span>
      </span>
      <span style={{ textAlign: 'right', fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 12.5, color: 'var(--neutral-8)', whiteSpace: 'nowrap' }}>
        <span style={{ fontWeight: 600, color: 'var(--neutral-10)', fontVariantNumeric: 'tabular-nums' }}>£39.15</span> Pending orders
      </span>
    </div>);

}

function StockRow({ h, last }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '15px 16px', borderBottom: last ? 'none' : '1px solid var(--neutral-4)' }}>
      <Logo p={h} size={38} />
      <span style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 3 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16.5, color: STR_INK, whiteSpace: 'nowrap' }}>{h.name}</span>
          {h.badge &&
          <span style={{ flexShrink: 0, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 11.5, color: 'var(--neutral-10)', background: 'var(--neutral-3)', borderRadius: 1000, padding: '3px 9px', whiteSpace: 'nowrap' }}>{h.badge}{h.emoji ? ' ' + h.emoji : ''}</span>}
        </span>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13, color: 'var(--neutral-9)' }}>
          <span style={{ fontWeight: 600, color: STR_INK, fontSize: 14, fontVariantNumeric: 'tabular-nums' }}>{gbp(h.value)}</span> · {h.shares}
        </span>
      </span>
      <span style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15, color: STR_GREEN, fontVariantNumeric: 'tabular-nums' }}>{h.pct}%</span>
        <GreenArrow />
      </span>
    </div>);

}

function HoldingsList() {
  return (
    <div style={{ marginTop: 14, background: '#fff', border: '1px solid var(--neutral-4)', borderRadius: 18, boxShadow: 'var(--elevation-default)', overflow: 'hidden' }}>
      <CashRow />
      {HOLDINGS.map((h, i) => <StockRow key={h.name} h={h} last={i === HOLDINGS.length - 1} />)}
    </div>);

}

function ActivityList() {
  const acts = [
  { name: 'Starbucks', mono: 'S', color: '#0B6E4F', side: 'Buy', detail: '2 Shares · 12 Jun', amt: 551.37 },
  { name: 'Meta', mono: 'M', color: '#0866FF', side: 'Buy', detail: '1 Share · 9 Jun', amt: 526.12 },
  { name: 'Nio', mono: 'N', color: '#00BEFF', side: 'Sell', detail: '3 Shares · 2 Jun', amt: 158.40 }];

  return (
    <div style={{ marginTop: 14, background: '#fff', border: '1px solid var(--neutral-4)', borderRadius: 18, boxShadow: 'var(--elevation-default)', overflow: 'hidden' }}>
      {acts.map((a, i) =>
      <div key={a.name} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '15px 16px', borderBottom: i < acts.length - 1 ? '1px solid var(--neutral-4)' : 'none' }}>
          <Logo p={a} size={38} />
          <span style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 2 }}>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16.5, color: STR_INK }}>{a.side} {a.name}</span>
            <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13, color: 'var(--neutral-9)' }}>{a.detail}</span>
          </span>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15.5, color: STR_INK, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>{a.side === 'Sell' ? '+' : '−'}{gbp(a.amt)}</span>
        </div>
      )}
    </div>);

}

/* ===================== INSURELY CONNECT (host function) ===================== */

function ConnectBanner({ connected, accounts, onOpen }) {
  if (connected) {
    return (
      <div style={{ width: '100%', marginTop: 16, background: '#fff', border: '1px solid var(--neutral-4)', borderRadius: 18, overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 18px 12px' }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 17.5, color: STR_INK, whiteSpace: 'nowrap' }}>Investments elsewhere</span>
          <button onClick={onOpen} style={{ ...strIconBtn, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14.5, color: STR_PURPLE }}>Manage</button>
        </div>
        <div style={{ padding: '0 18px' }}>
          {accounts.map((a) => {
            const subs = a.accounts && a.accounts.length ? a.accounts : [{ type: a.accountType || 'Account', balance: a.balance || 0 }];
            return (
              <div key={a.name} style={{ padding: '14px 0', borderTop: '1px solid var(--neutral-4)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <Logo p={a} size={38} />
                  <span style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16.5, color: STR_INK, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.name}</span>
                    {subs.length > 1 &&
                    <span style={{ flexShrink: 0, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 11.5, color: STR_PURPLE, background: STR_PURPLE_SOFT, borderRadius: 1000, padding: '2px 8px' }}>{subs.length} accounts</span>}
                  </span>
                  <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16, color: STR_INK, flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>{gbp(a.balance || 0)}</span>
                </div>
                <div style={{ marginTop: 8, marginLeft: 50, display: 'flex', flexDirection: 'column', gap: 7 }}>
                  {subs.map((s, j) =>
                  <div key={j} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--neutral-7)', flexShrink: 0 }} />
                      <span style={{ flex: 1, minWidth: 0, fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13.5, color: 'var(--neutral-10)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.type}</span>
                      <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13.5, color: 'var(--neutral-10)', flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>{gbp(s.balance || 0)}</span>
                    </div>
                  )}
                </div>
              </div>);

          })}
        </div>
        <button onClick={onOpen} style={{ width: '100%', appearance: 'none', border: 'none', borderTop: '1px solid var(--neutral-4)', background: 'transparent', cursor: 'pointer', padding: '14px 0', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15.5, color: STR_PURPLE, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
          <PI size={18} c={STR_PURPLE} w={2.4}><path d="M12 5v14M5 12h14" /></PI><span style={{ whiteSpace: 'nowrap' }}>Add another account</span>
        </button>
      </div>);

  }
  return (
    <button onClick={onOpen} style={{ width: '100%', marginTop: 16, textAlign: 'left', appearance: 'none', cursor: 'pointer',
      background: STR_PURPLE_SOFT, border: 'none', borderRadius: 18, padding: '18px 18px', display: 'flex', alignItems: 'center', gap: 14 }}>
      <span style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 18, color: STR_INK, letterSpacing: '-0.2px' }}>Add your other investments</span>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 14.5, lineHeight: '20px', color: 'var(--neutral-10)' }}>Connect your other ISAs and accounts to track your full portfolio in Stratiphy.</span>
      </span>
      <PI size={22} c={STR_PURPLE} w={2}><path d="M9 6l6 6-6 6" /></PI>
    </button>);

}

/* ===================== BOTTOM NAV ===================== */

function BottomNav({ active = 'Portfolio' }) {
  const grey = 'var(--neutral-8)';
  const item = (icon, iconOn, label) => {
    const on = label === active;
    return (
      <button style={{ ...strTabBtn }}>
        {on ? iconOn : icon}
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: on ? 700 : 500, fontSize: 11, color: on ? STR_INK : grey }}>{label}</span>
      </button>);

  };
  const home = (c) => <PI size={23} c={c} w={1.9}><path d="M4 11l8-7 8 7" /><path d="M6 9.5V20h12V9.5" /></PI>;
  const search = (c) => <PI size={23} c={c} w={1.9}><circle cx="11" cy="11" r="7" /><path d="M20 20l-3.6-3.6" /></PI>;
  const strat = (c) => <PI size={23} c={c} w={1.9}><path d="M3 12h3.5l2.5-7 4 14 2.5-7H21" /></PI>;
  const cap = (c) => <PI size={23} c={c} w={1.9}><path d="M3 9l9-4 9 4-9 4z" /><path d="M7 11v4.5c0 1 2.2 2 5 2s5-1 5-2V11" /></PI>;
  const wallet = (c) => <PI size={23} c={c} w={1.9}><rect x="3" y="6" width="18" height="13" rx="2.5" /><path d="M16 12h2" /></PI>;
  return (
    <div style={{ flexShrink: 0, borderTop: '1px solid var(--neutral-4)', background: '#fff', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-around', padding: '10px 8px 8px' }}>
      {item(home(grey), home(STR_GOLD), 'Portfolio')}
      {item(search(grey), search(STR_GOLD), 'Discover')}
      {item(strat(grey), strat(STR_GOLD), 'Strategies')}
      {item(cap(grey), cap(STR_GOLD), 'Strativersity')}
      {item(wallet(grey), wallet(STR_GOLD), 'Account')}
    </div>);

}

/* ===================== TRANSFER STATUS ===================== */

function TransferStatusCard({ transfer, onDismiss }) {
  const DURATION = 45000; // demo: progress fills over ~45s
  const [now, setNow] = React.useState(() => Date.now());
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 400);
    return () => clearInterval(id);
  }, []);
  const elapsed = now - transfer.startedAt;
  const pct = Math.max(3, Math.min(100, Math.round(elapsed / DURATION * 100)));
  const done = pct >= 100;
  const stage = done ? 'Transfer complete' :
  pct < 33 ? `Sale instructed at ${transfer.name}` :
  pct < 78 ? 'Funds in transit' :
  'Settling into your ISA';
  const bar = done ? STR_GREEN : STR_PURPLE;

  return (
    <div style={{ marginTop: 16, background: '#fff', border: '1px solid var(--neutral-4)', borderRadius: 18, boxShadow: 'var(--elevation-default)', padding: '16px 18px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        {done ?
        <span style={{ width: 34, height: 34, borderRadius: '50%', background: STR_GREEN, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><PI size={18} c="#fff" w={3}><path d="M5 12l4.5 4.5L19 7" /></PI></span> :
        <Logo p={transfer} size={34} />}
        <span style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 2 }}>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15.5, color: STR_INK, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>ISA transfer from {transfer.name}</span>
          <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13, color: done ? '#0E8C53' : 'var(--neutral-9)' }}>{stage}</span>
        </span>
        {done ?
        <button onClick={onDismiss} aria-label="Dismiss" style={{ ...strIconBtn, flexShrink: 0 }}><PI size={20} c="var(--neutral-8)" w={2}><path d="M6 6l12 12M18 6L6 18" /></PI></button> :
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 16, color: STR_PURPLE, flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>{pct}%</span>}
      </div>
      <div style={{ marginTop: 13, height: 7, borderRadius: 100, background: 'var(--neutral-3)', overflow: 'hidden' }}>
        <div style={{ height: '100%', borderRadius: 100, background: bar, width: pct + '%', transition: 'width 500ms linear' }} />
      </div>
      <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 12.5, color: 'var(--neutral-9)' }}>{transfer.count} ISA{transfer.count !== 1 ? 's' : ''} · <span style={{ fontWeight: 600, color: STR_INK, fontVariantNumeric: 'tabular-nums' }}>{gbp(transfer.total)}</span></span>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 12.5, color: 'var(--neutral-8)' }}>{done ? 'Added to your ISA' : 'Est. ~14 mins'}</span>
      </div>
    </div>);

}

/* ===================== HOME SCREEN ===================== */

function PortfolioHome({ connected, accounts, transfer, onDismissTransfer, onOpenCollect, onOpenChat, onOpenTransfer }) {
  const [tab, setTab] = React.useState('holdings');
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff' }}>
      <div style={{ flex: 1, overflowY: 'auto', background: '#fafafa' }}>
        <div style={{ padding: '60px 18px 24px' }}>
          <PortfolioHeader />
          <BalanceBlock total={2917.27} pct="7.1" up={198.76} />
          {transfer && <TransferStatusCard transfer={transfer} onDismiss={onDismissTransfer} />}
          <PerfChart />
          <PeriodTabs />
          <HoldingsToggle tab={tab} setTab={setTab} />
          {tab === 'holdings' ? <HoldingsList /> : <ActivityList />}
          <button onClick={onOpenTransfer} style={{ width: '100%', marginTop: 16, 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}><path d="M4 7h13M13 3l4 4-4 4" /><path d="M20 17H7M11 13l-4 4 4 4" /></PI>
            Find and transfer your ISAs
          </button>
          <ConnectBanner connected={connected} accounts={accounts} onOpen={onOpenCollect} />
          <button onClick={onOpenChat} style={{ width: '100%', marginTop: 12, height: 54, borderRadius: 1000, cursor: 'pointer', background: '#fff', border: `1.5px solid ${STR_PURPLE}`, color: STR_PURPLE, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16.5 }}>
            <PI size={20} 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>
            Ask Stratiphy about your portfolio
          </button>
        </div>
      </div>
      <BottomNav active="Portfolio" />
    </div>);

}

/* ===================== APP / FRAME ===================== */

const strIconBtn = { appearance: 'none', border: 'none', background: 'transparent', padding: 2, cursor: 'pointer', display: 'flex', alignItems: 'center' };
const strTabBtn = { appearance: 'none', border: 'none', background: 'transparent', padding: '4px 4px', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 };

function PhoneFrame({ children }) {
  const btn = { position: 'absolute', background: 'linear-gradient(180deg,#3a3a3c,#1c1c1e)', boxShadow: 'inset 0 1px 1px rgba(255,255,255,0.12)' };
  return (
    <div style={{ position: 'relative', padding: 13, borderRadius: 62, background: 'linear-gradient(135deg,#46464a 0%,#1c1c1e 22%,#3a3a3d 50%,#161618 78%,#46464a 100%)', boxShadow: '0 40px 90px rgba(30,20,60,0.4), 0 0 0 1px rgba(0,0,0,0.5), inset 0 0 0 2px rgba(255,255,255,0.08)' }}>
      <div style={{ position: 'absolute', inset: 9, borderRadius: 54, boxShadow: 'inset 0 0 0 2px rgba(0,0,0,0.85)', pointerEvents: 'none', zIndex: 70 }} />
      <div style={{ ...btn, left: -2.5, top: 152, width: 3.5, height: 30, borderRadius: '3px 0 0 3px' }} />
      <div style={{ ...btn, left: -3, top: 205, width: 4, height: 56, borderRadius: '3px 0 0 3px' }} />
      <div style={{ ...btn, left: -3, top: 275, width: 4, height: 56, borderRadius: '3px 0 0 3px' }} />
      <div style={{ ...btn, right: -3, top: 232, width: 4, height: 86, borderRadius: '0 3px 3px 0' }} />
      {children}
    </div>);

}

function App() {
  const [linked, setLinked] = React.useState([]);
  const [widgetOpen, setWidgetOpen] = React.useState(false);
  const [widgetSeq, setWidgetSeq] = React.useState(0);
  const [chatOpen, setChatOpen] = React.useState(false);
  const [chatSeq, setChatSeq] = React.useState(0);
  const [transfer, setTransfer] = React.useState(null);
  const [isaFlow, setIsaFlow] = React.useState(false);
  const [isaSeq, setIsaSeq] = React.useState(0);
  const [isaTransfer, setIsaTransfer] = React.useState(() => {
    try {const v = localStorage.getItem('stratiphy_transfer');return v ? JSON.parse(v) : null;} catch (e) {return null;}
  });

  const startTransfer = (t) => {
    setIsaTransfer(t);
    try {localStorage.setItem('stratiphy_transfer', JSON.stringify(t));} catch (e) {}
  };
  const dismissTransfer = () => {
    setIsaTransfer(null);
    try {localStorage.removeItem('stratiphy_transfer');} catch (e) {}
  };

  const openIsaFlow = () => {setIsaSeq((s) => s + 1);setIsaFlow(true);};
  const openWidget = () => {setWidgetSeq((s) => s + 1);setWidgetOpen(true);};
  const openChat = () => {setChatSeq((s) => s + 1);setChatOpen(true);};
  const finishCollect = (providers) => {setLinked(providers);setWidgetOpen(false);};

  return (
    <div className="fit">
      <PhoneFrame>
        <IOSDevice dark={false} homeDark={false}>
          <div style={{ position: 'relative', height: '100%', overflow: 'hidden' }}>
            <PortfolioHome connected={linked.length > 0} accounts={linked} transfer={isaTransfer} onDismissTransfer={dismissTransfer} onOpenCollect={openWidget} onOpenChat={openChat} onOpenTransfer={openIsaFlow} />

            <div className="pane" style={{ position: 'absolute', inset: 0, zIndex: 52, transform: isaFlow ? 'translateX(0)' : 'translateX(100%)' }}>
              {isaFlow && <IsaTransferFlow key={isaSeq} onClose={() => setIsaFlow(false)} onComplete={startTransfer} />}
            </div>

            <div className="pane" style={{ position: 'absolute', inset: 0, zIndex: 45, transform: chatOpen ? 'translateX(0)' : 'translateX(100%)' }}>
              {chatOpen && <StratiphyChatScreen key={chatSeq} accounts={linked} onBack={() => setChatOpen(false)} onConnect={() => {setChatOpen(false);openWidget();}} onTransfer={(data) => setTransfer(data)} />}
            </div>

            <div className="pane" style={{ position: 'absolute', inset: 0, zIndex: 48, transform: transfer ? 'translateX(0)' : 'translateX(100%)' }}>
              {transfer && <TransferScreen data={transfer} onClose={() => setTransfer(null)} />}
            </div>

            <div onClick={() => setWidgetOpen(false)} style={{ position: 'absolute', inset: 0, zIndex: 49, background: 'rgba(30,20,60,0.4)', opacity: widgetOpen ? 1 : 0, pointerEvents: widgetOpen ? 'auto' : 'none', transition: 'opacity 380ms cubic-bezier(0.2,0.7,0.2,1)' }} />
            <div className="pane" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, top: '25%', zIndex: 50, borderRadius: '26px 26px 0 0', overflow: 'hidden', boxShadow: '0 -12px 44px rgba(0,0,0,0.28)', transform: widgetOpen ? 'translateY(0)' : 'translateY(101%)' }}>
              {widgetOpen && <CollectWidget key={widgetSeq} initial={linked} onDone={finishCollect} onCancel={() => setWidgetOpen(false)} accent={STR_PURPLE} />}
            </div>
          </div>
        </IOSDevice>
      </PhoneFrame>
    </div>);

}

Object.assign(window, { STR_PURPLE, STR_PURPLE_DEEP, STR_PURPLE_SOFT, STR_GOLD, STR_GOLD_SOFT, STR_GREEN, STR_GREEN_SOFT, STR_INK, PI, StratDonut, StratAvatar, gbp, strIconBtn });

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
