// Towbook-skinned Android phone frame.
// Wraps content in a phone-shaped chrome with status bar, optional app bar, content area, and gesture nav.
// Differs from the generic starter: uses Towbook brand blue app bar by default, Inter type, status pill mapping.

const { useState } = React;

// Status bar — battery / wifi / signal / clock. Color flips with theme.
function TBStatusBar({ tone = 'light', time = '4:54' }) {
  // tone: 'light' (dark icons on light bg), 'dark' (light icons on dark bg), 'primary' (light icons on blue)
  const fg = tone === 'light' ? '#1e1f24' : '#ffffff';
  return (
    <div style={{
      height: 28,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '0 16px',
      fontFamily: 'var(--font-sans)',
      color: fg,
      flexShrink: 0,
    }}>
      <span style={{ fontSize: 13, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{time}</span>
      <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
        {/* signal */}
        <svg width="14" height="14" viewBox="0 0 16 16"><path d="M2 14h2v-2H2v2zm4 0h2V9H6v5zm4 0h2V5h-2v9zm4 0h2V1h-2v13z" fill={fg}/></svg>
        {/* wifi */}
        <svg width="14" height="14" viewBox="0 0 16 16"><path d="M8 11.5a1.5 1.5 0 100 3 1.5 1.5 0 000-3zm-3.5-2.4l1.4 1.4a3 3 0 014.2 0l1.4-1.4a5 5 0 00-7 0zm-2.5-2.5l1.4 1.4a6.5 6.5 0 019.2 0l1.4-1.4a8.5 8.5 0 00-12 0z" fill={fg}/></svg>
        {/* battery */}
        <svg width="20" height="12" viewBox="0 0 22 12">
          <rect x="0.5" y="0.5" width="19" height="11" rx="2" fill="none" stroke={fg} strokeWidth="1"/>
          <rect x="2" y="2" width="13" height="8" rx="1" fill={fg}/>
          <rect x="20" y="3.5" width="1.5" height="5" rx="0.5" fill={fg}/>
        </svg>
      </div>
    </div>
  );
}

// Top app bar — Towbook brand uses solid primary. Variant 'surface' for low-emphasis screens.
function TBAppBar({
  title,
  variant = 'primary',  // 'primary' | 'surface'
  leading,              // {icon, onClick} — defaults to menu / back
  trailing = [],        // [{icon, onClick, badge?}]
  onMenu, onBack,
  centered = false,
  size = 'small',       // 'small' | 'medium' | 'large'
}) {
  const isPrimary = variant === 'primary';
  const bg = isPrimary ? 'var(--tb-primary)' : 'var(--tb-surface)';
  const fg = isPrimary ? 'var(--tb-on-primary)' : 'var(--tb-on-surface)';
  const border = isPrimary ? 'transparent' : '1px solid var(--tb-divider)';

  const Icon = leading?.icon || (onBack ? I.ArrowLeft : I.Menu);
  const onLeading = leading?.onClick || onBack || onMenu;

  const titleSize = size === 'large' ? 28 : size === 'medium' ? 22 : 18;
  const titleWeight = size === 'small' ? 600 : 600;
  const barHeight = size === 'large' ? 124 : size === 'medium' ? 88 : 56;

  return (
    <div style={{
      background: bg,
      color: fg,
      borderBottom: border,
      display: 'flex', flexDirection: 'column', flexShrink: 0,
    }}>
      <div style={{
        height: 56,
        display: 'flex', alignItems: 'center',
        padding: '0 4px',
        gap: 4,
      }}>
        {onLeading !== undefined && (
          <IconButton onClick={onLeading} color={fg}><Icon size={22}/></IconButton>
        )}
        {size === 'small' && (
          <div style={{
            flex: 1,
            fontSize: 18, fontWeight: 600, letterSpacing: '-0.005em',
            textAlign: centered ? 'center' : 'left',
            paddingLeft: onLeading ? (centered ? 0 : 4) : 16,
            paddingRight: centered ? 0 : 0,
          }}>{title}</div>
        )}
        {size !== 'small' && <div style={{ flex: 1 }}/>}
        <div style={{ display: 'flex', alignItems: 'center', gap: 0 }}>
          {trailing.map((t, i) => (
            <IconButton key={i} onClick={t.onClick} color={fg}>
              <t.icon size={22}/>
              {t.badge ? <span style={{
                position: 'absolute', top: 6, right: 6,
                background: 'var(--red-9)', color: 'white',
                fontSize: 9, fontWeight: 700,
                minWidth: 14, height: 14, padding: '0 3px',
                borderRadius: 99,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                lineHeight: 1,
              }}>{t.badge}</span> : null}
            </IconButton>
          ))}
        </div>
      </div>
      {(size === 'medium' || size === 'large') && (
        <div style={{
          padding: '4px 16px 16px',
          fontSize: titleSize, fontWeight: titleWeight,
          letterSpacing: '-0.015em', lineHeight: 1.15,
        }}>{title}</div>
      )}
    </div>
  );
}

function IconButton({ children, onClick, color = 'currentColor', size = 40 }) {
  const [pressed, setPressed] = useState(false);
  return (
    <button
      onClick={onClick}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
      onMouseLeave={() => setPressed(false)}
      style={{
        width: size, height: size,
        margin: 4,
        border: 0, background: pressed ? 'rgba(255,255,255,0.18)' : 'transparent',
        borderRadius: '50%',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        color, cursor: 'pointer',
        position: 'relative',
        transition: 'background 120ms var(--ease-in)',
      }}>
      {children}
    </button>
  );
}

// Bottom gesture nav (the pill)
function TBNavBar({ tone = 'light', bg }) {
  const pillColor = tone === 'light' ? '#1e1f24' : '#ffffff';
  return (
    <div style={{
      height: 22, flexShrink: 0,
      background: bg || 'transparent',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div style={{
        width: 108, height: 4, borderRadius: 2,
        background: pillColor, opacity: 0.85,
      }}/>
    </div>
  );
}

// The phone frame itself.
function TBPhone({
  width = 360,           // device viewport width (Pixel-class ~ 360-412dp)
  height = 760,          // viewport height
  scale = 1,
  appBar,                // <TBAppBar/> element OR null
  statusBarTone,         // 'light' | 'dark' | 'primary' (auto if appBar variant=primary)
  navBarTone,            // 'light' | 'dark'
  surface,               // body background override
  children,
  label,                 // small label rendered underneath
  bezel = true,
}) {
  // theme detection: read data-theme on the document root for tone defaults
  const dark = typeof document !== 'undefined' && document.documentElement.getAttribute('data-theme') === 'dark';
  const sbTone = statusBarTone || (appBar?.props?.variant === 'primary' ? 'dark' : (dark ? 'dark' : 'light'));
  const nbTone = navBarTone || (dark ? 'dark' : 'light');
  const sbBg = appBar?.props?.variant === 'primary' ? 'var(--tb-primary)' : (surface || 'var(--tb-surface)');
  const bodyBg = surface || (dark ? 'var(--tb-surface-1)' : 'var(--tb-surface-1)');

  const w = width, h = height;
  const containerW = w * scale + (bezel ? 16 : 0);
  const containerH = h * scale + (bezel ? 16 : 0) + (label ? 28 : 0);

  return (
    <div style={{
      width: containerW, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
    }}>
      <div style={{
        width: w * scale, height: h * scale,
        position: 'relative',
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          transform: `scale(${scale})`, transformOrigin: 'top left',
          width: w, height: h,
          borderRadius: bezel ? 36 : 0,
          background: bodyBg,
          border: bezel ? '8px solid #0c0d10' : 'none',
          boxShadow: bezel ? '0 30px 70px rgba(13,18,30,0.18), 0 8px 18px rgba(13,18,30,0.10)' : 'none',
          overflow: 'hidden',
          display: 'flex', flexDirection: 'column',
          fontFamily: 'var(--font-sans)',
        }}>
          {/* status bar */}
          <div style={{ background: sbBg }}>
            <TBStatusBar tone={sbTone}/>
          </div>
          {/* app bar (optional) */}
          {appBar}
          {/* content body */}
          <div style={{ flex: 1, overflow: 'auto', background: bodyBg, position: 'relative' }}>
            {children}
          </div>
          {/* gesture nav */}
          <TBNavBar tone={nbTone}/>
        </div>
      </div>
      {label && (
        <div style={{
          fontSize: 12, fontWeight: 500, color: 'var(--slate-11)',
          letterSpacing: '0.01em',
        }}>{label}</div>
      )}
    </div>
  );
}

Object.assign(window, { TBPhone, TBAppBar, TBStatusBar, TBNavBar, IconButton });
