/* USE CASE — Insurely "collect" widget. Bottom-sheet account picker → connect →
   loading flow for connecting investments held elsewhere. Depends only on
   shared/core.jsx (PROVIDERS, Logo, Stroke, iconBtn). Exports { CollectWidget }. */

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 });
