/* Shared Insurely collect-data widget for the Chip Home demo.
   Exports to window: CollectWidget, Logo, PROVIDERS, Stroke, iconBtn */

const PROVIDERS = [
{ name: 'Barclays', accountType: 'Stocks & Shares ISA', accounts: [{ type: 'Stocks & Shares ISA', balance: 30200.00 }, { type: 'Cash ISA', balance: 24000.00 }], logo: 'images/logos/barclays.png', balance: 54200.00, feeRate: 0.0105, ytd: 2.0, dip: 1.3, isaRate: 4.30, isaTerm: '1-year fixed', monthly: 220 },
{ name: 'Chase', accountType: 'Cash ISA', accounts: [{ type: 'Cash ISA', balance: 18950.40 }], logo: 'images/logos/chase.png', balance: 18950.40, feeRate: 0.0060, ytd: 2.4, dip: 1.6, isaRate: 4.35, isaTerm: 'Easy access', monthly: 180 },
{ name: 'Freetrade', accountType: 'Stocks & Shares ISA', accounts: [{ type: 'Stocks & Shares ISA', balance: 84560.18 }, { type: 'General Investment Account', balance: 40000.00 }], logo: 'images/logos/freetrade.png', balance: 124560.18, feeRate: 0.0042, ytd: 3.8, dip: 2.1, isaRate: 4.55, isaTerm: '1-year fixed', monthly: 450 },
{ name: 'Halifax', accountType: 'Fixed Rate ISA', accounts: [{ type: 'Fixed Rate ISA', balance: 88240.55 }], logo: 'images/logos/halifax.png', balance: 88240.55, feeRate: 0.0115, ytd: 1.9, dip: 1.4, isaRate: 4.25, isaTerm: '1-year fixed', monthly: 200 },
{ name: 'Hargreaves Lansdown', accountType: 'Self-Invested Personal Pension', accounts: [{ type: 'Self-Invested Personal Pension', balance: 140900.00 }, { type: 'Stocks & Shares ISA', balance: 75000.00 }], logo: 'images/logos/hl.png', balance: 215900.00, feeRate: 0.0095, ytd: 2.6, dip: 1.8, isaRate: 4.40, isaTerm: '18-month fixed', monthly: 600 },
{ name: 'HSBC UK', accountType: 'Cash ISA', accounts: [{ type: 'Cash ISA', balance: 41400.00 }, { type: 'Lifetime ISA', balance: 26000.00 }], logo: 'images/logos/hsbc.png', balance: 67400.00, feeRate: 0.0110, ytd: 1.8, dip: 1.2, isaRate: 4.20, isaTerm: '1-year fixed', monthly: 240 },
{ name: 'Interactive Investor', accountType: 'General Investment Account', accounts: [{ type: 'General Investment Account', balance: 92300.00 }, { type: 'Stocks & Shares ISA', balance: 50000.00 }], logo: 'images/logos/ii.png', balance: 142300.00, feeRate: 0.0050, ytd: 3.1, dip: 2.0, isaRate: 4.60, isaTerm: '1-year fixed', monthly: 520 },
{ name: 'Lloyds Bank', accountType: 'Fixed Rate ISA', accounts: [{ type: 'Fixed Rate ISA', balance: 39800.00 }], logo: 'images/logos/lloyds.png', balance: 39800.00, feeRate: 0.0120, ytd: 1.6, dip: 1.1, isaRate: 4.15, isaTerm: 'Easy access', monthly: 160 },
{ name: 'Moneybox', accountType: 'Lifetime ISA', accounts: [{ type: 'Lifetime ISA', balance: 20180.40 }, { type: 'Cash ISA', balance: 12000.00 }], logo: 'images/logos/moneybox.png', balance: 32180.40, feeRate: 0.0070, ytd: 2.2, dip: 1.1, isaRate: 4.65, isaTerm: '1-year fixed', monthly: 250 },
{ name: 'Monzo', accountType: 'Cash ISA', accounts: [{ type: 'Cash ISA', balance: 21450.00 }], logo: 'images/logos/monzo.png', balance: 21450.00, feeRate: 0.0055, ytd: 2.5, dip: 1.7, isaRate: 4.45, isaTerm: 'Easy access', monthly: 190 },
{ name: 'Natwest', accountType: 'Fixed Rate ISA', accounts: [{ type: 'Fixed Rate ISA', balance: 31015.22 }, { type: 'Cash ISA', balance: 15000.00 }], logo: 'images/logos/natwest.png', balance: 46015.22, feeRate: 0.0125, ytd: 1.5, dip: 1.0, isaRate: 4.05, isaTerm: 'Easy access', monthly: 150 },
{ name: 'Revolut', accountType: 'General Investment Account', accounts: [{ type: 'General Investment Account', balance: 12450.75 }], logo: 'images/logos/revolut.png', balance: 12450.75, feeRate: 0.0050, ytd: 4.1, dip: 2.6, isaRate: 4.50, isaTerm: '1-year fixed', monthly: 300 },
{ name: 'Santander UK', accountType: 'UK Occupational Pension', accounts: [{ type: 'UK Occupational Pension', balance: 42900.00 }, { type: 'Cash ISA', balance: 16000.00 }], logo: 'images/logos/santander.png', balance: 58900.00, feeRate: 0.0118, ytd: 1.7, dip: 1.2, isaRate: 4.10, isaTerm: '1-year fixed', monthly: 210 },
{ name: 'Trading 212', accountType: 'Stocks & Shares ISA', accounts: [{ type: 'Stocks & Shares ISA', balance: 108549.64 }, { type: 'General Investment Account', balance: 55000.00 }], logo: 'images/logos/trading212.png', balance: 163549.64, feeRate: 0.0040, ytd: 3.5, dip: 2.3, isaRate: 4.90, isaTerm: '2-year fixed', monthly: 500 }];


function Stroke({ d, size = 24, c = 'rgba(40,46,32,0.72)', w = 1.8, children }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
    stroke={c} strokeWidth={w} strokeLinecap="round" strokeLinejoin="round">
      {d && <path d={d} />}{children}
    </svg>);

}

const iconBtn = { appearance: 'none', border: 'none', background: 'transparent', padding: 2, cursor: 'pointer', display: 'flex' };

function Logo({ p, size = 42 }) {
  const [failed, setFailed] = React.useState(false);
  const resolve = (typeof window !== 'undefined' && window.assetUrl) ? window.assetUrl : (x) => x;
  if (p.logo && !failed) {
    return (
      <img src={resolve(p.logo)} alt={p.name} onError={() => setFailed(true)} style={{
        width: size, height: size, borderRadius: '50%', objectFit: 'cover',
        flexShrink: 0, display: 'block', background: '#fff'
      }} />);

  }
  const initials = p.mono || (p.name ? p.name.trim()[0].toUpperCase() : '?');
  return (
    <span style={{
      width: size, height: size, borderRadius: '50%', background: p.color || 'var(--midnight)', color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      fontFamily: 'var(--font-body)', fontWeight: 700,
      fontSize: initials.length > 1 ? 13 : 17, letterSpacing: initials.length > 1 ? '-0.4px' : 0
    }}>{initials}</span>);

}

function InsurelyFooter() {
  return (
    <div style={{ flexShrink: 0, padding: '14px 0 30px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, background: '#fff' }}>
      <span style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13, color: 'var(--neutral-9)' }}>Connected by</span>
      <span style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 19, color: 'var(--midnight)', letterSpacing: '-0.02em' }}>insurely</span>
    </div>);

}

function PickAccounts({ connected, onSelect, onClose, onFinish, accent = 'var(--midnight)' }) {
  const [q, setQ] = React.useState('');
  const list = PROVIDERS.filter((p) => p.name.toLowerCase().includes(q.toLowerCase()));
  const names = connected.map((c) => c.name);
  return (
    <div style={{ padding: '18px 22px 8px' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
        <h2 style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 26, lineHeight: '32px', letterSpacing: '-0.5px', color: 'var(--midnight)' }}>
          {names.length > 0 ? 'Do you want to add another account?' : 'Which account would you like to add?'}
        </h2>
        <button onClick={() => names.length ? onFinish() : onClose()} aria-label="Close" style={{ ...iconBtn, marginTop: 2, flexShrink: 0 }}>
          <Stroke size={24} w={2}><path d="M6 6l12 12M18 6L6 18" /></Stroke>
        </button>
      </div>
      <p style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 14.5, color: 'var(--neutral-9)', marginTop: 8 }}>
        Connect each account you'd like to add. Authenticate one at a time.
      </p>

      <div style={{ marginTop: 16, height: 48, borderRadius: 12, border: '1px solid var(--neutral-5)', display: 'flex', alignItems: 'center', gap: 10, padding: '0 16px' }}>
        <Stroke size={19} w={2} c="var(--neutral-9)"><circle cx="11" cy="11" r="7" /><path d="M20 20l-3.6-3.6" /></Stroke>
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search for your company"
        style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 15.5, color: 'var(--midnight)' }} />
      </div>

      <div style={{ marginTop: 16, border: '1px solid var(--neutral-4)', borderRadius: 12, overflow: 'hidden' }}>
        {list.map((p, i) => {
          const isConnected = names.includes(p.name);
          const clickable = !isConnected;
          return (
            <button key={p.name} disabled={!clickable} onClick={() => clickable && onSelect(p)}
            style={{
              width: '100%', appearance: 'none', background: isConnected ? 'var(--mint-3)' : 'transparent', textAlign: 'left',
              border: 'none', borderBottom: i < list.length - 1 ? '1px solid var(--neutral-4)' : 'none',
              padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14,
              cursor: clickable ? 'pointer' : 'default'
            }}>
              <Logo p={p} />
              <span style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 4 }}>
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 16.5, color: 'var(--midnight)' }}>{p.name}</span>
                {isConnected &&
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, color: 'var(--green)' }}>Connected</span>}
              </span>
              {isConnected ?
              <span style={{ width: 24, height: 24, borderRadius: '50%', background: 'var(--green)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Stroke size={15} w={2.6} c="#fff"><path d="M5 12l4.5 4.5L19 7" /></Stroke></span> :
              <Stroke size={20} w={2} c="var(--green)"><path d="M9 6l6 6-6 6" /></Stroke>}
            </button>);

        })}
        {list.length === 0 &&
        <div style={{ padding: '24px 16px', fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 15, color: 'var(--neutral-9)' }}>No companies found.</div>
        }
      </div>

      {names.length > 0 &&
      <button onClick={onFinish} style={{ width: '100%', marginTop: 18, height: 56, borderRadius: 1000, border: 'none', background: accent, color: '#fff', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 17, cursor: 'pointer' }}>
          Done · {names.length} connected
        </button>
      }
    </div>);

}

function ConnectProvider({ provider, onBack, onConnect, accent = 'var(--midnight)' }) {
  const [show, setShow] = React.useState(false);
  const fieldStyle = { width: '100%', boxSizing: 'border-box', height: 50, borderRadius: 8, border: '1px solid var(--neutral-5)', padding: '0 16px', fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 16, color: 'var(--midnight)', outline: 'none', background: '#fff' };
  return (
    <div style={{ padding: '14px 22px 8px' }}>
      <button onClick={onBack} style={{ ...iconBtn, alignItems: 'center', gap: 10 }}>
        <Stroke size={22} w={2.2} c="var(--green)"><path d="M11 5l-7 7 7 7" /><path d="M4 12h15" /></Stroke>
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 17, color: 'var(--green)' }}>Back</span>
      </button>
      <h2 style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 26, letterSpacing: '-0.5px', color: 'var(--midnight)', margin: '14px 0 0' }}>Connect to {provider.name}</h2>
      <div style={{ height: 1, background: 'var(--neutral-4)', margin: '18px 0' }} />

      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
        <Logo p={provider} size={44} />
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 20, color: 'var(--midnight)' }}>{provider.name}</span>
      </div>

      <div style={{ border: '1px solid var(--neutral-4)', borderRadius: 16, padding: 20 }}>
        <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 19, color: 'var(--midnight)' }}>Fetch automatically</div>
        <p style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 15, lineHeight: '22px', color: 'var(--neutral-10)', margin: '8px 0 22px' }}>
          Log in to {provider.name}, our service will retrieve your accounts automatically and create a personalised offer.
        </p>

        <label style={{ display: 'block', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15, color: 'var(--midnight)', marginBottom: 8 }}>Username</label>
        <input placeholder="Username" style={fieldStyle} />

        <label style={{ display: 'block', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15, color: 'var(--midnight)', margin: '18px 0 8px' }}>Password</label>
        <div style={{ position: 'relative' }}>
          <input type={show ? 'text' : 'password'} placeholder="Password" style={{ ...fieldStyle, paddingRight: 46 }} />
          <button onClick={() => setShow((s) => !s)} aria-label="Show password" style={{ position: 'absolute', right: 12, top: 0, height: 50, ...iconBtn, alignItems: 'center' }}>
            <Stroke size={22} w={1.8} c="var(--green)"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z" /><circle cx="12" cy="12" r="3" /></Stroke>
          </button>
        </div>

        <button onClick={onConnect} style={{ width: '100%', marginTop: 24, height: 56, borderRadius: 1000, border: 'none', background: accent, color: '#fff', fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 17, cursor: 'pointer' }}>
          Connect to {provider.name}
        </button>

        <p style={{ fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 13, lineHeight: '19px', color: 'var(--neutral-10)', marginTop: 16 }}>
          By clicking "Connect to {provider.name}" you accept the <a style={{ color: 'var(--green)', textDecoration: 'underline' }}>terms &amp; conditions</a>. Please read the <a style={{ color: 'var(--green)', textDecoration: 'underline' }}>privacy policy</a> and <a style={{ color: 'var(--green)', textDecoration: 'underline' }}>personal data</a> regarding data processing.
        </p>
      </div>
    </div>);

}

function LoadingStep({ provider, onDone, onCancel }) {
  const steps = [
  { label: `Connecting to ${provider.name}`, kind: 'provider', dur: 1400 },
  { label: 'Authenticating', kind: 'shield', dur: 1200 },
  { label: 'Collecting your information', kind: 'doc', dur: 1600 }];

  const [active, setActive] = React.useState(0);
  const [fill, setFill] = React.useState([0, 0, 0]);

  React.useEffect(() => {
    let cancelled = false;
    const wait = (ms) => new Promise((r) => setTimeout(r, ms));
    (async () => {
      for (let i = 0; i < steps.length; i++) {
        if (cancelled) return;
        setActive(i);
        await wait(90);
        if (cancelled) return;
        setFill((f) => {const n = [...f];n[i] = 100;return n;});
        await wait(steps[i].dur);
      }
      await wait(480);
      if (!cancelled) onDone();
    })();
    return () => {cancelled = true;};
  }, []);

  const tile = (kind) => {
    const ic = { width: 40, height: 40, borderRadius: 10, background: 'var(--neutral-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 };
    if (kind === 'provider') return <span style={{ ...ic, background: '#fff', border: '1px solid var(--neutral-4)' }}><Logo p={provider} size={26} /></span>;
    if (kind === 'shield') return <span style={ic}><Stroke size={22} c="var(--midnight)"><path d="M12 3l7 3v5c0 4.4-3 7.4-7 8.8-4-1.4-7-4.4-7-8.8V6z" /><circle cx="12" cy="11" r="1.4" /><path d="M12 12.4V15" /></Stroke></span>;
    return <span style={ic}><Stroke size={22} c="var(--midnight)"><path d="M13 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6" /><path d="M13 3l5 5h-5z" /><circle cx="16.5" cy="15.5" r="2.6" /><path d="M18.6 17.6L21 20" /></Stroke></span>;
  };

  return (
    <div style={{ padding: '18px 22px 8px' }}>
      <h2 style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 27, letterSpacing: '-0.5px', color: 'var(--midnight)' }}>Loading</h2>
      <div style={{ height: 1, background: 'var(--neutral-4)', margin: '18px 0 20px' }} />

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {steps.map((s, i) =>
        <div key={i} style={{ border: '1px solid var(--neutral-4)', borderRadius: 12, padding: '16px 16px', opacity: i <= active ? 1 : 0.55, transition: 'opacity 300ms ease' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              {tile(s.kind)}
              <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 17, color: 'var(--midnight)' }}>{s.label}</span>
            </div>
            {i <= active &&
          <div style={{ marginTop: 14, height: 8, borderRadius: 100, background: 'var(--neutral-3)', overflow: 'hidden' }}>
                <div style={{ height: '100%', borderRadius: 100, background: 'var(--green)', width: fill[i] + '%', transition: `width ${s.dur}ms linear` }} />
              </div>
          }
          </div>
        )}
      </div>

      <button onClick={onCancel} style={{ display: 'block', margin: '24px auto 0', ...iconBtn, fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 17, color: 'var(--green)' }}>Cancel</button>
    </div>);

}

function CollectWidget({ initial, onDone, onCancel, accent = 'var(--midnight)' }) {
  const [step, setStep] = React.useState('pick');
  const [provider, setProvider] = React.useState(null);
  const [connected, setConnected] = React.useState(initial || []);

  const addConnected = () => {
    setConnected((c) => c.find((x) => x.name === provider.name) ? c : [...c, provider]);
    setStep('pick');
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#fff' }}>
      <div style={{ flexShrink: 0, paddingTop: 10, display: 'flex', justifyContent: 'center' }}>
        <div style={{ width: 40, height: 5, borderRadius: 100, background: 'var(--neutral-5)' }} />
      </div>
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {step === 'pick' && <PickAccounts connected={connected} accent={accent} onSelect={(p) => {setProvider(p);setStep('connect');}} onClose={onCancel} onFinish={() => onDone(connected)} />}
        {step === 'connect' && <ConnectProvider provider={provider} accent={accent} onBack={() => setStep('pick')} onConnect={() => setStep('loading')} />}
        {step === 'loading' && <LoadingStep provider={provider} onDone={addConnected} onCancel={() => setStep('pick')} />}
      </div>
    </div>);

}

Object.assign(window, { CollectWidget, Logo, PROVIDERS, Stroke, iconBtn });
