// Reel — shared tokens, icons, components, helpers

const REEL_TOKENS = {
  bg: '#0a0a0a',
  surface: '#141414',
  surface2: '#1c1c1c',
  surface3: '#262626',
  border: 'rgba(255,255,255,0.08)',
  borderStrong: 'rgba(255,255,255,0.14)',
  text: '#fafafa',
  textDim: '#a1a1a1',
  textMuted: '#6b6b6b',
  accent: '#f59e0b',
  accentSoft: 'rgba(245,158,11,0.16)',
  red: '#ef4444',
  green: '#22c55e',
  sans: '"Manrope", system-ui, -apple-system, sans-serif',
  mono: '"JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace',
};

// Empty arrays — populated per-video by player
window.REEL_SUBTITLES = [];
window.REEL_CHAPTERS  = [];
window.REEL_BOOKMARKS = [];
window.REEL_FAV_SCENES = [];

function fmt(secs) {
  const s = Math.max(0, Math.floor(secs));
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const ss = s % 60;
  const pad = n => String(n).padStart(2, '0');
  return h > 0 ? `${h}:${pad(m)}:${pad(ss)}` : `${m}:${pad(ss)}`;
}

function accentSoftColor(hex) {
  // Parse hex to rgba with 0.16 opacity
  const r = parseInt(hex.slice(1,3),16);
  const g = parseInt(hex.slice(3,5),16);
  const b = parseInt(hex.slice(5,7),16);
  return `rgba(${r},${g},${b},0.16)`;
}

function Icon({ name, size = 22, color = 'currentColor', strokeWidth = 1.7, style, text }) {
  const s = { width: size, height: size, display: 'inline-block', flexShrink: 0, ...style };
  const c = { fill: 'none', stroke: color, strokeWidth, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const skipText = text != null ? String(text) : null;
  switch (name) {
    case 'play':         return <svg viewBox="0 0 24 24" style={s}><path d="M7 5v14l12-7z" fill={color} stroke="none"/></svg>;
    case 'play-line':    return <svg viewBox="0 0 24 24" style={s}><path d="M7 5v14l12-7z" {...c}/></svg>;
    case 'pause':        return <svg viewBox="0 0 24 24" style={s}><rect x="6" y="5" width="4" height="14" rx="1" fill={color}/><rect x="14" y="5" width="4" height="14" rx="1" fill={color}/></svg>;
    case 'next':         return <svg viewBox="0 0 24 24" style={s}><path d="M5 5v14l11-7z" fill={color} stroke="none"/><rect x="17" y="5" width="2" height="14" rx="1" fill={color}/></svg>;
    case 'prev':         return <svg viewBox="0 0 24 24" style={s} transform="scale(-1,1)"><path d="M5 5v14l11-7z" fill={color} stroke="none"/><rect x="17" y="5" width="2" height="14" rx="1" fill={color}/></svg>;
    case 'fwd10':        return <svg viewBox="0 0 24 24" style={s}><path d="M12 5a7 7 0 1 1-6.93 8" {...c}/><path d="M12 2l3 3-3 3" {...c}/><text x="12" y="16" fontSize={skipText && skipText.length>2?6:7} fontFamily="ui-monospace,monospace" fontWeight="700" fill={color} textAnchor="middle" stroke="none">{skipText||'10'}</text></svg>;
    case 'back10':       return <svg viewBox="0 0 24 24" style={s}><path d="M12 5a7 7 0 1 0 6.93 8" {...c}/><path d="M12 2L9 5l3 3" {...c}/><text x="12" y="16" fontSize={skipText && skipText.length>2?6:7} fontFamily="ui-monospace,monospace" fontWeight="700" fill={color} textAnchor="middle" stroke="none">{skipText||'10'}</text></svg>;
    case 'search':       return <svg viewBox="0 0 24 24" style={s}><circle cx="11" cy="11" r="6" {...c}/><path d="M16 16l4 4" {...c}/></svg>;
    case 'menu':         return <svg viewBox="0 0 24 24" style={s}><path d="M4 7h16M4 12h16M4 17h16" {...c}/></svg>;
    case 'close':        return <svg viewBox="0 0 24 24" style={s}><path d="M6 6l12 12M18 6L6 18" {...c}/></svg>;
    case 'back':         return <svg viewBox="0 0 24 24" style={s}><path d="M14 6l-6 6 6 6" {...c}/></svg>;
    case 'more':         return <svg viewBox="0 0 24 24" style={s}><circle cx="12" cy="5" r="1.5" fill={color}/><circle cx="12" cy="12" r="1.5" fill={color}/><circle cx="12" cy="19" r="1.5" fill={color}/></svg>;
    case 'more-h':       return <svg viewBox="0 0 24 24" style={s}><circle cx="5" cy="12" r="1.5" fill={color}/><circle cx="12" cy="12" r="1.5" fill={color}/><circle cx="19" cy="12" r="1.5" fill={color}/></svg>;
    case 'folder':       return <svg viewBox="0 0 24 24" style={s}><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z" {...c}/></svg>;
    case 'film':         return <svg viewBox="0 0 24 24" style={s}><rect x="3" y="4" width="18" height="16" rx="2" {...c}/><path d="M3 9h18M3 15h18M8 4v16M16 4v16" {...c}/></svg>;
    case 'list':         return <svg viewBox="0 0 24 24" style={s}><path d="M4 6h16M4 12h16M4 18h10" {...c}/></svg>;
    case 'grid':         return <svg viewBox="0 0 24 24" style={s}><rect x="4" y="4" width="7" height="7" rx="1" {...c}/><rect x="13" y="4" width="7" height="7" rx="1" {...c}/><rect x="4" y="13" width="7" height="7" rx="1" {...c}/><rect x="13" y="13" width="7" height="7" rx="1" {...c}/></svg>;
    case 'home':         return <svg viewBox="0 0 24 24" style={s}><path d="M4 11l8-7 8 7v9a1 1 0 0 1-1 1h-4v-6h-6v6H5a1 1 0 0 1-1-1v-9z" {...c}/></svg>;
    case 'heart':        return <svg viewBox="0 0 24 24" style={s}><path d="M12 20s-7-4.5-7-10a4 4 0 0 1 7-2.7A4 4 0 0 1 19 10c0 5.5-7 10-7 10z" {...c}/></svg>;
    case 'heart-fill':   return <svg viewBox="0 0 24 24" style={s}><path d="M12 20s-7-4.5-7-10a4 4 0 0 1 7-2.7A4 4 0 0 1 19 10c0 5.5-7 10-7 10z" fill={color}/></svg>;
    case 'gear':         return <svg viewBox="0 0 24 24" style={s}><circle cx="12" cy="12" r="3" {...c}/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4L7 17M17 7l1.4-1.4" {...c}/></svg>;
    case 'cc':           return <svg viewBox="0 0 24 24" style={s}><rect x="3" y="5" width="18" height="14" rx="2" {...c}/><path d="M8 11a1.5 1.5 0 0 0-3 0v2a1.5 1.5 0 0 0 3 0M15 11a1.5 1.5 0 0 0-3 0v2a1.5 1.5 0 0 0 3 0" {...c}/></svg>;
    case 'speed':        return <svg viewBox="0 0 24 24" style={s}><path d="M4 14a8 8 0 1 1 16 0" {...c}/><path d="M12 14l4-3" {...c}/></svg>;
    case 'lock':         return <svg viewBox="0 0 24 24" style={s}><rect x="5" y="11" width="14" height="9" rx="2" {...c}/><path d="M8 11V8a4 4 0 0 1 8 0v3" {...c}/></svg>;
    case 'unlock':       return <svg viewBox="0 0 24 24" style={s}><rect x="5" y="11" width="14" height="9" rx="2" {...c}/><path d="M8 11V8a4 4 0 0 1 7-2.7" {...c}/></svg>;
    case 'pip':          return <svg viewBox="0 0 24 24" style={s}><rect x="3" y="5" width="18" height="14" rx="2" {...c}/><rect x="12" y="11" width="7" height="6" rx="1" fill={color} stroke="none"/></svg>;
    case 'cast':         return <svg viewBox="0 0 24 24" style={s}><path d="M3 8V6a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6" {...c}/><path d="M3 12a8 8 0 0 1 8 8M3 16a4 4 0 0 1 4 4" {...c}/><circle cx="3.5" cy="20.5" r=".7" fill={color}/></svg>;
    case 'volume':       return <svg viewBox="0 0 24 24" style={s}><path d="M4 9h3l5-4v14l-5-4H4V9z" {...c}/><path d="M16 9a4 4 0 0 1 0 6" {...c}/></svg>;
    case 'volume-x':     return <svg viewBox="0 0 24 24" style={s}><path d="M4 9h3l5-4v14l-5-4H4V9z" {...c}/><path d="M16 10l4 4M20 10l-4 4" {...c}/></svg>;
    case 'sun':          return <svg viewBox="0 0 24 24" style={s}><circle cx="12" cy="12" r="3.5" {...c}/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6L7 7M17 17l1.4 1.4M5.6 18.4L7 17M17 7l1.4-1.4" {...c}/></svg>;
    case 'moon':         return <svg viewBox="0 0 24 24" style={s}><path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z" {...c}/></svg>;
    case 'bookmark':     return <svg viewBox="0 0 24 24" style={s}><path d="M6 4h12v17l-6-4-6 4V4z" {...c}/></svg>;
    case 'bookmark-fill':return <svg viewBox="0 0 24 24" style={s}><path d="M6 4h12v17l-6-4-6 4V4z" fill={color}/></svg>;
    case 'timer':        return <svg viewBox="0 0 24 24" style={s}><circle cx="12" cy="13" r="8" {...c}/><path d="M12 9v4l3 2M9 3h6" {...c}/></svg>;
    case 'eq':           return <svg viewBox="0 0 24 24" style={s}><path d="M5 20V10M5 7V4M12 20v-6M12 11V4M19 20V14M19 11V4" {...c}/><circle cx="5" cy="8.5" r="1.5" fill={color}/><circle cx="12" cy="12.5" r="1.5" fill={color}/><circle cx="19" cy="12.5" r="1.5" fill={color}/></svg>;
    case 'plus':         return <svg viewBox="0 0 24 24" style={s}><path d="M12 5v14M5 12h14" {...c}/></svg>;
    case 'download':     return <svg viewBox="0 0 24 24" style={s}><path d="M12 4v11M7 11l5 5 5-5M4 20h16" {...c}/></svg>;
    case 'file':         return <svg viewBox="0 0 24 24" style={s}><path d="M7 4h7l5 5v11a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z" {...c}/><path d="M14 4v5h5" {...c}/></svg>;
    case 'check':        return <svg viewBox="0 0 24 24" style={s}><path d="M5 12l5 5L20 7" {...c}/></svg>;
    case 'chev-right':   return <svg viewBox="0 0 24 24" style={s}><path d="M9 6l6 6-6 6" {...c}/></svg>;
    case 'chev-down':    return <svg viewBox="0 0 24 24" style={s}><path d="M6 9l6 6 6-6" {...c}/></svg>;
    case 'sort':         return <svg viewBox="0 0 24 24" style={s}><path d="M7 4v16M3 8l4-4 4 4M17 20V4M13 16l4 4 4-4" {...c}/></svg>;
    case 'aspect':       return <svg viewBox="0 0 24 24" style={s}><rect x="3" y="6" width="18" height="12" rx="1" {...c}/><path d="M7 10l-2 2 2 2M17 10l2 2-2 2" {...c}/></svg>;
    case 'audio':        return <svg viewBox="0 0 24 24" style={s}><path d="M9 18V6l10-2v12" {...c}/><circle cx="6" cy="18" r="3" {...c}/><circle cx="16" cy="16" r="3" {...c}/></svg>;
    case 'rotate':       return <svg viewBox="0 0 24 24" style={s}><path d="M21 12a9 9 0 1 1-3-6.7" {...c}/><path d="M21 4v5h-5" {...c}/></svg>;
    case 'pin':          return <svg viewBox="0 0 24 24" style={s}><path d="M12 21v-7M8 4h8l-1 5 3 3H7l3-3-2-5z" {...c}/></svg>;
    case 'eye':          return <svg viewBox="0 0 24 24" style={s}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z" {...c}/><circle cx="12" cy="12" r="3" {...c}/></svg>;
    case 'eye-off':      return <svg viewBox="0 0 24 24" style={s}><path d="M3 3l18 18M10.5 6.2a10 10 0 0 1 1.5-.1c6.5 0 10 6 10 6a18 18 0 0 1-3 3.9M6.6 6.6C3.4 8.6 2 12 2 12s3.5 7 10 7c2 0 3.8-.5 5.3-1.4M9 9.5a3 3 0 0 0 4.5 4" {...c}/></svg>;
    case 'star':         return <svg viewBox="0 0 24 24" style={s}><path d="M12 3l2.7 5.7 6.3.9-4.5 4.4 1 6.2L12 17.3 6.5 20.2l1-6.2L3 9.6l6.3-.9L12 3z" {...c}/></svg>;
    case 'clock':        return <svg viewBox="0 0 24 24" style={s}><circle cx="12" cy="12" r="9" {...c}/><path d="M12 7v5l3 3" {...c}/></svg>;
    case 'scan':         return <svg viewBox="0 0 24 24" style={s}><path d="M3 7V5a2 2 0 0 1 2-2h2M17 3h2a2 2 0 0 1 2 2v2M21 17v2a2 2 0 0 1-2 2h-2M7 21H5a2 2 0 0 1-2-2v-2M3 12h18" {...c}/></svg>;
    case 'history':      return <svg viewBox="0 0 24 24" style={s}><path d="M12 8v4l3 3" {...c}/><path d="M3.05 11a9 9 0 1 0 .5-3M3 4v4h4" {...c}/></svg>;
    case 'cloud':        return <svg viewBox="0 0 24 24" style={s}><path d="M18 10a6 6 0 0 0-12 0A4 4 0 0 0 8 18h10a4 4 0 0 0 0-8z" {...c}/></svg>;
    case 'video-rec':    return <svg viewBox="0 0 24 24" style={s}><rect x="2" y="7" width="14" height="10" rx="2" {...c}/><path d="M16 11l5-3v8l-5-3v-2z" {...c}/><circle cx="8" cy="12" r="2" fill={color} stroke="none"/></svg>;
    default:             return <svg viewBox="0 0 24 24" style={s}><rect x="4" y="4" width="16" height="16" rx="2" {...c}/></svg>;
  }
}

function Thumbnail({ hue = 30, label = '', aspect = '16/9', radius = 10, style }) {
  const reactId = React.useId ? React.useId() : Math.random().toString(36).slice(2);
  const pid = `rp-${reactId.replace(/:/g, '')}`;
  const gid = `rg-${reactId.replace(/:/g, '')}`;
  return (
    <div style={{ position:'relative', aspectRatio:aspect, borderRadius:radius, overflow:'hidden', background:`oklch(0.22 0.04 ${hue})`, ...style }}>
      <svg width="100%" height="100%" viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" style={{ position:'absolute', inset:0, display:'block' }}>
        <defs>
          <pattern id={pid} width="14" height="14" patternUnits="userSpaceOnUse" patternTransform="rotate(35)">
            <rect width="14" height="14" fill={`oklch(0.24 0.05 ${hue})`}/>
            <rect width="6" height="14" fill={`oklch(0.20 0.04 ${hue})`}/>
          </pattern>
          <radialGradient id={gid} cx="50%" cy="55%" r="65%">
            <stop offset="0%" stopColor="rgba(0,0,0,0)"/>
            <stop offset="100%" stopColor="rgba(0,0,0,0.55)"/>
          </radialGradient>
        </defs>
        <rect width="160" height="90" fill={`url(#${pid})`}/>
        <rect width="160" height="90" fill={`url(#${gid})`}/>
      </svg>
      {label && (
        <div style={{ position:'absolute', left:8, bottom:8, fontFamily:REEL_TOKENS.mono, fontSize:9, color:'rgba(255,255,255,0.55)', letterSpacing:0.5, textTransform:'uppercase' }}>{label}</div>
      )}
    </div>
  );
}

function ResumeBar({ progress = 0, accent = REEL_TOKENS.accent }) {
  return (
    <div style={{ position:'absolute', left:8, right:8, bottom:6, height:3, background:'rgba(255,255,255,0.18)', borderRadius:2, overflow:'hidden' }}>
      <div style={{ width:`${progress*100}%`, height:'100%', background:accent }}/>
    </div>
  );
}

function Chip({ active, children, onClick, style }) {
  return (
    <button onClick={onClick} style={{
      border:'1px solid', borderColor:active ? REEL_TOKENS.accent : REEL_TOKENS.border,
      background:active ? REEL_TOKENS.accentSoft : 'transparent',
      color:active ? REEL_TOKENS.accent : REEL_TOKENS.text,
      borderRadius:999, padding:'6px 12px', fontSize:12, fontWeight:600,
      fontFamily:'inherit', cursor:'pointer', whiteSpace:'nowrap', ...style,
    }}>{children}</button>
  );
}

// Bottom sheet container
function Sheet({ title, sub, onClose, children, height = 'auto', actions }) {
  const T = REEL_TOKENS;
  const iconBtn = { width:38,height:38,borderRadius:19,border:'none',background:'transparent',color:T.text,display:'inline-flex',alignItems:'center',justifyContent:'center',cursor:'pointer',padding:0 };
  return (
    <div onClick={onClose} style={{ position:'absolute',inset:0,zIndex:20,background:'rgba(0,0,0,0.55)',backdropFilter:'blur(4px)',display:'flex',flexDirection:'column',justifyContent:'flex-end' }}>
      <div onClick={e=>e.stopPropagation()} style={{ background:T.surface,color:T.text,borderTopLeftRadius:24,borderTopRightRadius:24,borderTop:'1px solid '+T.border,padding:'8px 0 18px',maxHeight:height==='full'?'92%':'80%',display:'flex',flexDirection:'column' }}>
        <div style={{ width:38,height:4,borderRadius:2,background:'rgba(255,255,255,0.2)',margin:'6px auto 6px' }}/>
        <div style={{ padding:'8px 18px 10px',display:'flex',alignItems:'center' }}>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:17,fontWeight:700 }}>{title}</div>
            {sub && <div style={{ fontSize:12,color:T.textDim,marginTop:2 }}>{sub}</div>}
          </div>
          {actions}
          <button onClick={onClose} style={iconBtn}><Icon name="close" size={20}/></button>
        </div>
        <div style={{ overflow:'auto',padding:'4px 16px 4px' }}>{children}</div>
      </div>
    </div>
  );
}

// Seek bar with chapter ticks, bookmark stars, fav-scene hearts
function SeekBar({ pos, duration, accent, onChange, favScenes = [], chapters = [], bookmarks = [] }) {
  const ref = React.useRef(null);
  const pct = duration > 0 ? (pos / duration) * 100 : 0;
  const onDown = e => {
    const rect = ref.current.getBoundingClientRect();
    const move = ev => {
      const x = (ev.touches ? ev.touches[0].clientX : ev.clientX) - rect.left;
      onChange(Math.max(0, Math.min(1, x / rect.width)) * duration);
    };
    move(e);
    const up = () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); window.removeEventListener('touchmove', move); window.removeEventListener('touchend', up); };
    window.addEventListener('mousemove', move); window.addEventListener('mouseup', up);
    window.addEventListener('touchmove', move); window.addEventListener('touchend', up);
  };
  return (
    <div ref={ref} onMouseDown={onDown} onTouchStart={onDown} style={{ height:24,display:'flex',alignItems:'center',cursor:'pointer',position:'relative' }}>
      <div style={{ position:'absolute',left:0,right:0,height:4,borderRadius:2,background:'rgba(255,255,255,0.2)' }}/>
      <div style={{ position:'absolute',left:0,width:`${pct}%`,height:4,borderRadius:2,background:accent }}/>
      {chapters.map((c,i) => <div key={i} style={{ position:'absolute',left:`${(c.t/duration)*100}%`,width:2,height:4,background:'rgba(0,0,0,0.6)',transform:'translateX(-1px)' }}/>)}
      {bookmarks.map((b,i) => <div key={i} style={{ position:'absolute',left:`${(b.t/duration)*100}%`,top:-3,transform:'translateX(-50%)' }}><Icon name="bookmark-fill" size={10} color={accent}/></div>)}
      {favScenes.map((f,i) => <div key={i} style={{ position:'absolute',left:`${(f.t/duration)*100}%`,top:9,transform:'translateX(-50%)',filter:'drop-shadow(0 1px 2px rgba(0,0,0,0.6))' }}><Icon name="heart-fill" size={11} color={accent}/></div>)}
      <div style={{ position:'absolute',left:`${pct}%`,width:14,height:14,borderRadius:7,background:accent,transform:'translateX(-50%)',boxShadow:`0 0 0 4px ${accentSoftColor(accent)}` }}/>
    </div>
  );
}

function useTweaks(defaults) {
  const KEY = 'reel-tweaks';
  const [tweaks, setAll] = React.useState(() => {
    try { return { ...defaults, ...JSON.parse(localStorage.getItem(KEY) || '{}') }; }
    catch { return defaults; }
  });
  const setTweak = React.useCallback((k, v) => {
    setAll(t => {
      const next = { ...t, [k]: v };
      try { localStorage.setItem(KEY, JSON.stringify(next)); } catch {}
      return next;
    });
  }, []);
  return [tweaks, setTweak];
}

Object.assign(window, { REEL_TOKENS, fmt, accentSoftColor, Icon, Thumbnail, ResumeBar, Chip, Sheet, SeekBar, useTweaks });
