// Shell — phone chrome, navigation, status bar
const { useState, useEffect, useRef, createContext, useContext, useMemo } = React;

const AppCtx = createContext(null);
const useApp = () => useContext(AppCtx);

function useTheme() {
  const [theme, setTheme] = useState(() => window.__getTheme?.() || 'dark');
  useEffect(() => {
    const onChange = e => setTheme(e.detail);
    window.addEventListener('aitr-theme-change', onChange);
    return () => window.removeEventListener('aitr-theme-change', onChange);
  }, []);
  const toggle = () => window.__setTheme(theme === 'dark' ? 'light' : 'dark');
  return [theme, toggle];
}

function ThemeToggle({ variant = 'icon' }) {
  const [theme, toggle] = useTheme();
  const dark = theme === 'dark';
  if (variant === 'pill') {
    return (
      <button onClick={toggle} className="topbar-pill" style={{ width: 40, padding: 0, justifyContent: 'center' }} title={dark ? 'Switch to light' : 'Switch to dark'}>
        {dark
          ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
          : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
        }
      </button>
    );
  }
  return (
    <button onClick={toggle} className="icon-btn" title={dark ? 'Switch to light' : 'Switch to dark'}>
      {dark
        ? <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
        : <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
      }
    </button>
  );
}

function StatusBar() {
  return (
    <div className="statusbar">
      <span>9:41</span>
      <div className="icons">
        <svg width="17" height="11" viewBox="0 0 17 11" fill="currentColor"><circle cx="2" cy="9" r="1.5"/><circle cx="6" cy="7" r="1.5"/><circle cx="10" cy="5" r="1.5"/><circle cx="14" cy="3" r="1.5"/></svg>
        <svg width="16" height="12" viewBox="0 0 16 12" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M1 5c2-2 4-3 7-3s5 1 7 3"/><path d="M3 7.5c1.5-1.5 3-2 5-2s3.5.5 5 2"/><circle cx="8" cy="10" r="1" fill="currentColor"/></svg>
        <svg width="26" height="12" viewBox="0 0 26 12" fill="none"><rect x="0.5" y="0.5" width="22" height="11" rx="3" stroke="currentColor" opacity="0.4"/><rect x="2" y="2" width="19" height="8" rx="1.5" fill="currentColor"/><rect x="23.5" y="4" width="2" height="4" rx="1" fill="currentColor" opacity="0.5"/></svg>
      </div>
    </div>
  );
}

function Logo({ size = 'md' }) {
  const sz = size === 'lg' ? 56 : size === 'sm' ? 28 : 36;
  const fz = size === 'lg' ? 22 : size === 'sm' ? 13 : 16;
  return (
    <div className="logo">
      <div className="logo-mark" style={{ width: sz, height: sz, borderRadius: sz/3, fontSize: fz }}>
        <span>▲</span>
      </div>
      <div style={{ fontSize: size === 'lg' ? 24 : 18, lineHeight: 1 }}>
        AITrader
      </div>
    </div>
  );
}

function AppBar({ title, onBack, right, large }) {
  return (
    <div className="appbar" style={large ? { padding: '8px 20px 6px' } : {}}>
      <div className="row" style={{ gap: 10, flex: 1, minWidth: 0 }}>
        {onBack && (
          <button className="back" onClick={onBack} aria-label="Back">
            <I.back />
          </button>
        )}
        <h1 style={{ fontSize: large ? 32 : 22, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title}</h1>
      </div>
      <div className="appbar-actions">{right}</div>
    </div>
  );
}

function TabBar() {
  const { route, go } = useApp();
  const tabs = [
    { id: 'dashboard', label: 'Home', icon: 'home' },
    { id: 'accounts', label: 'Accounts', icon: 'chart' },
    { id: 'trade', label: '', icon: 'trade' },
    { id: 'history', label: 'History', icon: 'wallet' },
    { id: 'profile', label: 'Profile', icon: 'user' },
  ];
  const active = ['dashboard','accounts','history','profile'].includes(route) ? route : null;
  const openTrade = () => {
    window.open('about:blank', '_blank');
    setTimeout(() => alert('AI WebTrader would open in a new tab.\n\n(Demo: external trading platform)'), 50);
  };
  return (
    <div className="tabbar">
      {tabs.map(t => {
        if (t.id === 'trade') return (
          <div key="trade" className="tab trade" onClick={openTrade}>
            <I.trade size={26} />
          </div>
        );
        return (
          <div key={t.id} className={'tab ' + (active === t.id ? 'active' : '')} onClick={() => go(t.id)}>
            {I[t.icon]({ size: 22 })}
            <span>{t.label}</span>
          </div>
        );
      })}
    </div>
  );
}

function Toast({ msg, onClose }) {
  useEffect(() => {
    if (!msg) return;
    const id = setTimeout(onClose, 2200);
    return () => clearTimeout(id);
  }, [msg]);
  if (!msg) return null;
  return <div className="toast"><I.check /> {msg}</div>;
}

window.StatusBar = StatusBar;
window.Logo = Logo;
window.AppBar = AppBar;
window.TabBar = TabBar;
window.Toast = Toast;
window.AppCtx = AppCtx;
window.useApp = useApp;
