// Shared UI primitives for the ByDuty Guard prototype.
// Uses window.BD_TOKENS, window.Icon, window.BDLogo.

const T = () => window.__BD_THEME__ || window.BD_TOKENS.dark;

// ────────────────────────────────────────────────────────────
// Phone frame — 390 × 844 (iPhone 14/15 base)
// ────────────────────────────────────────────────────────────
function PhoneFrame({ children, dark = true, label, w = 390, h = 844, bg }) {
  const t = dark ? window.BD_TOKENS.dark : window.BD_TOKENS.light;
  return (
    <div style={{
      width: w + 16, padding: 8, boxSizing: 'content-box',
      borderRadius: 56, background: dark ? '#04060E' : '#D7DCE8',
      boxShadow: dark
        ? '0 30px 60px rgba(0,0,0,0.45), 0 0 0 1px rgba(255,255,255,0.06), inset 0 0 0 1px rgba(255,255,255,0.04)'
        : '0 30px 60px rgba(15,23,42,0.18), 0 0 0 1px rgba(15,23,42,0.10)',
    }}>
      <div style={{
        width: w, height: h, borderRadius: 48, overflow: 'hidden', position: 'relative',
        background: bg || t.bg, color: t.text,
        fontFamily: window.BD_FONT,
      }}>
        {/* dynamic island */}
        <div style={{
          position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)',
          width: 120, height: 34, borderRadius: 22, background: '#000', zIndex: 60,
        }} />
        {/* status bar */}
        <StatusBar dark={dark} />
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column' }}>
          {children}
        </div>
        {/* home indicator */}
        <div style={{
          position: 'absolute', bottom: 8, left: 0, right: 0,
          display: 'flex', justifyContent: 'center', zIndex: 70, pointerEvents: 'none',
        }}>
          <div style={{
            width: 134, height: 5, borderRadius: 999,
            background: dark ? 'rgba(255,255,255,0.55)' : 'rgba(0,0,0,0.35)',
          }} />
        </div>
      </div>
      {label && (
        <div style={{
          marginTop: 14, textAlign: 'center', color: dark ? '#cbd5e1' : '#334155',
          fontFamily: window.BD_FONT, fontSize: 13, fontWeight: 600, letterSpacing: 0.2,
        }}>{label}</div>
      )}
    </div>
  );
}

function StatusBar({ dark = true, time = '9:41' }) {
  const c = dark ? '#fff' : '#000';
  return (
    <div style={{
      position: 'absolute', top: 0, left: 0, right: 0, height: 50, zIndex: 55,
      display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
      padding: '17px 28px 0', pointerEvents: 'none',
    }}>
      <div style={{ fontSize: 15.5, fontWeight: 600, color: c, letterSpacing: 0.1 }}>{time}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: c }}>
        <window.Icon.Signal size={16} sw={2} stroke={c}/>
        <window.Icon.Wifi size={16} sw={2} stroke={c}/>
        <window.Icon.Battery size={22} sw={2} stroke={c}/>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Card / surface
// ────────────────────────────────────────────────────────────
function Card({ children, style, t = T(), pad = 14, hi = false }) {
  return (
    <div style={{
      background: hi ? t.surface2 : t.surface,
      borderRadius: window.BD_RADII.lg,
      border: `1px solid ${t.line}`,
      padding: pad,
      ...style,
    }}>{children}</div>
  );
}

// Status / category pill
function Pill({ tone = 'primary', children, t = T(), size = 'md', style }) {
  const map = {
    primary: [t.primary, t.primarySoft],
    gold: [t.gold, t.goldSoft],
    success: [t.success, t.successSoft],
    warn: [t.warn, t.warnSoft],
    danger: [t.danger, t.dangerSoft],
    purple: [t.purple, t.purpleSoft],
    teal: [t.teal, t.tealSoft],
    pink: [t.pink, t.pinkSoft],
    muted: [t.text3, t.line],
  };
  const [fg, bg] = map[tone] || map.primary;
  const sm = size === 'sm';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: sm ? '3px 8px' : '5px 10px',
      borderRadius: 999, background: bg, color: fg,
      fontSize: sm ? 10.5 : 11.5, fontWeight: 700, letterSpacing: 0.4,
      textTransform: 'uppercase',
      ...style,
    }}>{children}</span>
  );
}

// Section header
function SectionLabel({ children, action, t = T(), style }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '0 4px', ...style }}>
      <div style={{ fontSize: 13, fontWeight: 700, color: t.text2, letterSpacing: 0.6, textTransform: 'uppercase' }}>{children}</div>
      {action && <div style={{ fontSize: 12.5, fontWeight: 600, color: t.primary }}>{action}</div>}
    </div>
  );
}

// Quick action tile (colored)
function ActionTile({ icon, label, tone = 'primary', t = T(), badge, big = false, onClick }) {
  const [fg, bg] = {
    primary: [t.primary, t.primarySoft],
    gold: [t.gold, t.goldSoft],
    success: [t.success, t.successSoft],
    warn: [t.warn, t.warnSoft],
    danger: [t.danger, t.dangerSoft],
    purple: [t.purple, t.purpleSoft],
    teal: [t.teal, t.tealSoft],
    pink: [t.pink, t.pinkSoft],
  }[tone];
  return (
    <button onClick={onClick} style={{
      flex: 1, position: 'relative', appearance: 'none', cursor: 'pointer', textAlign: 'left',
      background: bg, border: `1px solid ${t.line}`, borderRadius: 16,
      padding: big ? '16px 14px' : '14px 12px', minHeight: big ? 100 : 88,
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 16,
      color: t.text,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 12, background: fg + '22',
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: fg,
      }}>{icon}</div>
      <div style={{ fontSize: 13.5, fontWeight: 700, color: t.text, letterSpacing: 0.2 }}>{label}</div>
      {badge != null && (
        <span style={{
          position: 'absolute', top: 10, right: 10,
          minWidth: 20, height: 20, padding: '0 6px', borderRadius: 999,
          background: t.danger, color: '#fff', fontSize: 11, fontWeight: 700,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{badge}</span>
      )}
    </button>
  );
}

// Primary button
function Button({ children, tone = 'primary', t = T(), icon, full, size = 'md', onClick, style }) {
  const styles = {
    primary: { bg: t.primary, fg: '#fff', border: 'transparent' },
    danger:  { bg: t.danger,  fg: '#fff', border: 'transparent' },
    success: { bg: t.success, fg: '#fff', border: 'transparent' },
    ghost:   { bg: 'transparent', fg: t.text, border: t.lineStrong },
    soft:    { bg: t.primarySoft, fg: t.primary, border: 'transparent' },
  }[tone];
  return (
    <button onClick={onClick} style={{
      appearance: 'none', cursor: 'pointer',
      background: styles.bg, color: styles.fg,
      border: `1px solid ${styles.border}`, borderRadius: 14,
      padding: size === 'lg' ? '14px 18px' : '11px 16px',
      fontSize: size === 'lg' ? 16 : 14.5, fontWeight: 700, letterSpacing: 0.2,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      width: full ? '100%' : 'auto',
      fontFamily: window.BD_FONT,
      ...style,
    }}>
      {icon}{children}
    </button>
  );
}

// Bottom nav (5 items, center scan FAB)
function BottomNav({ active = 'home', t = T(), onChange }) {
  const items = [
    { k: 'home', label: 'Home', icon: window.Icon.Home },
    { k: 'patrol', label: 'Patrol', icon: window.Icon.Shield },
    { k: 'scan', label: 'Scan', icon: window.Icon.Scan, fab: true },
    { k: 'reports', label: 'Reports', icon: window.Icon.Doc },
    { k: 'more', label: 'More', icon: window.Icon.More },
  ];
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 50,
      paddingBottom: 14, paddingTop: 10, paddingLeft: 12, paddingRight: 12,
      background: t.bg2 + 'EE',
      borderTop: `1px solid ${t.line}`,
      backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center', gap: 'clamp(20px, 6vw, 80px)',
    }}>
      {items.map(it => {
        const isActive = active === it.k;
        if (it.fab) {
          return (
            <button key={it.k} onClick={() => onChange?.(it.k)} style={{
              appearance: 'none', cursor: 'pointer', border: 'none',
              width: 56, height: 56, borderRadius: 999,
              background: `linear-gradient(180deg, ${t.primaryHi}, ${t.primary})`,
              boxShadow: `0 10px 24px ${t.primary}66, 0 0 0 6px ${t.bg2}`,
              color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
              transform: 'translateY(-14px)',
            }}>
              <it.icon size={24} sw={2}/>
            </button>
          );
        }
        return (
          <button key={it.k} onClick={() => onChange?.(it.k)} style={{
            appearance: 'none', cursor: 'pointer', border: 'none', background: 'transparent',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            color: isActive ? t.primary : t.text3, padding: '4px 8px',
          }}>
            <it.icon size={22} sw={isActive ? 2 : 1.7}/>
            <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: 0.3 }}>{it.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// Top app bar with logo, optional back, title, bell
function AppBar({ title, back, bell = true, badge = 3, right, t = T() }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '20px 24px 14px', gap: 12,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
        {back ? (
          <button style={{
            appearance: 'none', border: `1px solid ${t.line}`, background: t.surface,
            width: 36, height: 36, borderRadius: 12, display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: t.text, cursor: 'pointer',
          }}><window.Icon.ArrowL size={18} sw={2}/></button>
        ) : (
          <window.BDLogo size={32}/>
        )}
        {title ? (
          <div style={{ fontSize: 17, fontWeight: 700, color: t.text }}>{title}</div>
        ) : (
          <div style={{ fontSize: 17, fontWeight: 800, letterSpacing: 0.2, color: t.text }}>ByDuty</div>
        )}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {right}
        {bell && (
          <div style={{ position: 'relative' }}>
            <button style={{
              appearance: 'none', border: `1px solid ${t.line}`, background: t.surface,
              width: 36, height: 36, borderRadius: 12, display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: t.text, cursor: 'pointer',
            }}>
              <window.Icon.Bell size={18} sw={2}/>
            </button>
            {!!badge && (
              <span style={{
                position: 'absolute', top: -4, right: -4,
                minWidth: 18, height: 18, padding: '0 5px', borderRadius: 999,
                background: t.danger, color: '#fff', fontSize: 10.5, fontWeight: 700,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                border: `2px solid ${t.bg}`,
              }}>{badge}</span>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// Avatar
function Avatar({ size = 40, name = 'JS', tone = 'primary', t = T(), online }) {
  const fg = t[tone] || t.primary;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <div style={{
        width: size, height: size, borderRadius: 999,
        background: `linear-gradient(135deg, ${fg}, ${t.purple})`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: '#fff', fontWeight: 700, fontSize: size * 0.38,
        border: `2px solid ${t.surface}`,
      }}>{name}</div>
      {online && (
        <span style={{
          position: 'absolute', bottom: 0, right: 0, width: size * 0.28, height: size * 0.28,
          borderRadius: 999, background: t.success, border: `2px solid ${t.surface}`,
        }}/>
      )}
    </div>
  );
}

// Scrollable content area (pad bottom for bottom nav)
function Screen({ children, t = T(), bottomPad = 110, scroll = true, style, maxWidth = 720 }) {
  return (
    <div style={{
      flex: 1, overflow: scroll ? 'auto' : 'hidden',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        width: '100%', maxWidth, margin: '0 auto',
        padding: '0 24px',
        paddingBottom: bottomPad,
        display: 'flex', flexDirection: 'column', gap: 14,
        ...style,
      }}>{children}</div>
    </div>
  );
}

Object.assign(window, {
  PhoneFrame, StatusBar, Card, Pill, SectionLabel, ActionTile, Button, BottomNav, AppBar, Avatar, Screen,
});
