/* global React */
// ui.jsx — shared primitives for the CamBam Fantasy prototype.

// Color helpers (so we don't pull in CSS-in-JS)
const C = {
  bg: '#0a0a0a',
  surface: '#141414',
  surface2: '#1c1c1c',
  hairline: '#262626',
  text: '#f5f5f4',
  text2: '#a3a3a3',
  text3: '#525252',
  emerald: '#1f8a5b',
  emeraldMute: '#0c3d28',
  amber: '#f59e0b',
  red: '#ef4444',
};

// ─── Screen scaffold ────────────────────────────────────────────────
// In canvas mode: fixed iPhone 15 Pro frame (393 × 852) for the showcase.
// In app mode (window.APP_MODE === true): fills its container — the app
// shell decides whether that's a full-viewport mobile column or a
// phone-shaped centered column on desktop.
// `bottomNav`: which nav tab to highlight (or null to hide).
function Screen({ children, bottomNav = null, statusBarTime = '9:41', scroll = true, label }) {
  const appMode = typeof window !== 'undefined' && window.APP_MODE === true;
  const frame = appMode
    ? { width: '100%', height: '100%' }
    : { width: 393, height: 852 };
  return (
    <div data-screen-label={label} style={{
      ...frame,
      background: C.bg, color: C.text,
      fontFamily: "'Inter', -apple-system, system-ui, sans-serif",
      WebkitFontSmoothing: 'antialiased',
      position: 'relative', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
    }}>
      {!appMode && <StatusBar time={statusBarTime} />}
      <div style={{
        flex: 1, overflow: scroll ? 'auto' : 'hidden', position: 'relative',
        paddingBottom: bottomNav !== null
          ? (appMode ? 'calc(72px + env(safe-area-inset-bottom))' : 90)
          : 0,
      }}>
        {children}
      </div>
      {bottomNav !== null && <BottomNav active={bottomNav} />}
      {!appMode && <HomeIndicator />}
    </div>
  );
}

function StatusBar({ time = '9:41' }) {
  return (
    <div style={{
      height: 54, paddingTop: 18,
      display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
      padding: '18px 32px 0', flexShrink: 0,
      position: 'relative', zIndex: 10,
    }}>
      <div style={{ font: '600 17px/22px Inter', color: C.text, fontFeatureSettings: '"tnum"' }}>{time}</div>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center', paddingTop: 1 }}>
        <svg width="18" height="11" viewBox="0 0 18 11"><rect x="0" y="6" width="3" height="5" rx="0.6" fill={C.text}/><rect x="5" y="4" width="3" height="7" rx="0.6" fill={C.text}/><rect x="10" y="2" width="3" height="9" rx="0.6" fill={C.text}/><rect x="15" y="0" width="3" height="11" rx="0.6" fill={C.text}/></svg>
        <svg width="16" height="11" viewBox="0 0 17 12"><path d="M8.5 3.2C10.8 3.2 12.9 4.1 14.4 5.6L15.5 4.5C13.7 2.7 11.2 1.5 8.5 1.5C5.8 1.5 3.3 2.7 1.5 4.5L2.6 5.6C4.1 4.1 6.2 3.2 8.5 3.2Z" fill={C.text}/><path d="M8.5 6.8C9.9 6.8 11.1 7.3 12 8.2L13.1 7.1C11.8 5.9 10.2 5.1 8.5 5.1C6.8 5.1 5.2 5.9 3.9 7.1L5 8.2C5.9 7.3 7.1 6.8 8.5 6.8Z" fill={C.text}/><circle cx="8.5" cy="10.5" r="1.5" fill={C.text}/></svg>
        <svg width="25" height="12" viewBox="0 0 27 13"><rect x="0.5" y="0.5" width="23" height="12" rx="3.5" stroke={C.text} strokeOpacity="0.4" fill="none"/><rect x="2" y="2" width="20" height="9" rx="2" fill={C.text}/><path d="M25 4.5V8.5C25.8 8.2 26.5 7.2 26.5 6.5C26.5 5.8 25.8 4.8 25 4.5Z" fill={C.text} fillOpacity="0.4"/></svg>
      </div>
    </div>
  );
}

function HomeIndicator() {
  return (
    <div style={{
      position: 'absolute', bottom: 8, left: 0, right: 0,
      display: 'flex', justifyContent: 'center', zIndex: 100, pointerEvents: 'none',
    }}>
      <div style={{ width: 134, height: 5, borderRadius: 100, background: 'rgba(255,255,255,0.5)' }} />
    </div>
  );
}

// ─── App Header (spec component 1) ──────────────────────────────────
function Header({ title, subtitle, onBack, right, dense = false }) {
  // Default right-slot = settings gear (one-tap to settings from any page).
  // Read window.appNav at click time so initial-render closures stay live.
  const rightSlot = right !== undefined ? right : (
    <button
      aria-label="Settings"
      onClick={() => { const n = window.appNav; if (n) n.openSheet('settings'); }}
      style={iconBtn40()}
    >
      <Gear size={20} />
    </button>
  );
  return (
    <div style={{
      height: 56, padding: '0 8px',
      display: 'grid', gridTemplateColumns: '40px 1fr 40px',
      alignItems: 'center', flexShrink: 0,
    }}>
      <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
        {onBack !== undefined && (
          <button
            onClick={() => {
              if (typeof onBack === 'function') onBack();
              else { const n = window.appNav; if (n) n.back(); }
            }}
            style={iconBtn40()}
            aria-label="Back"
          >
            <Chevron size={18} stroke={2} />
          </button>
        )}
      </div>
      <div style={{ textAlign: 'center', overflow: 'hidden' }}>
        <div style={{ font: `600 ${dense ? 16 : 17}px/22px Inter`, color: C.text }}>{title}</div>
        {subtitle && <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 1 }}>{subtitle}</div>}
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        {rightSlot}
      </div>
    </div>
  );
}

const iconBtn40 = () => ({
  width: 40, height: 40, borderRadius: 999,
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  background: 'transparent', border: 'none', color: C.text2, cursor: 'pointer',
});

// ─── Avatar (initials chip — no real photos in prototype) ───────────
const AVATAR_COLORS = [
  ['#1c1c1c', '#a3a3a3'], // default
  ['#1f2937', '#f5f5f4'], ['#0c3d28', '#1f8a5b'],
  ['#3f2d18', '#f59e0b'], ['#3a1b1b', '#ef4444'],
  ['#1c1c1c', '#a3a3a3'], ['#2a2a2a', '#f5f5f4'],
];
function Avatar({ name = '?', size = 40, tone = 0, ring = false, champion = false }) {
  const [bg, fg] = AVATAR_COLORS[tone % AVATAR_COLORS.length];
  const init = name.split(/\s+/).map(p => p[0]).join('').slice(0, 2).toUpperCase();
  // Champion = "green jacket" badge: pine ring + tiny lapel mark.
  const shadow = champion
    ? `0 0 0 2px ${C.bg}, 0 0 0 3.5px ${C.emerald}, 0 0 0 5px ${C.emeraldMute}`
    : ring
      ? `0 0 0 2px ${C.bg}, 0 0 0 3.5px ${C.emerald}`
      : 'none';
  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <div style={{
        width: size, height: size, borderRadius: '50%',
        background: bg, color: fg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        font: `600 ${Math.round(size * 0.36)}px/1 Inter`,
        letterSpacing: 0.2,
        boxShadow: shadow,
      }}>{init}</div>
      {champion && (
        <span title="Green jacket — 2024 Champion" style={{
          position: 'absolute', right: -2, bottom: -2,
          width: Math.max(14, Math.round(size * 0.36)),
          height: Math.max(14, Math.round(size * 0.36)),
          borderRadius: '50%',
          background: C.emerald, color: '#0a0a0a',
          boxShadow: `0 0 0 2px ${C.bg}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          font: `700 ${Math.max(8, Math.round(size * 0.18))}px/1 Inter`,
          letterSpacing: 0,
        }}>★</span>
      )}
    </div>
  );
}

// ─── Status pills (spec component 13) ───────────────────────────────
function Pill({ kind = 'live', children, leadingDot = false }) {
  const styles = {
    live:     { bg: 'rgba(31, 138, 91,0.15)', fg: C.emerald },
    finished: { bg: C.surface2,              fg: C.text2 },
    mc:       { bg: 'rgba(239,68,68,0.15)',  fg: C.red },
    paid:     { bg: C.emeraldMute,           fg: C.emerald },
    unpaid:   { bg: 'rgba(245,158,11,0.15)', fg: C.amber },
    wd:       { bg: 'rgba(245,158,11,0.15)', fg: C.amber },
    neutral:  { bg: C.surface2,              fg: C.text2 },
  };
  const s = styles[kind] || styles.neutral;
  return (
    <span style={{
      height: 22, display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '0 8px', borderRadius: 999, background: s.bg, color: s.fg,
      font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
    }}>
      {leadingDot && (
        <span className={kind === 'live' ? 'live-pulse' : ''} style={{
          width: 6, height: 6, borderRadius: 999, background: s.fg, flexShrink: 0,
        }} />
      )}
      {kind === 'paid' && <Check size={11} />}
      {children}
    </span>
  );
}

// ─── Tabs (spec component 2) ────────────────────────────────────────
function Tabs({ items, active, onChange }) {
  const idx = items.indexOf(active);
  return (
    <div style={{ position: 'relative' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: `repeat(${items.length}, 1fr)`,
        borderBottom: `1px solid ${C.hairline}`,
      }}>
        {items.map(t => (
          <button key={t} onClick={() => onChange && onChange(t)} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            padding: '14px 0', minHeight: 56,
            color: t === active ? C.text : C.text2,
            font: '600 18px/24px Inter',
          }}>{t}</button>
        ))}
      </div>
      <div style={{
        position: 'absolute', bottom: 0, height: 2, background: C.emerald,
        width: `${100 / items.length}%`, left: `${(idx * 100) / items.length}%`,
        transition: 'left 200ms ease-out',
      }} />
    </div>
  );
}

// ─── Segmented control (spec component 4) ───────────────────────────
function Segmented({ items, active, onChange, size = 'md' }) {
  const pad = size === 'sm' ? 4 : 4;
  const h = size === 'sm' ? 36 : 44;
  return (
    <div style={{
      background: C.surface2, borderRadius: 999, padding: pad,
      display: 'grid', gridTemplateColumns: `repeat(${items.length}, 1fr)`,
      gap: 4, position: 'relative', height: h,
    }}>
      {items.map(t => {
        const on = t === active;
        return (
          <button key={t} onClick={() => onChange && onChange(t)} style={{
            background: on ? C.surface : 'transparent',
            border: 'none', borderRadius: 999, cursor: 'pointer',
            color: on ? C.text : C.text2,
            font: `${size === 'sm' ? 500 : 600} ${size === 'sm' ? 13 : 14}px/1 Inter`,
            position: 'relative', overflow: 'hidden',
            transition: 'background 180ms ease-out, color 180ms ease-out',
          }}>
            {on && (
              <span style={{
                position: 'absolute', top: 0, left: '20%', right: '20%', height: 1.5,
                background: C.emerald, borderRadius: 999,
              }} />
            )}
            {t}
          </button>
        );
      })}
    </div>
  );
}

// ─── iOS Toggle (spec component 6) ──────────────────────────────────
function Toggle({ on, onChange }) {
  return (
    <button onClick={() => onChange && onChange(!on)} style={{
      width: 51, height: 31, borderRadius: 999, border: 'none', padding: 0,
      background: on ? C.emerald : C.surface2,
      position: 'relative', cursor: 'pointer',
      transition: 'background 200ms ease-out',
    }}>
      <span style={{
        position: 'absolute', top: 2, left: on ? 22 : 2,
        width: 27, height: 27, borderRadius: 999, background: '#fff',
        transition: 'left 200ms ease-out',
        boxShadow: '0 1px 2px rgba(0,0,0,0.4)',
      }} />
    </button>
  );
}

// ─── Bottom Nav (spec component 15) ─────────────────────────────────
// Sports-forward: scoreboard / golf-flag / podium / jersey, with short labels.
const NAV_ROUTES = {
  home: 'home',
  pools: 'pools/lineup',
  standings: 'pools/standings',
  stats: 'stats',
};
function BottomNav({ active = 'home' }) {
  const appMode = typeof window !== 'undefined' && window.APP_MODE === true;
  const items = [
    { id: 'home',      label: 'Home',     Icon: NavHome },
    { id: 'pools',     label: 'Pools',    Icon: NavPool },
    { id: 'standings', label: 'Board',    Icon: NavStandings },
    { id: 'stats',     label: 'Stats',    Icon: NavProfile },
  ];
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0,
      background: `${C.bg}f2`,
      backdropFilter: 'blur(20px)',
      borderTop: `1px solid ${C.hairline}`,
      paddingBottom: appMode ? 'max(8px, env(safe-area-inset-bottom))' : 24,
      paddingTop: 4,
      height: appMode ? 72 : 90,
      display: 'flex', justifyContent: 'space-around', alignItems: 'center',
      zIndex: 90,
    }}>
      {items.map(({ id, label, Icon }) => {
        const on = id === active;
        // Read window.appNav at click time — initial render may run before App's useEffect.
        const onClick = () => {
          const n = window.appNav;
          if (!n) return;
          n.go(NAV_ROUTES[id] || id);
        };
        return (
          <button key={id} aria-label={id} onClick={onClick} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            width: 72, height: 60, padding: '6px 0 0',
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start', gap: 3,
            color: on ? C.emerald : C.text2,
            position: 'relative',
          }}>
            <span style={{
              width: 48, height: 30, borderRadius: 999,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              background: on ? 'rgba(31, 138, 91, 0.14)' : 'transparent',
              transition: 'background 180ms ease-out',
            }}>
              <Icon size={22} active={on} />
            </span>
            <span style={{
              font: `${on ? 600 : 500} 10px/12px Inter`,
              letterSpacing: 0.04 * 10, textTransform: 'uppercase',
              color: on ? C.emerald : C.text2,
            }}>{label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ─── Roster row (spec component 5) ──────────────────────────────────
function RosterRow({ name, country, price, points, live, dim, position = 'G', tone = 1, status, swoosh, onClick }) {
  const handleClick = onClick || (() => { const n = window.appNav; if (n) n.openSheet('golfer-detail'); });
  return (
    <div
      role="button" tabIndex={0}
      onClick={handleClick}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') handleClick(); }}
      style={{
        height: 64, display: 'flex', alignItems: 'center', gap: 12,
        padding: '0 16px', position: 'relative',
        opacity: dim ? 0.3 : 1, transition: 'opacity 200ms ease-out',
        background: 'transparent',
        cursor: 'pointer',
      }}>
      <div style={{ position: 'relative' }}>
        <Avatar name={name} size={40} tone={tone} />
        <span style={{
          position: 'absolute', bottom: -3, left: '50%', transform: 'translateX(-50%)',
          font: '700 9px/1 Inter', color: C.text3, background: C.bg,
          padding: '1px 4px', borderRadius: 4,
        }}>{position}</span>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '600 16px/22px Inter', color: C.text,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</div>
        <div style={{ font: '400 13px/18px Inter', color: C.text2, marginTop: 1,
          display: 'flex', alignItems: 'center', gap: 6 }}>
          <span>{country}</span>
          {status && <><span style={{ color: C.text3 }}>·</span><span style={{ color: live ? C.emerald : C.text2 }}>{status}</span></>}
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className="tnum" style={{ font: '500 13px/18px Inter', color: C.text2 }}>${price}</div>
        <div className={'tnum' + (swoosh ? ' swoosh-pulse' : '')} style={{ font: '600 17px/22px Inter', color: C.text, marginTop: 2 }}>{points.toFixed(1)}</div>
      </div>
      {live && (
        <div className="live-pulse" style={{
          position: 'absolute', right: 0, top: 8, bottom: 8, width: 3,
          background: C.emerald, borderRadius: 2,
        }} />
      )}
    </div>
  );
}

// ─── Empty roster slot ──────────────────────────────────────────────
function EmptyRosterSlot({ position = 'G' }) {
  return (
    <div style={{
      height: 64, margin: '0 16px',
      border: `1px dashed ${C.hairline}`, borderRadius: 12,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: C.text2,
      font: 'italic 400 16px/24px Inter',
      gap: 8,
    }}>
      <Plus size={16} />
      <span>Empty {position} slot</span>
    </div>
  );
}

// ─── Primary CTA button ─────────────────────────────────────────────
function CTA({ children, disabled, kind = 'primary', size = 'lg', onClick, full = true, type = 'button' }) {
  const palette = {
    primary:   { bg: C.emerald,   fg: '#0a0a0a' },
    secondary: { bg: C.surface,   fg: C.text },
    ghost:     { bg: 'transparent', fg: C.emerald },
  };
  const p = palette[kind];
  const h = size === 'lg' ? 56 : size === 'md' ? 44 : 36;
  return (
    <button onClick={onClick} disabled={disabled} type={type} style={{
      height: h, width: full ? '100%' : 'auto', padding: '0 20px',
      background: disabled ? C.surface : p.bg,
      color: disabled ? C.text3 : p.fg,
      border: kind === 'ghost' ? `1px solid ${C.hairline}` : 'none',
      borderRadius: 8, cursor: disabled ? 'not-allowed' : 'pointer',
      font: '600 16px/1 Inter',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    }}>{children}</button>
  );
}

// ─── Progress bar ───────────────────────────────────────────────────
function Progress({ value = 0.5, color = C.emerald, height = 2 }) {
  return (
    <div style={{
      width: '100%', height, background: C.surface2, borderRadius: 999, overflow: 'hidden',
    }}>
      <div style={{ width: `${Math.max(0, Math.min(1, value)) * 100}%`, height: '100%', background: color }} />
    </div>
  );
}

Object.assign(window, {
  C, Screen, StatusBar, HomeIndicator, Header, Avatar, Pill,
  Tabs, Segmented, Toggle, BottomNav, RosterRow, EmptyRosterSlot, CTA, Progress,
});
