/* global React */
const { useState, useEffect, useRef, useMemo } = React;

// ── Icons (inline Lucide stroke SVGs) ─────────────────────────────────
const Icon = ({ d, size = 14, sw = 1.75 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
    stroke="currentColor" strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"
    dangerouslySetInnerHTML={{ __html: d }} />
);
const IPlus     = (p) => <Icon {...p} d='<path d="M5 12h14M12 5v14"/>' />;
const ICopy     = (p) => <Icon {...p} d='<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>' />;
const ICheck    = (p) => <Icon {...p} d='<path d="M20 6 9 17l-5-5"/>' />;
const IArrowL   = (p) => <Icon {...p} d='<path d="M19 12H5M12 19l-7-7 7-7"/>' />;
const IArrowDL  = (p) => <Icon {...p} d='<line x1="17" y1="7" x2="7" y2="17"/><polyline points="17 17 7 17 7 7"/>' />;
const IArrowUR  = (p) => <Icon {...p} d='<line x1="7" y1="17" x2="17" y2="7"/><polyline points="7 7 17 7 17 17"/>' />;
const IZap      = (p) => <Icon {...p} d='<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>' />;
const IShield   = (p) => <Icon {...p} d='<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>' />;
const IEye      = (p) => <Icon {...p} d='<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>' />;
const IExt      = (p) => <Icon {...p} d='<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>' />;
const IPause    = (p) => <Icon {...p} d='<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>' />;
const ISettings = (p) => <Icon {...p} d='<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>' />;
const ILogout   = (p) => <Icon {...p} d='<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9"/>' />;
const IChevron  = (p) => <Icon {...p} d='<polyline points="6 9 12 15 18 9"/>' />;
const IKey      = (p) => <Icon {...p} d='<circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6M15.5 7.5l3 3L22 7l-3-3"/>' />;

// ── Primitives ────────────────────────────────────────────────────────
const Button = ({ variant = 'primary', size = 'md', children, className = '', style, ...p }) => {
  const sizes = { sm: 'h-[30px] px-3 text-[11px]', md: 'h-[36px] px-3.5 text-[12px]', lg: 'h-[42px] px-5 text-[13px]' };
  const variants = {
    primary:   { className: 'text-white font-medium', style: { background: 'var(--ks-coral-gradient)' } },
    secondary: { className: 'text-[var(--ks-fg-2)] border', style: { background: 'var(--ks-surface-input)', borderColor: 'var(--ks-border)' } },
    deposit:   { className: 'font-medium border', style: { background: 'var(--ks-success-glow)', color: 'var(--ks-success)', borderColor: 'rgba(74,222,128,0.15)' } },
    withdraw:  { className: 'font-medium border', style: { background: 'var(--ks-danger-glow)', color: 'var(--ks-danger)', borderColor: 'rgba(248,113,113,0.15)' } },
    skill:     { className: 'font-medium border', style: { background: 'var(--ks-special-glow)', color: 'var(--ks-special)', borderColor: 'rgba(167,139,250,0.15)' } },
    ghost:     { className: 'text-[var(--ks-fg-2)]', style: {} },
  };
  const v = variants[variant];
  return (
    <button {...p}
      className={`inline-flex items-center justify-center gap-1.5 rounded-full transition-all duration-200 cursor-pointer hover:-translate-y-px active:scale-[0.97] ${sizes[size]} ${v.className} ${className}`}
      style={{ ...v.style, ...style }}>{children}</button>
  );
};

const Label = ({ children, className = '' }) => (
  <div className={`text-[10px] font-semibold uppercase tracking-[0.5px] text-[var(--ks-fg-3)] ${className}`}>{children}</div>
);

const StatusPill = ({ status }) => {
  if (status === 'active') return (
    <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-[3px] text-[9px] font-semibold uppercase tracking-[0.5px]"
      style={{ background: 'var(--ks-success-glow)', color: 'var(--ks-success)' }}>
      <span className="w-1 h-1 rounded-full ks-pulse" style={{ background: 'var(--ks-success)', boxShadow: '0 0 8px rgba(74,222,128,0.4)' }} />
      Active
    </span>
  );
  return (
    <span className="inline-flex px-1.5 py-0.5 rounded-[3px] text-[9px] font-semibold uppercase tracking-[0.5px]"
      style={{ background: 'var(--ks-warning-glow)', color: 'var(--ks-warning)' }}>Paused</span>
  );
};

const SpendingBar = ({ spent, deposited, showLabel = true }) => {
  const pct = deposited > 0 ? Math.min((spent / deposited) * 100, 100) : 0;
  const color = pct >= 80 ? 'var(--ks-danger)' : pct > 50 ? 'var(--ks-warning)' : 'var(--ks-coral)';
  return (
    <div className="flex items-center gap-3">
      <div className="flex-1 h-[6px] rounded-full overflow-hidden" style={{ background: 'var(--ks-border)' }}>
        <div className="h-full rounded-full" style={{ width: `${Math.max(pct, 1)}%`, background: color, boxShadow: `0 0 10px ${color}50`, transition: 'width 700ms ease-out' }} />
      </div>
      {showLabel && <span className="text-[10px] font-mono shrink-0" style={{ color: pct > 80 ? 'var(--ks-danger)' : 'var(--ks-fg-3)' }}>{Math.round(pct)}% spent</span>}
    </div>
  );
};

const Card = ({ variant = 'default', className = '', style, children, onClick }) => {
  const styles = {
    default: { background: 'linear-gradient(145deg, #151a24, #121620)', border: '1px solid #1e2438', boxShadow: '0 0 0 1px rgba(255,255,255,0.02) inset' },
    glow:    { background: 'linear-gradient(145deg, #161c28, #111620)', border: '1px solid #283048', boxShadow: '0 0 0 1px rgba(255,255,255,0.03) inset, 0 0 24px rgba(238,96,85,0.04)' },
    accent:  { background: 'linear-gradient(145deg, #1a1619, #141012)', border: '1px solid rgba(238,96,85,0.22)', boxShadow: '0 0 0 1px rgba(238,96,85,0.04) inset, 0 0 30px rgba(238,96,85,0.08)', position: 'relative', overflow: 'hidden' },
  };
  return (
    <div onClick={onClick} className={`rounded-2xl ${onClick ? 'cursor-pointer hover:-translate-y-px transition-transform' : ''} ${className}`} style={{ ...styles[variant], ...style }}>
      {variant === 'accent' && <div className="pointer-events-none absolute" style={{ bottom: '-40%', right: '-20%', width: '60%', height: '80%', background: 'radial-gradient(ellipse, rgba(238,96,85,0.12) 0%, transparent 70%)' }} />}
      <div className="relative">{children}</div>
    </div>
  );
};

// ── TopBar ─────────────────────────────────────────────────────────────
const TopBar = ({ currentPath, onNav, authed }) => {
  const tabs = [
    { href: 'dashboard', label: 'Agent Wallets' },
    { href: 'skills', label: 'Skills' },
    { href: 'why', label: 'Why' },
    { href: 'security', label: 'Security' },
  ];
  return (
    <header className="h-16 flex items-center justify-between px-5 shrink-0 border-b" style={{ background: 'var(--ks-ink)', borderColor: 'var(--ks-border)' }}>
      <div className="flex items-center gap-5">
        <a onClick={() => onNav('dashboard')} className="flex items-center gap-2 cursor-pointer">
          <img src="../../assets/keysmith-logo.png" alt="Keysmith" style={{ height: 22, width: 'auto' }} />
        </a>
        <nav className="flex items-center gap-1">
          {tabs.map((t) => {
            const active = currentPath === t.href || (t.href === 'dashboard' && currentPath === 'detail');
            return (
              <a key={t.href} onClick={() => onNav(t.href)}
                className={`text-[13px] px-3 py-1.5 rounded-full transition-all duration-200 cursor-pointer ${active ? 'font-medium' : ''}`}
                style={active ? { background: 'var(--ks-coral-glow)', color: 'var(--ks-coral)' } : { color: 'var(--ks-fg-2)' }}>
                {t.label}
              </a>
            );
          })}
        </nav>
      </div>
      {authed && (
        <div className="flex items-center gap-3">
          <BalanceChip />
          <button onClick={() => onNav('login')} className="w-8 h-8 rounded-full border flex items-center justify-center cursor-pointer hover:text-[var(--ks-danger)] transition-colors" style={{ borderColor: 'var(--ks-border)', color: 'var(--ks-fg-3)' }} title="Logout">
            <ILogout size={13} />
          </button>
        </div>
      )}
    </header>
  );
};

const BalanceChip = () => (
  <div className="flex items-center gap-2 h-[30px] px-2.5 rounded-full cursor-pointer transition-all" style={{ background: 'var(--ks-surface)', border: '1px solid var(--ks-border)' }}>
    <span className="text-[10px] font-semibold uppercase tracking-wide" style={{ color: 'var(--ks-fg-3)' }}>Base</span>
    <span className="text-[11px] font-mono font-bold" style={{ color: 'var(--ks-success)' }}>12,450.32</span>
    <span className="text-[10px]" style={{ color: 'var(--ks-fg-3)' }}>USDC</span>
    <IChevron size={9} />
  </div>
);

// ── Sidebar ────────────────────────────────────────────────────────────
const Sidebar = ({ wallets, activeId, onSelect, onCreate }) => (
  <aside className="w-[220px] flex flex-col shrink-0 border-r" style={{ background: 'var(--ks-ink-sidebar)', borderColor: 'var(--ks-border)' }}>
    <div className="p-3 pt-4 px-4"><Label>Your Wallets</Label></div>
    <div className="flex-1 overflow-y-auto px-2 space-y-0.5">
      {wallets.map((w) => {
        const isA = w.id === activeId;
        return (
          <a key={w.id} onClick={() => onSelect(w.id)}
            className="relative flex items-center gap-2 px-2.5 py-2 rounded-lg transition-all duration-200 cursor-pointer"
            style={isA
              ? { background: 'var(--ks-surface)', border: '1px solid transparent', backgroundImage: 'linear-gradient(var(--ks-surface),var(--ks-surface)),linear-gradient(135deg,rgba(238,96,85,0.35),rgba(238,96,85,0.1))', backgroundOrigin: 'border-box', backgroundClip: 'padding-box, border-box' }
              : { background: 'transparent' }}>
            <span className="text-[14px] shrink-0" style={{ fontFamily: 'var(--font-emoji)' }}>{w.emoji}</span>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-1.5">
                <span className="text-[12px] font-medium truncate" style={{ color: isA ? 'var(--ks-fg-1)' : 'var(--ks-fg-2)' }}>{w.name}</span>
                {w.status === 'active' && <span className="w-1 h-1 rounded-full ks-pulse shrink-0" style={{ background: 'var(--ks-success)', boxShadow: '0 0 8px rgba(74,222,128,0.3)' }} />}
              </div>
              <span className="text-[10px] font-mono" style={{ color: isA ? 'var(--ks-coral)' : 'var(--ks-fg-3)' }}>${w.balance.toLocaleString()}</span>
            </div>
          </a>
        );
      })}
      <a onClick={onCreate} className="flex items-center gap-2 px-2.5 py-2 mt-1 rounded-lg transition-all duration-200 cursor-pointer" style={{ color: 'var(--ks-coral)' }}>
        <IPlus size={12} />
        <span className="text-[12px] font-medium">New Wallet</span>
      </a>
    </div>
  </aside>
);

// ── Stat card, Wallet card, Tx row ────────────────────────────────────
const StatCard = ({ label, value, color }) => (
  <Card variant="glow"><div className="p-4">
    <Label>{label}</Label>
    <div className="text-[20px] font-mono font-bold mt-1" style={{ color: color || 'var(--ks-fg-1)' }}>{value}</div>
  </div></Card>
);

const WalletCard = ({ wallet, onClick, index = 0 }) => {
  const daysLeft = Math.max(0, Math.ceil((new Date(wallet.expires_at).getTime() - Date.now()) / 86400000));
  return (
    <Card onClick={onClick} className="ks-fade-in" style={{ animationDelay: `${index * 0.04}s` }}>
      <div className="p-4">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <span className="text-[14px] shrink-0" style={{ fontFamily: 'var(--font-emoji)' }}>{wallet.emoji}</span>
            <span className="text-[14px] font-semibold">{wallet.name}</span>
          </div>
          <div className="text-right">
            <div className="text-[16px] font-mono font-bold" style={{ color: 'var(--ks-success)' }}>${wallet.balance.toLocaleString(undefined, { minimumFractionDigits: 2 })}</div>
            <div className="text-[10px] font-mono" style={{ color: 'var(--ks-fg-3)' }}>USDC</div>
          </div>
        </div>
        <div className="flex items-center gap-2 mb-3 text-[10px]" style={{ color: 'var(--ks-fg-3)' }}>
          <StatusPill status={wallet.status} />
          <span>{daysLeft}d left</span>
          <span className="font-mono">{wallet.id}</span>
        </div>
        <div className="grid grid-cols-3 gap-3 mb-3">
          {[['Deposited', `$${wallet.deposited.toLocaleString()}`, 'var(--ks-fg-1)'], ['Spent', `$${wallet.spent.toLocaleString()}`, 'var(--ks-fg-1)'], ['Max/tx', `$${wallet.max_per_tx}`, 'var(--ks-warning)']].map(([l, v, c]) => (
            <div key={l}>
              <Label className="mb-0.5">{l}</Label>
              <div className="text-[13px] font-mono font-semibold" style={{ color: c }}>{v}</div>
            </div>
          ))}
        </div>
        <SpendingBar spent={wallet.spent} deposited={wallet.deposited} />
        {wallet.last_active && <div className="mt-2 text-[10px] font-mono" style={{ color: 'var(--ks-fg-3)' }}>Last active: {new Date(wallet.last_active).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</div>}
      </div>
    </Card>
  );
};

const TxRow = ({ tx, isLast }) => {
  const isIn = tx.type === 'fund' || tx.type === 'deposit';
  const isRej = tx.status === 'rejected';
  const cfg = isRej
    ? { Icn: IZap, bg: 'var(--ks-danger-glow)', fg: 'var(--ks-danger)' }
    : isIn
      ? { Icn: IArrowDL, bg: 'var(--ks-success-glow)', fg: 'var(--ks-success)' }
      : { Icn: IZap, bg: 'var(--ks-warning-glow)', fg: 'var(--ks-warning)' };
  return (
    <div className={`flex items-center gap-3 py-2.5 ${!isLast ? 'border-b' : ''}`} style={{ borderColor: 'var(--ks-border)' }}>
      <div className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0" style={{ background: cfg.bg, color: cfg.fg }}>
        <cfg.Icn size={12} />
      </div>
      <div className="flex-1 min-w-0">
        <div className="text-[12px] font-medium truncate">{tx.description || tx.type}</div>
        <div className="text-[10px]" style={{ color: 'var(--ks-fg-3)' }}>{tx.timeAgo}</div>
      </div>
      <div className="text-right shrink-0">
        <div className="text-[11px] font-mono font-semibold" style={{ color: isRej ? 'var(--ks-danger)' : isIn ? 'var(--ks-success)' : 'var(--ks-fg-2)', textDecoration: isRej ? 'line-through' : 'none' }}>
          {isIn ? '+' : '-'}${tx.amount}
        </div>
        <div className="text-[9px] font-mono" style={{ color: 'var(--ks-fg-3)' }}>USDC</div>
      </div>
    </div>
  );
};

// ── Modals ─────────────────────────────────────────────────────────────
const Modal = ({ open, onClose, children, width = 420 }) => {
  if (!open) return null;
  return (
    <div className="fixed inset-0 flex items-center justify-center z-50" style={{ background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(4px)' }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} className="rounded-2xl p-6 ks-scale-in" style={{ background: 'var(--ks-ink-raised)', border: '1px solid var(--ks-border)', boxShadow: 'var(--sh-modal)', width, maxWidth: '90vw' }}>
        {children}
      </div>
    </div>
  );
};

const SignModal = ({ open, onClose, message, onSuccess, wallet }) => {
  const [phase, setPhase] = useState('idle');
  useEffect(() => { if (!open) setPhase('idle'); }, [open]);
  const sign = () => {
    setPhase('signing');
    setTimeout(() => { setPhase('done'); setTimeout(() => { onSuccess?.(); onClose(); }, 700); }, 1200);
  };
  return (
    <Modal open={open} onClose={onClose} width={360}>
      <div className="flex flex-col items-center">
        <div className="w-14 h-14 rounded-2xl flex items-center justify-center ks-glow mb-4" style={{ background: 'var(--ks-coral-glow)', color: 'var(--ks-coral)' }}>
          {phase === 'done' ? <ICheck size={22} /> : <IShield size={22} />}
        </div>
        <h2 className="text-[16px] font-bold mb-1" style={{ fontFamily: 'var(--font-display)' }}>
          {phase === 'done' ? 'Signed' : phase === 'signing' ? 'Waiting for passkey…' : 'Sign message'}
        </h2>
        <p className="text-[11px] mb-4 text-center" style={{ color: 'var(--ks-fg-2)' }}>
          {phase === 'idle' && 'Authenticate with Face ID or Touch ID to continue.'}
          {phase === 'signing' && 'Complete the prompt in your browser.'}
          {phase === 'done' && 'Authentication complete.'}
        </p>
        {phase === 'idle' && (
          <>
            <div className="w-full rounded-lg px-3 py-2 mb-3 font-mono text-[11px]" style={{ background: 'var(--ks-surface-input)', border: '1px solid var(--ks-border)', color: 'var(--ks-fg-2)' }}>{message}</div>
            <div className="w-full text-[11px] mb-4" style={{ color: 'var(--ks-fg-3)' }}>
              <div className="flex justify-between py-1"><span>Origin</span><span className="font-mono" style={{ color: 'var(--ks-fg-2)' }}>connect.keysmith.ai</span></div>
              <div className="flex justify-between py-1"><span>Wallet</span><span style={{ color: 'var(--ks-fg-2)' }}>{wallet}</span></div>
              <div className="flex justify-between py-1"><span>Network</span><span style={{ color: 'var(--ks-fg-2)' }}>Base</span></div>
            </div>
            <div className="flex gap-2 w-full">
              <Button variant="secondary" size="md" className="flex-1" onClick={onClose}>Reject</Button>
              <Button variant="primary" size="md" className="flex-1" onClick={sign}>Passkey</Button>
            </div>
          </>
        )}
        {phase === 'signing' && (
          <div className="w-full h-1 rounded-full overflow-hidden" style={{ background: 'var(--ks-border)' }}>
            <div className="h-full ks-progress" style={{ background: 'var(--ks-coral)' }} />
          </div>
        )}
      </div>
    </Modal>
  );
};

Object.assign(window, { Button, Label, StatusPill, SpendingBar, Card, TopBar, Sidebar, StatCard, WalletCard, TxRow, Modal, SignModal, IPlus, ICopy, ICheck, IArrowL, IArrowDL, IArrowUR, IZap, IShield, IEye, IExt, IPause, ISettings, ILogout, IChevron, IKey });
