// Linked accounts — list of connected institutions with unlink + confirmation

const BRAND_LOGOS = {
  "Emirates NBD": { initials: "NBD", bg: "#A21E22" },
  ADCB: { initials: "ADCB", bg: "#9C1D2C" },
  FAB: { initials: "FAB", bg: "#0E2A47" },
  Mashreq: { initials: "M", bg: "#E8541A" },
  HSBC: { initials: "HSBC", bg: "#DB0011" },
  Wise: { initials: "W", bg: "#9FE870" },
  Revolut: { initials: "R", bg: "#0666EB" },
  "Saxo Bank": { initials: "Saxo", bg: "#012169" },
  Saxo: { initials: "Saxo", bg: "#012169" },
  "Interactive Brokers": { initials: "IBKR", bg: "#D81222" },
  eToro: { initials: "e", bg: "#13C636" },
  "Charles Schwab": { initials: "CS", bg: "#00A0DF" },
  Sarwa: { initials: "S", bg: "#1B4DB1" },
  "FAB Securities": { initials: "FAB", bg: "#0E2A47" },
  Binance: { initials: "B", bg: "#F0B90B" },
  Coinbase: { initials: "C", bg: "#0052FF" },
  Kraken: { initials: "K", bg: "#5841D8" },
  Ledger: { initials: "L", bg: "#000000" },
  Bitcoin: { initials: "₿", bg: "#F7931A" },
  Ethereum: { initials: "Ξ", bg: "#627EEA" },
  Solana: { initials: "S", bg: "#7B53D6" },
  "USD Coin": { initials: "$", bg: "#2775CA" },
  BTC: { initials: "₿", bg: "#F7931A" },
  ETH: { initials: "Ξ", bg: "#627EEA" },
  SOL: { initials: "S", bg: "#7B53D6" },
  USDC: { initials: "$", bg: "#2775CA" },
  Bybit: { initials: "B", bg: "#F7A600" },
  OKX: { initials: "OKX", bg: "#000000" },
  BitOasis: { initials: "BO", bg: "#1A1A1A" },
  Robinhood: { initials: "R", bg: "#00C805" },
  Fidelity: { initials: "F", bg: "#368727" },
  Wio: { initials: "wio", bg: "#0F1B2D" },
  Liv: { initials: "liv", bg: "#FF5C8A" },
};

function getBrand(name) {
  if (BRAND_LOGOS[name]) return BRAND_LOGOS[name];
  // Fallback initial
  const initials = name
    .split(" ")
    .map((w) => w[0])
    .join("")
    .slice(0, 3)
    .toUpperCase();
  return { initials, bg: "#6B7280" };
}

function BrandLogo({ name, size = 34 }) {
  const b = getBrand(name);
  const fontSize =
    b.initials.length >= 4
      ? size * 0.32
      : b.initials.length === 3
        ? size * 0.36
        : b.initials.length === 2
          ? size * 0.4
          : size * 0.5;
  return (
    <div
      style={{
        width: size,
        height: size,
        borderRadius: 10,
        background: b.bg,
        color: "#fff",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontFamily: FONTS.ui,
        fontSize,
        fontWeight: 700,
        letterSpacing: 0.2,
        flexShrink: 0,
      }}
    >
      {b.initials}
    </div>
  );
}

function SettingsLinkedAccountsScreen({ theme, accent, onBack, onAddAsset }) {
  // All listed rows are linked; unlinking removes them locally.
  const initial = React.useMemo(() => {
    const items = [];
    BANK_ACCOUNTS.forEach((a) =>
      items.push({
        id: a.id,
        kind: "Banking",
        name: a.bank,
        secondary: `${a.type} · ${a.last}`,
      }),
    );
    BROKERAGES.forEach((b) =>
      items.push({
        id: b.id,
        kind: "Brokerages",
        name: b.name,
        secondary: `${b.holdings.length} holdings`,
      }),
    );
    (typeof CRYPTO_ACCOUNTS !== "undefined" ? CRYPTO_ACCOUNTS : []).forEach(
      (c) =>
        items.push({
          id: c.id,
          kind: "Crypto",
          name: c.name,
          secondary: `${c.kind} · ${c.holdings.length} holdings`,
        }),
    );
    return items;
  }, []);
  const [items, setItems] = React.useState(initial);
  const [pendingUnlink, setPendingUnlink] = React.useState(null);

  const groups = ["Banking", "Brokerages", "Crypto"];

  return (
    <Screen theme={theme} padTop={0} padBottom={120}>
      <NavBar theme={theme} title="Linked accounts" onBack={onBack} />

      {groups.map((g) => {
        const rows = items.filter((i) => i.kind === g);
        if (rows.length === 0) return null;
        return (
          <Section key={g} theme={theme} label={g}>
            {rows.map((row, i) => (
              <LinkRow
                key={row.id}
                theme={theme}
                accent={accent}
                name={row.name}
                secondary={row.secondary}
                onUnlink={() => setPendingUnlink(row)}
                last={i === rows.length - 1}
              />
            ))}
          </Section>
        );
      })}

      <div style={{ padding: "22px 16px 0" }}>
        <button
          onClick={() => onAddAsset && onAddAsset()}
          style={{
            width: "100%",
            background: theme.text,
            color: theme.bg,
            border: "none",
            borderRadius: 16,
            padding: "14px",
            fontFamily: FONTS.ui,
            fontSize: 13.5,
            fontWeight: 600,
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: 8,
          }}
        >
          <Ico.plus size={15} stroke={theme.bg} sw={2} /> Link a new account
        </button>
      </div>

      {pendingUnlink && (
        <UnlinkConfirm
          theme={theme}
          accent={accent}
          row={pendingUnlink}
          onCancel={() => setPendingUnlink(null)}
          onConfirm={() => {
            setItems((prev) => prev.filter((i) => i.id !== pendingUnlink.id));
            setPendingUnlink(null);
          }}
        />
      )}
    </Screen>
  );
}

function Section({ theme, label, children }) {
  return (
    <div style={{ padding: "22px 16px 0" }}>
      <SectionLabel theme={theme} style={{ padding: "0 4px 8px" }}>
        {label}
      </SectionLabel>
      <Card theme={theme} padded={false}>
        {children}
      </Card>
    </div>
  );
}

function LinkRow({ theme, accent, name, secondary, onUnlink, last }) {
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        gap: 12,
        padding: "13px 16px",
        borderBottom: last ? "none" : `0.5px solid ${theme.line}`,
      }}
    >
      <BrandLogo name={name} size={32} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, color: theme.text, fontWeight: 500 }}>
          {name}
        </div>
        <div
          style={{
            fontSize: 11,
            color: theme.textMute,
            marginTop: 2,
            fontFamily: FONTS.mono,
            letterSpacing: 0.3,
          }}
        >
          {secondary}
        </div>
      </div>
      <button
        onClick={onUnlink}
        style={{
          background: "transparent",
          border: "none",
          color: theme.negative,
          fontFamily: FONTS.ui,
          fontSize: 12,
          fontWeight: 600,
          cursor: "pointer",
          padding: "4px 8px",
        }}
      >
        Unlink
      </button>
    </div>
  );
}

function UnlinkConfirm({ theme, accent, row, onCancel, onConfirm }) {
  return (
    <div
      onClick={onCancel}
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 100,
        display: "flex",
        alignItems: "flex-end",
        background: "rgba(0,0,0,0.55)",
      }}
    >
      <style>{`@keyframes himma-unlink-slide { from { transform: translateY(20px); opacity: 0 } to { transform: translateY(0); opacity: 1 } }`}</style>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "100%",
          background: theme.surface,
          borderRadius: "24px 24px 0 0",
          borderTop: `0.5px solid ${theme.line2}`,
          padding: "18px 20px 28px",
          animation: "himma-unlink-slide 220ms cubic-bezier(.2,.8,.25,1)",
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            paddingBottom: 14,
          }}
        >
          <div
            style={{
              width: 40,
              height: 4,
              borderRadius: 2,
              background: theme.line2,
            }}
          />
        </div>

        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 12,
            marginBottom: 12,
          }}
        >
          <BrandLogo name={row.name} size={40} />
          <div style={{ minWidth: 0 }}>
            <div
              style={{
                fontFamily: FONTS.display,
                fontSize: 18,
                color: theme.text,
              }}
            >
              Unlink {row.name}?
            </div>
            <div style={{ fontSize: 12, color: theme.textDim, marginTop: 2 }}>
              {row.secondary}
            </div>
          </div>
        </div>

        <div
          style={{
            fontSize: 13,
            color: theme.textDim,
            lineHeight: 1.55,
            marginTop: 6,
          }}
        >
          We’ll stop syncing balances and transactions from this account. Your
          historical data stays in Himma — you can relink anytime.
        </div>

        <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
          <button
            onClick={onCancel}
            style={{
              flex: 1,
              background: theme.surface2,
              border: `0.5px solid ${theme.line2}`,
              borderRadius: 14,
              padding: "12px",
              color: theme.text,
              fontFamily: FONTS.ui,
              fontSize: 13,
              fontWeight: 600,
              cursor: "pointer",
            }}
          >
            Cancel
          </button>
          <button
            onClick={onConfirm}
            style={{
              flex: 1,
              background: theme.negative,
              border: "none",
              borderRadius: 14,
              padding: "12px",
              color: "#fff",
              fontFamily: FONTS.ui,
              fontSize: 13,
              fontWeight: 600,
              cursor: "pointer",
            }}
          >
            Unlink
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  SettingsLinkedAccountsScreen,
  BrandLogo,
  getBrand,
  BRAND_LOGOS,
});
