// terminal-shell.jsx — Chrome (phone frame + top bar + bottom tab bar).
// Mobile-first 390 × 844, centered in a desktop viewport with subtle ambient
// background. The tab bar is the universal navigation primitive.

const TAB_DEFS = [
  { key: 'watchlists', label: 'Watchlists', icon: 'heart' },
  { key: 'markets',    label: 'Markets',    icon: 'planet' },
  { key: 'portfolio',  label: 'Portfolio',  icon: 'wallet' },
  { key: 'receipts',   label: 'Receipts',   icon: 'receipt' },
  { key: 'insights',   label: 'Insights',   icon: 'sparkle' },
  { key: 'council',    label: 'Council',    icon: 'orbit' },
];

function TabIcon({ name, color, size = 22 }) {
  const sw = 1.6;
  switch (name) {
    case 'heart':   return <svg width={size} height={size} viewBox="0 0 24 24" fill="none"><path d="M12 20s-7-4.5-7-10a4 4 0 0 1 7-2.5A4 4 0 0 1 19 10c0 5.5-7 10-7 10z" stroke={color} strokeWidth={sw} strokeLinejoin="round"/></svg>;
    case 'planet':  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="6" stroke={color} strokeWidth={sw}/><ellipse cx="12" cy="12" rx="11" ry="4" stroke={color} strokeWidth={sw} transform="rotate(-25 12 12)"/></svg>;
    case 'wallet':  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none"><rect x="3" y="6" width="18" height="14" rx="2" stroke={color} strokeWidth={sw}/><path d="M3 10h18" stroke={color} strokeWidth={sw}/><circle cx="16.5" cy="14.5" r="1.2" fill={color}/></svg>;
    case 'receipt': return <svg width={size} height={size} viewBox="0 0 24 24" fill="none"><path d="M5 3v18l2-1.5 2 1.5 2-1.5 2 1.5 2-1.5 2 1.5 2-1.5V3z" stroke={color} strokeWidth={sw} strokeLinejoin="round"/><line x1="8" y1="9"  x2="16" y2="9"  stroke={color} strokeWidth={sw}/><line x1="8" y1="13" x2="16" y2="13" stroke={color} strokeWidth={sw}/></svg>;
    case 'sparkle': return <svg width={size} height={size} viewBox="0 0 24 24" fill="none"><path d="M12 3v6M12 15v6M3 12h6M15 12h6M5.5 5.5l4 4M14.5 14.5l4 4M18.5 5.5l-4 4M9.5 14.5l-4 4" stroke={color} strokeWidth={sw} strokeLinecap="round"/></svg>;
    case 'orbit':   return <svg width={size} height={size} viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" stroke={color} strokeWidth={sw}/><ellipse cx="12" cy="12" rx="9" ry="5" stroke={color} strokeWidth={sw}/><circle cx="20" cy="12" r="1.4" fill={color}/></svg>;
    default: return null;
  }
}

// ── Top bar — back arrow · title · trailing actions ─────────
function TopBar({ title, subtitle, onBack, right, dense = false }) {
  return (
    <div style={{
      padding: dense ? '12px 16px 10px' : '14px 16px 12px',
      borderBottom: `1px solid ${TM.border}`,
      background: TM.bg, position: 'sticky', top: 0, zIndex: 10,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, minHeight: 36 }}>
        {onBack && (
          <button onClick={onBack} style={{
            width: 32, height: 32, borderRadius: 16,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: TM.text,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M9 1L3 7l6 6" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        )}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: GE, fontSize: 19, fontWeight: 600, color: TM.text,
            letterSpacing: -0.4, lineHeight: 1.1,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{title}</div>
          {subtitle && (
            <div style={{
              marginTop: 2, fontFamily: GM, fontSize: 10.5,
              color: TM.mutedDim, letterSpacing: 0.6, textTransform: 'uppercase',
            }}>{subtitle}</div>
          )}
        </div>
        {right}
      </div>
    </div>
  );
}

// ── Bottom tab bar — 6 tabs, active highlighted in QP orange ──
function BottomTabBar({ active, onChange }) {
  return (
    <nav style={{
      position: 'sticky', bottom: 0, left: 0, right: 0, zIndex: 20,
      background: TM.bg, borderTop: `1px solid ${TM.border}`,
      display: 'grid', gridTemplateColumns: `repeat(${TAB_DEFS.length}, 1fr)`,
      paddingTop: 4, paddingBottom: 'env(safe-area-inset-bottom, 4px)',
    }}>
      {TAB_DEFS.map(tab => {
        const isActive = tab.key === active;
        const color = isActive ? TM.orange : TM.mutedDim;
        return (
          <button key={tab.key} onClick={() => onChange(tab.key)} style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            padding: '8px 4px 6px', color, position: 'relative',
          }}>
            {isActive && (
              <span style={{
                position: 'absolute', top: -1, left: '30%', right: '30%', height: 2,
                background: TM.orange,
              }}/>
            )}
            <TabIcon name={tab.icon} color={color}/>
            <span style={{
              fontFamily: GE, fontSize: 10, fontWeight: 500, letterSpacing: -0.1,
            }}>{tab.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// ── Phone frame (mobile-first, but desktop wraps in a frame) ─
function PhoneFrame({ children }) {
  return (
    <div style={{
      minHeight: '100vh',
      background: `radial-gradient(ellipse 1200px 800px at 50% 0%, rgba(40,35,155,0.16), transparent 60%), ${TM.bg}`,
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      padding: 'max(0px, env(safe-area-inset-top, 24px)) 16px 0',
    }}>
      <div style={{
        width: '100%', maxWidth: 430,
        background: TM.surface, color: TM.text,
        border: `1px solid ${TM.border}`, borderRadius: 28,
        minHeight: 'calc(100vh - 16px)',
        position: 'relative', overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
        boxShadow: '0 30px 80px -20px rgba(0,0,0,0.6)',
      }}>
        {children}
      </div>
    </div>
  );
}

// ── AI button (templated from the screenshots) ───────────────
function AIButton({ onClick }) {
  // If no explicit handler, route to /news inside the terminal.
  const handler = onClick || (() => {
    const nav = window.__txNav; if (nav) nav('news');
  });
  return (
    <button onClick={handler} style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '5px 10px 5px 6px', borderRadius: 18,
      background: TM.surfaceHi, border: `1px solid ${TM.borderHi}`,
    }}>
      <span style={{
        width: 22, height: 22, borderRadius: '50%',
        background: TM.cyanSoft, border: `1px solid ${TM.cyan}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: TM.cyan,
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
          <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="1.6"/>
          <path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M18.4 5.6L17 7M7 17l-1.4 1.4"
            stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
        </svg>
      </span>
      <span style={{ fontFamily: GM, fontSize: 11, fontWeight: 500, color: TM.text, letterSpacing: 0.4 }}>AI</span>
    </button>
  );
}

// ── Mono pill (small chip with tabular text) ─────────────────
function Pill({ children, color = TM.muted, bg, border }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '3px 8px',
      background: bg || 'transparent',
      border: border ? `1px solid ${border}` : `1px solid ${TM.border}`,
      fontFamily: GM, fontSize: 10, fontWeight: 500, color, letterSpacing: 0.6,
      textTransform: 'uppercase', borderRadius: 4,
    }}>{children}</span>
  );
}

// ── Segmented control (used for tab bars in detail screens) ─
function Segmented({ options, value, onChange }) {
  return (
    <div style={{
      display: 'inline-flex', padding: 3,
      background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 8,
    }}>
      {options.map(o => {
        const isActive = o.key === value;
        return (
          <button key={o.key} onClick={() => onChange(o.key)} style={{
            padding: '6px 12px',
            background: isActive ? TM.surface : 'transparent',
            border: isActive ? `1px solid ${TM.borderHi}` : '1px solid transparent',
            borderRadius: 6, color: isActive ? TM.text : TM.muted,
            fontFamily: GE, fontSize: 12.5, fontWeight: 500, letterSpacing: -0.1,
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

// ── Section header — "Commodities >" pattern from screenshot 2 ─
function SectionHeader({ title, action, onAction }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
      padding: '24px 16px 12px',
    }}>
      <h2 style={{
        margin: 0, fontFamily: GE, fontSize: 22, fontWeight: 600,
        letterSpacing: -0.6, color: TM.text,
      }}>{title}</h2>
      {action && (
        <button onClick={onAction} style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          color: TM.muted, fontFamily: GE, fontSize: 13, fontWeight: 500,
        }}>{action} <span style={{ fontSize: 16, lineHeight: 1 }}>›</span></button>
      )}
    </div>
  );
}

// ── Universal search button (wraps the magnifier) ────────────
function SearchButton({ onClick }) {
  const handler = onClick || (() => {
    const nav = window.__txNav; if (nav) nav('search');
  });
  return (
    <button onClick={handler} style={{
      width: 32, height: 32, borderRadius: 16,
      display: 'flex', alignItems: 'center', justifyContent: 'center', color: TM.muted,
    }}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
        <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="1.6"/>
        <line x1="16" y1="16" x2="21" y2="21" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
      </svg>
    </button>
  );
}

// ── Account avatar button — routes to Account overlay ───────
function AccountButton() {
  const handler = () => {
    const nav = window.__txNav; if (nav) nav('account');
  };
  return (
    <button onClick={handler} style={{
      width: 32, height: 32, borderRadius: 16,
      background: TM.cyanSoft, border: `1px solid ${TM.cyan}55`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: GE, fontSize: 12, fontWeight: 600, color: TM.cyan, letterSpacing: 0.3,
    }}>JW</button>
  );
}

Object.assign(window, {
  TAB_DEFS, TabIcon, TopBar, BottomTabBar, PhoneFrame,
  AIButton, SearchButton, AccountButton, Pill, Segmented, SectionHeader,
});
