// =============================================================================
// a-base.jsx — Variant A "Glasshouse" theme + base primitives
// =============================================================================
// Exports (window): A_TOK, aTheme, AFrame, ACard, ATag, AHeader, ATabBar, A
//
// • A_TOK     — design tokens (dark + light palette)
// • aTheme(t) — resolves a Tweaks object → consolidated theme {tk, card, ink, ...}
// • AFrame    — iPhone bezel + safe-area-aware page wrapper
// • ACard     — themed card surface (glass / solid / outline)
// • ATag      — small status pill (long / short / neutral)
// • AHeader   — top app-bar primitive (eyebrow + title + right slot)
// • ATabBar   — bottom tab bar (持仓 · 仓位 · 历史 · 钱包)
//
// Visual language: warm charcoal (dark) / institutional white (light),
// teal accent (#5cdcc9 / #0d8a7a), Inter Tight + JetBrains Mono digits.
// =============================================================================

// ── Layout constants (single source of truth) ───────────────────────────────
const A_LAYOUT = {
  pagePadX:    16,   // horizontal padding for page chrome (header / tab bar gutter)
  cardPadX:    14,   // horizontal padding inside a card
  // iOS status bar (54) + ~16px breathing room so titles never collide with
  // the dynamic island. Real PWA installs use safe-area-inset-top, see AFrame.
  statusBar:   70,
  topPad:      16,   // extra pad below the status bar / safe-area
  chartH:      400,  // TradingView widget canvas height
  deviceW:     390,
  deviceH:     820,
};

// ── Color tokens ────────────────────────────────────────────────────────────
const A_TOK = {
  dark: {
    // Bybit-style dark — deep near-black page, raised neutral panels lighter
    // than bg, crisp white ink. Mirrors the institutional light palette.
    bg:    '#0b0e11',
    bgs:   { dark:'#17181f', darker:'#0b0e11', abyss:'#000000' },
    ink:   '#eaecef',
    dim:   'rgba(234,236,239,0.62)',
    faint: 'rgba(234,236,239,0.36)',
    hair:  'rgba(234,236,239,0.08)',
    accent:'#5cdcc9',
    onAccent: '#04130f',
    glassBg: 'linear-gradient(180deg, rgba(255,255,255,0.04), rgba(255,255,255,0.015))',
    glassBorder: '1px solid rgba(255,255,255,0.06)',
    solidBg: '#1f2129', solidBorder: '1px solid rgba(255,255,255,0.04)',
    outlineBorder: '1px solid rgba(255,255,255,0.10)',
    sheetBg: 'rgba(31,33,41,0.94)',
    sheetBorder: '1px solid rgba(255,255,255,0.06)',
    scrim: 'rgba(0,0,0,0.55)',
  },
  light: {
    // Bybit-style light — clean near-white surfaces, subtle warm gray panels,
    // crisp dark ink. Reads professional / institutional.
    bg:    '#ffffff',
    bgs:   { dark:'#f4f4f5', darker:'#ffffff', abyss:'#fafafa' },
    ink:   '#17181f',
    dim:   'rgba(23,24,31,0.62)',
    faint: 'rgba(23,24,31,0.40)',
    hair:  'rgba(23,24,31,0.08)',
    accent:'#0d8a7a',
    onAccent: '#ffffff',
    glassBg: 'linear-gradient(180deg, rgba(255,255,255,0.82), rgba(255,255,255,0.55))',
    glassBorder: '1px solid rgba(23,24,31,0.06)',
    solidBg: '#f7f7f8', solidBorder: '1px solid rgba(23,24,31,0.06)',
    outlineBorder: '1px solid rgba(23,24,31,0.10)',
    sheetBg: 'rgba(255,255,255,0.96)',
    sheetBorder: '1px solid rgba(23,24,31,0.08)',
    scrim: 'rgba(0,0,0,0.35)',
  },
};

// ── Theme resolver ──────────────────────────────────────────────────────────
// Take the Tweaks object (mode / card / numFont / pnl / bg) → consolidated theme.
function aTheme(t = {}) {
  const mode = t.mode || 'dark';
  const tk = A_TOK[mode];
  const cardStyles = {
    glass:   { background: tk.glassBg, border: tk.glassBorder, backdropFilter: 'blur(20px) saturate(140%)' },
    solid:   { background: tk.solidBg, border: tk.solidBorder, backdropFilter: 'none' },
    outline: { background: 'transparent', border: tk.outlineBorder, backdropFilter: 'none' },
  };
  const numFonts = {
    mono:  '"JetBrains Mono", ui-monospace, "SF Mono", monospace',
    serif: '"Newsreader", Georgia, serif',
    sans:  '"Inter Tight", system-ui, sans-serif',
  };
  return {
    mode, tk, isDark: mode === 'dark',
    card: cardStyles[t.card || 'glass'],
    numFont: numFonts[t.numFont || 'mono'],
    accent: tk.accent, onAccent: tk.onAccent,
    pnlMode: t.pnl || 'rg',
    bg: tk.bgs[t.bg || 'darker'],
    ink: tk.ink, dim: tk.dim, faint: tk.faint, hair: tk.hair,
    L: A_LAYOUT,
  };
}

// ── AFrame: iPhone bezel (desktop preview) OR fullscreen (PWA / mobile) ─────
// Standalone mode bypasses IOSDevice and lets the host viewport (real iPhone /
// installed PWA) BE the device. Detection: window.HL_STANDALONE override,
// display-mode: standalone, or viewport ≤ 480px.
function useStandaloneMode() {
  const detect = () => {
    if (typeof window === 'undefined') return false;
    if (window.HL_STANDALONE === true)  return true;
    if (window.HL_STANDALONE === false) return false;
    try {
      if (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) return true;
      if (window.navigator && window.navigator.standalone) return true;
    } catch (e) {}
    // Phones (incl. iPhone Pro Max @ 430) + small tablets fill viewport;
    // desktop preview gets the bezel above this width.
    return window.innerWidth <= 640;
  };
  const [v, setV] = React.useState(detect);
  React.useEffect(() => {
    const onResize = () => setV(detect());
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return v;
}

function AFrame({ children, t, screenLabel }) {
  const th = aTheme(t);
  const standalone = useStandaloneMode();
  const fontStack = '"Inter Tight", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif';

  // Theme the chrome (page bg, theme-color meta) so the browser's safe-area
  // paint matches the active screen.
  React.useEffect(() => {
    if (typeof document === 'undefined') return;
    document.documentElement.style.background = th.bg;
    document.body.style.background = th.bg;
    document.body.style.color = th.ink;
    let meta = document.querySelector('meta[name="theme-color"]:not([media])');
    if (!meta) {
      meta = document.createElement('meta');
      meta.setAttribute('name', 'theme-color');
      document.head.appendChild(meta);
    }
    meta.setAttribute('content', th.bg);
  }, [th.bg, th.ink]);

  if (standalone) {
    return (
      <div data-screen-label={screenLabel} style={{
        position:'fixed', inset:0, background: th.bg,
        fontFamily: fontStack, color: th.ink, overflow:'hidden',
      }}>
        <div style={{ position:'absolute', inset:0,
          paddingTop:    `calc(env(safe-area-inset-top) + ${th.L.topPad}px)`,
          paddingBottom: 'env(safe-area-inset-bottom)',
          paddingLeft:   'env(safe-area-inset-left)',
          paddingRight:  'env(safe-area-inset-right)',
          display:'flex', flexDirection:'column' }}>
          {children}
        </div>
      </div>
    );
  }

  return (
    <IOSDevice dark={th.isDark} width={th.L.deviceW} height={th.L.deviceH}>
      <div data-screen-label={screenLabel} style={{
        position:'absolute', inset:0, background: th.bg,
        fontFamily: fontStack, color: th.ink, overflow:'hidden',
      }}>
        <div style={{ position:'absolute', inset:0, paddingTop: th.L.statusBar, display:'flex', flexDirection:'column' }}>
          {children}
        </div>
      </div>
    </IOSDevice>
  );
}

// ── ACard: themed surface ───────────────────────────────────────────────────
function ACard({ t, children, style={}, padded=true }) {
  const th = aTheme(t);
  return <div style={{ ...th.card, borderRadius: 18, padding: padded ? th.L.cardPadX : 0, ...style }}>{children}</div>;
}

// ── ATag: side / status pill ────────────────────────────────────────────────
function ATag({ children, tone='neutral', t }) {
  const th = aTheme(t);
  const tones = {
    long:    { bg: th.isDark?'rgba(34,197,94,0.14)':'rgba(34,197,94,0.16)',  fg: th.isDark?'#7ee2a8':'#15803d' },
    short:   { bg: 'rgba(239,68,68,0.14)', fg: th.isDark?'#fca5a5':'#b91c1c' },
    neutral: { bg: th.isDark?'rgba(255,255,255,0.06)':'rgba(0,0,0,0.06)',     fg: th.dim },
  };
  const c = tones[tone];
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:4,
      fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em',
      padding: '3px 7px', borderRadius: 5,
      background: c.bg, color: c.fg,
    }}>{children}</span>
  );
}

// ── AHeader: standardized top bar ───────────────────────────────────────────
// Use on every screen to keep padding/rhythm consistent.
//   <AHeader t={t} eyebrow="动态" title="历史成交" right={<button>...</button>}/>
//   <AHeader t={t} left={<BackBtn/>} center={<SymbolBlock/>}/>
function AHeader({ t, eyebrow, title, left, right, center, style={} }) {
  const th = aTheme(t);
  return (
    <div style={{
      padding: `4px ${th.L.pagePadX + 2}px 10px`,
      display:'flex', justifyContent:'space-between', alignItems: center ? 'center' : 'flex-end',
      flexShrink: 0, ...style,
    }}>
      {left ?? (
        <div>
          {eyebrow && <div style={{ fontSize:12, color:th.dim, letterSpacing:'0.18em' }}>{eyebrow}</div>}
          {title   && <div style={{ fontSize:22, fontWeight:600, marginTop:2 }}>{title}</div>}
        </div>
      )}
      {center}
      {right ?? <div style={{ width: 30 }}/>}
    </div>
  );
}

// Compatibility export — older call sites spread `A.*`. Defaults to dark tokens.
const A = A_TOK.dark;

// ── ATabBar: bottom navigation ──────────────────────────────────────────────
// Tabs map 1-1 to screen ids — onNav is invoked with the screen id ('home' is portfolio).
const A_TABS = [
  { id: 'markets',  label: '行情' },
  { id: 'home',     label: '持仓' },
  { id: 'history',  label: '历史' },
  { id: 'wallets',  label: '钱包' },
];
const A_TAB_ICONS = { markets: 'bars', home: 'home', history: 'list', wallets: 'wallet' };

function ATabBar({ active='home', onNav, t }) {
  const th = aTheme(t);
  // Glassmorphism dock — semi-transparent + heavy blur backdrop, bold text,
  // taller padding so it reads as substantial chrome.
  const isDark = th.isDark;
  const glassBg = isDark
    ? 'linear-gradient(180deg, rgba(20,24,28,0.78), rgba(15,18,22,0.72))'
    : 'linear-gradient(180deg, rgba(255,255,255,0.85), rgba(255,255,255,0.72))';
  const glassBorder = isDark
    ? '1px solid rgba(255,255,255,0.08)'
    : '1px solid rgba(23,24,31,0.06)';
  const glassShadow = isDark
    ? '0 -2px 14px rgba(0,0,0,0.36), 0 1px 0 rgba(255,255,255,0.04) inset'
    : '0 -2px 14px rgba(23,24,31,0.10), 0 1px 0 rgba(255,255,255,0.55) inset';
  return (
    <div style={{
      margin: `0 ${th.L.pagePadX - 2}px 18px`,
      borderRadius: 24,
      padding: '10px 6px 12px',
      display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:2,
      flexShrink: 0,
      background: glassBg,
      border: glassBorder,
      backdropFilter: 'blur(28px) saturate(180%)',
      WebkitBackdropFilter: 'blur(28px) saturate(180%)',
      boxShadow: glassShadow,
    }}>
      {A_TABS.map(it => {
        const on = it.id === active;
        return (
          <button key={it.id} onClick={() => onNav?.(it.id)} style={{
            background:'transparent', border:0, padding:'8px 0',
            display:'flex', flexDirection:'column', alignItems:'center', gap:5,
            color: on ? th.accent : th.faint, cursor:'pointer',
          }}>
            {Icon[A_TAB_ICONS[it.id]]('currentColor', 22)}
            <span style={{ fontSize: 12, fontWeight: 700, letterSpacing:'0.02em' }}>{it.label}</span>
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, { A, A_TOK, A_LAYOUT, aTheme, AFrame, ACard, ATag, AHeader, ATabBar });
