// Link new account — bottom sheet flow

const PLAID_COUNTRIES = [
  // UAE pinned at top
  { id: 'AE', name: 'United Arab Emirates', flag: '🇦🇪', pinned: true },
  // Plaid-supported markets
  { id: 'US', name: 'United States',  flag: '🇺🇸' },
  { id: 'CA', name: 'Canada',         flag: '🇨🇦' },
  { id: 'GB', name: 'United Kingdom', flag: '🇬🇧' },
  { id: 'IE', name: 'Ireland',        flag: '🇮🇪' },
  { id: 'FR', name: 'France',         flag: '🇫🇷' },
  { id: 'ES', name: 'Spain',          flag: '🇪🇸' },
  { id: 'DE', name: 'Germany',        flag: '🇩🇪' },
  { id: 'IT', name: 'Italy',          flag: '🇮🇹' },
  { id: 'NL', name: 'Netherlands',    flag: '🇳🇱' },
  { id: 'BE', name: 'Belgium',        flag: '🇧🇪' },
  { id: 'PT', name: 'Portugal',       flag: '🇵🇹' },
  { id: 'PL', name: 'Poland',         flag: '🇵🇱' },
  { id: 'DK', name: 'Denmark',        flag: '🇩🇰' },
  { id: 'NO', name: 'Norway',         flag: '🇳🇴' },
  { id: 'SE', name: 'Sweden',         flag: '🇸🇪' },
  { id: 'EE', name: 'Estonia',        flag: '🇪🇪' },
  { id: 'LV', name: 'Latvia',         flag: '🇱🇻' },
  { id: 'LT', name: 'Lithuania',      flag: '🇱🇹' },
];

const BANK_PROVIDERS_BY_COUNTRY = {
  AE: ['Emirates NBD','ADCB','FAB','Mashreq','HSBC','Wio','Liv'],
  US: ['Chase','Bank of America','Wells Fargo','Citi','Capital One','Ally'],
  CA: ['RBC','TD Bank','Scotiabank','BMO','CIBC','National Bank'],
  GB: ['Barclays','HSBC','Lloyds','NatWest','Monzo','Starling','Revolut','Wise'],
  IE: ['AIB','Bank of Ireland','Permanent TSB','Revolut','N26'],
  FR: ['BNP Paribas','Société Générale','Crédit Agricole','La Banque Postale'],
  ES: ['Santander','BBVA','CaixaBank','Bankinter'],
  DE: ['Deutsche Bank','Commerzbank','N26','DKB','ING'],
  IT: ['UniCredit','Intesa Sanpaolo','BPER','Fineco'],
  NL: ['ING','Rabobank','ABN AMRO','Bunq'],
  BE: ['BNP Paribas Fortis','KBC','Belfius','ING'],
  PT: ['Millennium BCP','Santander Totta','Novo Banco','Caixa Geral'],
  PL: ['PKO BP','Pekao','mBank','ING','Santander'],
  DK: ['Danske Bank','Nordea','Jyske Bank','Nykredit'],
  NO: ['DNB','Nordea','SpareBank 1','Sbanken'],
  SE: ['Swedbank','SEB','Handelsbanken','Nordea'],
  EE: ['Swedbank','SEB','LHV','Coop Pank'],
  LV: ['Swedbank','SEB','Citadele','Luminor'],
  LT: ['Swedbank','SEB','Luminor','Šiaulių bankas'],
};

const BROKERAGES_LIST = ['Saxo','Interactive Brokers','eToro','Charles Schwab','Sarwa','FAB Securities','Robinhood','Fidelity'];
const CRYPTO_EXCHANGES = ['Binance','Coinbase','Kraken','Bybit','OKX','BitOasis','CoinMENA'];

function AddAssetModal({ theme, accent, open, onClose }) {
  // step:
  //   pick                 → kind picker (bank / brokerage / crypto)
  //   bank-country         → choose country
  //   bank-provider        → choose bank within country
  //   broker-provider      → choose brokerage
  //   crypto-mode          → centralized vs decentralized
  //   crypto-exchange      → centralized exchange picker
  //   crypto-wallet-addr   → decentralized: paste address
  const [step, setStep] = React.useState('pick');
  const [kind, setKind] = React.useState(null);
  const [country, setCountry] = React.useState(null);
  const [walletAddr, setWalletAddr] = React.useState('');

  React.useEffect(() => {
    if (!open) {
      setTimeout(() => {
        setStep('pick'); setKind(null); setCountry(null); setWalletAddr('');
      }, 300);
    }
  }, [open]);

  const kinds = [
    { key: 'bank',   label: 'Bank account',  icon: 'building' },
    { key: 'broker', label: 'Brokerage',     icon: 'chart' },
    { key: 'crypto', label: 'Crypto wallet', icon: 'coin' },
  ];

  const pickKind = (k) => {
    setKind(k);
    if (k.key === 'bank')   setStep('bank-country');
    if (k.key === 'broker') setStep('broker-provider');
    if (k.key === 'crypto') setStep('crypto-mode');
  };

  if (!open) return null;

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      display: 'flex', alignItems: 'flex-end',
      background: 'rgba(0,0,0,0.55)',
      animation: 'himma-fade 200ms',
    }} onClick={onClose}>
      <style>{`
        @keyframes himma-fade { from { opacity: 0 } to { opacity: 1 } }
        @keyframes himma-slide { from { transform: translateY(20px); opacity: 0 } to { transform: translateY(0); opacity: 1 } }
      `}</style>

      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxHeight: '88%',
        background: theme.surface,
        borderRadius: '24px 24px 0 0',
        borderTop: `0.5px solid ${theme.line2}`,
        padding: '10px 20px 34px',
        animation: 'himma-slide 260ms cubic-bezier(.2,.8,.25,1)',
        overflow: 'auto',
      }}>
        <div style={{ display:'flex', justifyContent:'center', paddingBottom: 14 }}>
          <div style={{ width: 40, height: 4, borderRadius: 2, background: theme.line2 }}/>
        </div>

        {step === 'pick' && (
          <>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, letterSpacing: -0.4 }}>Link new account</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>
              Securely connect a new account so Himma can sync balances and transactions in real time.
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 18 }}>
              {kinds.map(k => {
                const Icon = Ico[k.icon];
                return (
                  <button key={k.key} onClick={() => pickKind(k)}
                    style={{
                      background: theme.surface2,
                      border: `0.5px solid ${theme.line}`,
                      borderRadius: 14, padding: '14px 14px',
                      display: 'flex', alignItems: 'center', gap: 12,
                      cursor: 'pointer', textAlign: 'left', color: theme.text,
                    }}>
                    <div style={{ width: 36, height: 36, borderRadius: 10, background: theme.surface3, color: accent, display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0 }}>
                      <Icon size={17}/>
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 500 }}>{k.label}</div>
                    </div>
                    <Ico.chevR size={14} stroke={theme.textMute}/>
                  </button>
                );
              })}
            </div>
          </>
        )}

        {step === 'bank-country' && (
          <>
            <BackBtn theme={theme} onClick={() => setStep('pick')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>Choose country</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>
              We’ll show banks supported in that country.
            </div>

            <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
              {PLAID_COUNTRIES.map((c, i, arr) => {
                const showSep = c.pinned && i + 1 < arr.length && !arr[i + 1].pinned;
                return (
                  <React.Fragment key={c.id}>
                    <button onClick={() => { setCountry(c); setStep('bank-provider'); }} style={{
                      background: theme.surface2, border: `0.5px solid ${theme.line}`,
                      borderRadius: 12, padding: '12px 14px',
                      display: 'flex', alignItems: 'center', gap: 12,
                      cursor: 'pointer', textAlign: 'left', color: theme.text,
                    }}>
                      <span style={{ fontSize: 20, lineHeight: 1 }}>{c.flag}</span>
                      <span style={{ flex: 1, fontSize: 13.5, fontWeight: 500 }}>{c.name}</span>
                      <Ico.chevR size={13} stroke={theme.textMute}/>
                    </button>
                    {showSep && (
                      <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1, textTransform: 'uppercase', color: theme.textMute, padding: '8px 4px 2px' }}>
                        Other supported countries
                      </div>
                    )}
                  </React.Fragment>
                );
              })}
            </div>
          </>
        )}

        {step === 'bank-provider' && country && (
          <>
            <BackBtn theme={theme} onClick={() => setStep('bank-country')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>
              Banks in {country.name}
            </div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>Select your bank to connect securely.</div>

            <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {(BANK_PROVIDERS_BY_COUNTRY[country.id] || []).map(p => (
                <ProviderTile key={p} theme={theme} name={p} onClick={onClose}/>
              ))}
            </div>

            <SecureBadge theme={theme} accent={accent}/>
          </>
        )}

        {step === 'broker-provider' && (
          <>
            <BackBtn theme={theme} onClick={() => setStep('pick')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>Choose your brokerage</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>Select your broker to connect securely.</div>

            <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {BROKERAGES_LIST.map(p => (
                <ProviderTile key={p} theme={theme} name={p} onClick={onClose}/>
              ))}
            </div>

            <SecureBadge theme={theme} accent={accent}/>
          </>
        )}

        {step === 'crypto-mode' && (
          <>
            <BackBtn theme={theme} onClick={() => setStep('pick')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>Link your crypto</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>Connect a centralized exchange or paste a public wallet address.</div>

            <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 8 }}>
              <ModeCard theme={theme} accent={accent}
                icon="building" title="Centralized exchange"
                onClick={() => setStep('crypto-exchange')}/>
              <ModeCard theme={theme} accent={accent}
                icon="wallet" title="Decentralized wallet"
                onClick={() => setStep('crypto-wallet-addr')}/>
            </div>
          </>
        )}

        {step === 'crypto-exchange' && (
          <>
            <BackBtn theme={theme} onClick={() => setStep('crypto-mode')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>Choose your exchange</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>Select your centralized exchange to connect.</div>

            <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {CRYPTO_EXCHANGES.map(p => (
                <ProviderTile key={p} theme={theme} name={p} onClick={onClose}/>
              ))}
            </div>

            <SecureBadge theme={theme} accent={accent}/>
          </>
        )}

        {step === 'crypto-wallet-addr' && (
          <>
            <BackBtn theme={theme} onClick={() => setStep('crypto-mode')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>Add wallet address</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>
              Paste your public wallet address. We track holdings via Etherscan — read-only.
            </div>

            <div style={{ marginTop: 18 }}>
              <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 6 }}>Public address</div>
              <input
                value={walletAddr}
                onChange={e => setWalletAddr(e.target.value)}
                placeholder="0x..."
                style={{
                  width: '100%', background: theme.surface2,
                  border: `0.5px solid ${theme.line2}`, borderRadius: 12,
                  padding: '12px 14px', color: theme.text,
                  fontSize: 13.5, fontFamily: FONTS.mono, letterSpacing: 0.4,
                  outline: 'none',
                }}
              />
              <a href="https://etherscan.io/" target="_blank" rel="noopener noreferrer" style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                marginTop: 10, color: accent, textDecoration: 'none',
                fontFamily: FONTS.ui, fontSize: 12, fontWeight: 600,
              }}>
                Look up on Etherscan <Ico.arrowUR size={12} stroke={accent}/>
              </a>
            </div>

            <button
              onClick={onClose}
              disabled={walletAddr.trim().length < 8}
              style={{
                marginTop: 22, width: '100%',
                background: walletAddr.trim().length < 8 ? theme.surface3 : accent,
                color: walletAddr.trim().length < 8 ? theme.textMute : theme.bg,
                border: 'none', padding: '14px', borderRadius: 14,
                fontFamily: FONTS.ui, fontSize: 14, fontWeight: 600,
                cursor: walletAddr.trim().length < 8 ? 'not-allowed' : 'pointer',
              }}>Track wallet</button>

            <SecureBadge theme={theme} accent={accent}/>
          </>
        )}
      </div>
    </div>
  );
}

function ProviderTile({ theme, name, onClick }) {
  return (
    <button onClick={onClick} style={{
      background: theme.surface2, border: `0.5px solid ${theme.line}`,
      borderRadius: 12, padding: '12px 10px',
      display: 'flex', alignItems: 'center', gap: 10,
      fontFamily: FONTS.ui, fontSize: 12.5, color: theme.text,
      cursor: 'pointer', textAlign: 'left',
    }}>
      <BrandLogo name={name} size={28}/>
      <span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}</span>
    </button>
  );
}

function ModeCard({ theme, accent, icon, title, onClick }) {
  const Icon = Ico[icon];
  return (
    <button onClick={onClick} style={{
      background: theme.surface2,
      border: `0.5px solid ${theme.line}`,
      borderRadius: 14, padding: '14px',
      display: 'flex', alignItems: 'center', gap: 12,
      cursor: 'pointer', textAlign: 'left', color: theme.text,
    }}>
      <div style={{ width: 34, height: 34, borderRadius: 10, background: theme.surface3, color: accent, display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0 }}>
        <Icon size={16}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13.5, fontWeight: 500 }}>{title}</div>
      </div>
      <Ico.chevR size={13} stroke={theme.textDim}/>
    </button>
  );
}

function SecureBadge({ theme, accent }) {
  return (
    <div style={{ marginTop: 18, padding: '10px 12px', background: theme.surface2, borderRadius: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
      <Ico.shield size={14} stroke={accent}/>
      <span style={{ fontFamily: FONTS.mono, fontSize: 10.5, color: theme.textDim, letterSpacing: 0.2 }}>Read-only. Himma never moves money.</span>
    </div>
  );
}

function BackBtn({ onClick, theme }) {
  return (
    <button onClick={onClick} style={{ background:'transparent', border:'none', color: theme.textDim, cursor: 'pointer', display:'flex', alignItems:'center', gap: 4, padding: 0, fontSize: 12, fontFamily: FONTS.ui }}>
      <Ico.chevL size={12}/> Back
    </button>
  );
}

Object.assign(window, { AddAssetModal });
