const { useState, useEffect, useRef, useCallback } = React;

const API_BASE = "";
const MOD_CODE = "filmscout-mod-2025";
const SK = "SKIP", MU = "MUTE", HU = "HEADS UP", GL = "ALL CLEAR";
const STYLE_D = {
  SKIP:        { bg:"#1a0808", border:"#dc2626", text:"#fca5a5", badge:"#dc2626", badgeText:"#fff" },
  MUTE:        { bg:"#160d02", border:"#ea580c", text:"#fdba74", badge:"#ea580c", badgeText:"#fff" },
  "HEADS UP":  { bg:"#111008", border:"#b45309", text:"#fcd34d", badge:"#d97706", badgeText:"#000" },
  "ALL CLEAR": { bg:"#061208", border:"#22c55e", text:"#86efac", badge:"#22c55e", badgeText:"#000" },
};
const STYLE_L = {
  SKIP:        { bg:"#fff1f1", border:"#dc2626", text:"#b91c1c", badge:"#dc2626", badgeText:"#fff" },
  MUTE:        { bg:"#fff5ee", border:"#ea580c", text:"#c2410c", badge:"#ea580c", badgeText:"#fff" },
  "HEADS UP":  { bg:"#fffbeb", border:"#b45309", text:"#92400e", badge:"#d97706", badgeText:"#000" },
  "ALL CLEAR": { bg:"#f0fdf4", border:"#22c55e", text:"#166534", badge:"#22c55e", badgeText:"#000" },
};
const ICON  = { SKIP:"⏭", MUTE:"🔇", "HEADS UP":"⚠️", "ALL CLEAR":"✅" };
const LABEL = { SKIP:"Skip to", MUTE:"Unmute at", "HEADS UP":"Safe at", "ALL CLEAR":"Safe until" };
const fmt = s => {
  const t=Math.max(0,Math.floor(s)),h=Math.floor(t/3600),m=Math.floor((t%3600)/60),sc=t%60;
  return h ? `${h}:${String(m).padStart(2,"0")}:${String(sc).padStart(2,"0")}` : `${String(m).padStart(2,"0")}:${String(sc).padStart(2,"0")}`;
};
const resolveTs = (sc, platform) => {
  if (!sc.platform_ts) return { s: sc.s||0, e: sc.e||0 };
  return sc.platform_ts[platform] || sc.platform_ts["default"] || { s: sc.s||0, e: sc.e||0 };
};

function createAlarm(onBlocked) {
  let ctx = null, blocked = false;
  function init() {
    if (ctx || blocked) return;
    try {
      ctx = new (window.AudioContext || window.webkitAudioContext)();
      const osc = ctx.createOscillator(), g = ctx.createGain();
      g.gain.value = 0.00001; osc.connect(g); g.connect(ctx.destination); osc.start();
      if (ctx.state === "suspended") ctx.resume();
    } catch(e) { blocked = true; if (onBlocked) onBlocked(); }
  }
  function beep(freq, t, dur, vol=0.4) {
    if (!ctx || blocked) return;
    try {
      const o=ctx.createOscillator(), g=ctx.createGain();
      o.frequency.value=freq; g.gain.setValueAtTime(vol,t); g.gain.exponentialRampToValueAtTime(0.001,t+dur);
      o.connect(g); g.connect(ctx.destination); o.start(t); o.stop(t+dur+0.05);
    } catch(e) {}
  }
  return {
    init, isBlocked: ()=>blocked,
    warning() { const t=ctx?.currentTime||0; beep(880,t,0.18); beep(880,t+0.28,0.18); },
    active()  { const t=ctx?.currentTime||0; beep(1100,t,0.12,0.5); beep(1100,t+0.18,0.12,0.5); beep(1100,t+0.36,0.12,0.5); },
  };
}

const GENRES = ["All","Action","Sci-Fi","Horror","Comedy","Drama","Fantasy","Musical","War","Romance"];
const SERVICES = ["All","Disney+","Netflix","Max","Prime Video","Paramount+","Apple TV+","Hulu","Peacock"];
const GENRE_COLOR = {
  "All":["#94a3b8","transparent","#334155"],"Action":["#fca5a5","#3f0f0f","#dc2626"],
  "Sci-Fi":["#93c5fd","#0c1a3f","#3b82f6"],"Horror":["#86efac","#061a0f","#22c55e"],
  "Comedy":["#fde68a","#2d1f03","#f59e0b"],"Drama":["#d8b4fe","#1e0d3f","#a855f7"],
  "Fantasy":["#67e8f9","#031a20","#06b6d4"],"Musical":["#f9a8d4","#2d0a1a","#ec4899"],
  "War":["#cbd5e1","#1a1f2e","#64748b"],"Romance":["#fda4af","#2d0a10","#f43f5e"],
};
const SVC = {
  "All":        ["#94a3b8","transparent","#334155","","transparent","#334155"],
  "Disney+":    ["#93c5fd","#0a1535","#1d4ed8","🏰","#eff6ff","#1e40af"],
  "Netflix":    ["#fca5a5","#2d0505","#dc2626","🎬","#fff1f1","#991b1b"],
  "Max":        ["#c4b5fd","#160d35","#7c3aed","〽️","#faf5ff","#5b21b6"],
  "Prime Video":["#67e8f9","#031520","#0891b2","📦","#ecfeff","#155e75"],
  "Paramount+": ["#fde68a","#1f1503","#ca8a04","⛰️","#fffbeb","#92400e"],
  "Apple TV+":  ["#6b7280","#111318","#6b7280","🍎","#f3f4f6","#374151"],
  "Hulu":       ["#86efac","#031a0a","#16a34a","💚","#f0fdf4","#166534"],
  "Peacock":    ["#f97316","#1a0d03","#ea580c","🦚","#fff7ed","#9a3412"],
};
const getSVC = (sv, isDark) => {
  const s = SVC[sv] || ["#94a3b8","transparent","#334155","","transparent","#334155"];
  return [isDark ? s[0] : s[5], isDark ? s[1] : s[4], s[2], s[3]];
};
const genreOf = m => m.genre.split(/[·,\/]/)[0].trim();
const getFingerprint = () => {
  try {
    const n = navigator.userAgent + navigator.language + screen.width + screen.height;
    let h = 0; for (let i=0;i<n.length;i++){h=((h<<5)-h)+n.charCodeAt(i);h|=0;}
    return "fp_"+Math.abs(h).toString(36);
  } catch(e) { return "fp_x"; }
};

// ─── API HELPERS ─────────────────────────────────────────────────────────────
const getFP = () => getFingerprint();
const apiFetch = (path, opts={}) => {
  const jwt = (() => { try { return localStorage.getItem("fs_jwt"); } catch(e) { return null; } })();
  const headers = { "Content-Type":"application/json", ...(jwt ? {"Authorization":"Bearer "+jwt} : {}), ...(opts.headers||{}) };
  return fetch(API_BASE + path, { ...opts, headers });
};
// ─────────────────────────────────────────────────────────────────────────────


const IC = {
  home:     <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9.5L12 3l9 6.5V20a1 1 0 01-1 1H4a1 1 0 01-1-1V9.5z"/><path d="M9 21V12h6v9"/></svg>,
  settings: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>,
  film:     <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18"/><line x1="7" y1="2" x2="7" y2="22"/><line x1="17" y1="2" x2="17" y2="22"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="2" y1="7" x2="7" y2="7"/><line x1="2" y1="17" x2="7" y2="17"/><line x1="17" y1="17" x2="22" y2="17"/><line x1="17" y1="7" x2="22" y2="7"/></svg>,
  search:   <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>,
  close:    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  arrowR:   <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>,
  resync:   <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 102.13-9.36L1 10"/></svg>,
  check:    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
  shield:   <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L3 7v6c0 5.25 3.75 10.15 9 11.25C17.25 23.15 21 18.25 21 13V7l-9-5z"/></svg>,
  user:     <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
  star:     <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>,
  pencil:   <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>,
  share:    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>,
};

function Logo({ size }) {
  const s = size || 28;
  return <img src="/assets/brand/icon_square.svg" width={s} height={s} alt="FilmScout" style={{display:"block"}} />;
}

function Badge({ type, isDark }) {
  if (type === "mod")  return <span style={{display:"inline-flex",alignItems:"center",gap:3,background:isDark?"#0a1a0a":"#f0fdf4",border:"1px solid #22c55e60",borderRadius:20,padding:"1px 6px",fontSize:9,fontWeight:700,color:"#16a34a",whiteSpace:"nowrap"}}>{IC.shield} Mod Verified</span>;
  if (type === "pro")  return <span style={{display:"inline-flex",alignItems:"center",gap:3,background:isDark?"#1a0900":"#fff7ed",border:"1px solid #d45b1750",borderRadius:20,padding:"1px 6px",fontSize:9,fontWeight:700,color:"#d45b17",whiteSpace:"nowrap"}}>{IC.star} Pro Verified</span>;
  if (type === "user") return <span style={{display:"inline-flex",alignItems:"center",gap:3,background:isDark?"#0c1a2e":"#eff6ff",border:"1px solid #3b82f650",borderRadius:20,padding:"1px 6px",fontSize:9,fontWeight:700,color:isDark?"#60a5fa":"#1d4ed8",whiteSpace:"nowrap"}}>{IC.user} User Edited - Needs Pro Review</span>;
  return null;
}

function SceneRow({ sc, platform, onEdit, T, isDark }) {
  const st = (isDark?STYLE_D:STYLE_L)[sc.a], ts = resolveTs(sc, platform);
  return (
    <div style={{display:"flex",gap:8,padding:"9px 0",borderBottom:"1px solid "+T.border,opacity:sc.a===GL?0.7:1}}>
      <div style={{background:isDark?st.badge:st.bg,color:isDark?st.badgeText:st.border,border:isDark?"none":"1px solid "+st.border+"80",borderRadius:4,padding:"2px 6px",fontSize:10,fontWeight:800,whiteSpace:"nowrap",flexShrink:0,marginTop:1}}>{ICON[sc.a]} {sc.a}</div>
      <div style={{flex:1,minWidth:0}}>
        <div style={{display:"flex",justifyContent:"space-between",gap:4}}>
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontSize:12,fontWeight:600,color:st.text}}>{sc.t}</div>
            <div style={{marginTop:2}}><Badge type={sc.verified_by} isDark={isDark}/></div>
          </div>
          <div style={{display:"flex",alignItems:"flex-start",gap:6,flexShrink:0}}>
            <div style={{textAlign:"right"}}>
              <div style={{fontSize:11,fontFamily:"monospace",color:"#94afc7"}}>{fmt(ts.s)} →</div>
              <div style={{fontSize:11,fontFamily:"monospace",color:st.border,fontWeight:700}}>{fmt(ts.e)}</div>
            </div>
            {onEdit && <button onClick={()=>onEdit(sc)} style={{background:"none",border:"1px solid "+T.border,borderRadius:6,minWidth:32,minHeight:32,display:"flex",alignItems:"center",justifyContent:"center",color:T.accent,cursor:"pointer",flexShrink:0}}>{IC.pencil}</button>}
          </div>
        </div>
        {sc.d && <div style={{fontSize:11,color:T.textDim,lineHeight:1.4,marginTop:2}}>{sc.d}</div>}
      </div>
    </div>
  );
}

function MovieCard({ movie, onSelect, locked, isGuestMovie, T, isDark }) {
  const flagged = movie.scenes.filter(s=>s.a!==GL);
  const skip=flagged.filter(s=>s.a===SK).length, mute=flagged.filter(s=>s.a===MU).length, warn=flagged.filter(s=>s.a===HU).length;
  const hues = {Action:"#ef4444","Sci-Fi":"#f97316",Horror:"#22c55e",Comedy:"#f59e0b",Drama:"#a855f7",Fantasy:"#06b6d4",Musical:"#f472b6",War:"#94a3b8",Romance:"#ec4899"};
  const accent = hues[genreOf(movie)]||"#f97316";
  return (
    <div onClick={()=>onSelect(movie)}
      style={{background:T.surface,border:"1px solid "+T.border,borderRadius:12,overflow:"hidden",cursor:"pointer",transition:"transform 0.15s, box-shadow 0.15s"}}
      onMouseEnter={e=>{e.currentTarget.style.transform="translateY(-2px)";e.currentTarget.style.boxShadow="0 6px 24px "+accent+"20";}}
      onMouseLeave={e=>{e.currentTarget.style.transform="";e.currentTarget.style.boxShadow="";}}>
      <div style={{height:3,background:"linear-gradient(90deg,"+accent+"60,"+accent+","+accent+"60)"}}/>
      <div style={{padding:"11px 13px 13px"}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:4}}>
          <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:13,color:T.text,lineHeight:1.25,flex:1,paddingRight:6}}>
            {movie.title}{movie.sub&&<span style={{color:accent,fontWeight:400}}> {movie.sub}</span>}
          </div>
          <span style={{fontSize:10,color:T.textDim,flexShrink:0}}>{movie.year}</span>
        </div>
        <div style={{display:"flex",alignItems:"center",gap:4,marginBottom:8}}>
          <span style={{fontSize:10,color:T.textFaint}}>{movie.genre}</span>
          <span style={{fontSize:10,color:T.textFaint}}>· {movie.year}</span>
          {movie.rating&&<span style={{fontSize:10,color:T.accentLt,background:T.accentBg,border:"1px solid "+T.accent+"30",borderRadius:3,padding:"1px 5px",marginLeft:2}}>{movie.rating}</span>}
        </div>
        <div style={{display:"flex",gap:4,flexWrap:"wrap",marginBottom:locked?6:0}}>
          {skip>0&&<span style={{background:isDark?"#1a080820":"#fff1f1",border:"1px solid #dc262650",borderRadius:3,padding:"2px 6px",fontSize:10,color:isDark?"#fca5a5":"#b91c1c",fontWeight:700}}>⏭ {skip}</span>}
          {mute>0&&<span style={{background:isDark?"#16090220":"#fff5ee",border:"1px solid #ea580c50",borderRadius:3,padding:"2px 6px",fontSize:10,color:isDark?"#fdba74":"#c2410c",fontWeight:700}}>🔇 {mute}</span>}
          {warn>0&&<span style={{background:isDark?"#11100820":"#fffbeb",border:"1px solid #d9770650",borderRadius:3,padding:"2px 6px",fontSize:10,color:isDark?"#fcd34d":"#92400e",fontWeight:700}}>⚠️ {warn}</span>}
        </div>
        {locked ? (
          <div style={{marginTop:6,display:"flex",gap:5,flexWrap:"wrap"}}>
            <span style={{display:"inline-flex",alignItems:"center",gap:4,background:"linear-gradient(135deg,#ff8f3c 0%,#d45b17 100%)",borderRadius:20,padding:"2px 8px",fontSize:10,color:"#fff",fontWeight:700}}>▶ 7-Day Free Trial</span>
            <span style={{display:"inline-flex",alignItems:"center",gap:4,background:"transparent",border:"1px solid "+T.border,borderRadius:20,padding:"2px 8px",fontSize:10,color:T.textDim,fontWeight:600}}>or 1 free as guest</span>
          </div>
        ) : isGuestMovie ? (
          <div style={{marginTop:6}}>
            <span style={{display:"inline-flex",alignItems:"center",gap:4,background:"transparent",border:"1px solid #22c55e60",borderRadius:20,padding:"2px 8px",fontSize:10,color:"#22c55e",fontWeight:600}}>✓ Guest preview</span>
          </div>
        ) : (
          <div style={{marginTop:6}}>
            <span style={{display:"inline-flex",alignItems:"center",gap:4,background:"transparent",border:"1px solid "+T.border,borderRadius:20,padding:"2px 8px",fontSize:10,color:T.textDim,fontWeight:600}}>▶ Watch</span>
          </div>
        )}
        {(movie.stream||[]).length>0&&(
          <div style={{marginTop:7,paddingTop:7,borderTop:"1px solid "+T.border}}>
            <div style={{display:"flex",gap:4,flexWrap:"wrap"}}>
              {(movie.stream||[]).map(sv=>{
                const [ct,cb,cbr,icon]=getSVC(sv,isDark);
                return <span key={sv} style={{fontSize:10,color:ct,background:cb,border:"1px solid "+cbr+"60",borderRadius:4,padding:"2px 7px",display:"inline-flex",alignItems:"center",gap:3,fontWeight:600}}>{icon&&<span style={{fontSize:11}}>{icon}</span>}{sv}</span>;
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function Sheet({children, onClose, borderColor, T}) {
  return (
    <div>
      <div onClick={onClose} style={{position:"fixed",inset:0,background:"rgba(0,0,0,.75)",zIndex:200}}/>
      <div style={{position:"fixed",bottom:0,left:0,right:0,maxWidth:500,margin:"0 auto",background:T.sheetBg,borderTop:"2px solid "+(borderColor||T.border),borderRadius:"24px 24px 0 0",padding:"28px 24px 48px",zIndex:201,animation:"sheet-up .3s ease",maxHeight:"85vh",overflowY:"auto"}}>
        {children}
      </div>
    </div>
  );
}

function CloseBtn({onClose, T}) {
  return <button onClick={onClose} style={{background:T.border,border:"none",borderRadius:"50%",width:32,height:32,color:T.textDim,fontSize:16,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}}>{IC.close}</button>;
}

function FilmScout() {
  const [phase,setPhase]             = useState("home");
  const [movie,setMovie]             = useState(null);
  const [search,setSearch]           = useState("");
  const [genre,setGenre]             = useState([]);
  const [service,setService]         = useState([]);
  const [filterAct,setFilterAct]     = useState([]);
  const [scenesOpen,setScenesOpen]   = useState(false);
  const [showGreen,setShowGreen]     = useState(false);
  const [elapsed,setElapsed]         = useState(0);
  const [playing,setPlaying]         = useState(false);
  const [alertScene,setAlertScene]   = useState(null);
  const [confirmLeave,setConfirmLeave] = useState(false);
  const [confirmClear,setConfirmClear] = useState(false);
  const [dismissed,setDismissed]     = useState(new Set());
  const [toast,setToast]             = useState(null);
  const [alarmOn,setAlarmOn]         = useState(()=>{ try{return localStorage.getItem('fs_alarm')!=='0';}catch(e){return true;} });
  const [vibrationOn,setVibrationOn] = useState(()=>{ try{return localStorage.getItem('fs_vib')!=='0';}catch(e){return true;} });
  const [warnAhead,setWarnAhead]     = useState(()=>{ try{return parseInt(localStorage.getItem('fs_warn')||'30');}catch(e){return 30;} });
  const [resyncOpen,setResyncOpen]   = useState(false);
  const [isPro,setIsPro]             = useState(false);
  const [isBetaFree,setIsBetaFree]   = useState(false);
  const [trialActive,setTrialActive] = useState(false);
  const [currentUser,setCurrentUser] = useState(null);
  const [isGuest,setIsGuest]         = useState(false);
  const [guestMovieId,setGuestMovieId] = useState(()=>{ try{return localStorage.getItem("fs_gm")||null;}catch(e){return null;} });
  useEffect(()=>{
    if(guestMovieId) return;
    const fp = getFP();
    apiFetch("/api/guest?fp="+encodeURIComponent(fp))
      .then(r=>r.json()).then(d=>{ if(d.movieId){ setGuestMovieId(d.movieId); try{localStorage.setItem("fs_gm",d.movieId);}catch(e){} } })
      .catch(()=>{});
  },[]);
  const [feedbackOpen,setFeedbackOpen] = useState(false);
  const [feedbackCategory,setFeedbackCategory] = useState("");
  const [feedbackText,setFeedbackText] = useState("");
  const [feedbackDone,setFeedbackDone] = useState(false);
  const [feedbackSubmitting,setFeedbackSubmitting] = useState(false);
  const [requestOpen,setRequestOpen]   = useState(false);
  const [requestText,setRequestText]   = useState("");
  const [requestDone,setRequestDone]   = useState(false);
  const [theme,setTheme]             = useState("dark");
  const [highContrast,setHighContrast] = useState(false);
  const [upgradeOpen,setUpgradeOpen] = useState(false);
  const [checkoutLoading,setCheckoutLoading] = useState(null); // "monthly" | "annual" | null
  const [showDisclaimer,setShowDisclaimer] = useState(()=>{ try{return!localStorage.getItem('fs_disc');}catch(e){return true;} });
  const [manualTime,setManualTime]   = useState("");
  const [resyncTime,setResyncTime]   = useState("");
  const [platform,setPlatform]       = useState("");
  const [movies,setMovies]           = useState([]);
  const [loading,setLoading]         = useState(true);
  const [pendingMovie,setPendingMovie] = useState(null);
  const [tsOpen,setTsOpen]           = useState(false);
  const [tsScene,setTsScene]         = useState(null);
  const [tsPlatform,setTsPlatform]   = useState("");
  const [tsType,setTsType]           = useState([]);
  const [tsStart,setTsStart]         = useState("");
  const [tsEnd,setTsEnd]             = useState("");
  const [tsNeighbors,setTsNeighbors] = useState({prev:null,next:null});
  const [corrections,setCorrections] = useState(()=>{ try{return JSON.parse(localStorage.getItem("fs_c")||"[]");}catch(e){return[];} });
  const [isMod,setIsMod]             = useState(()=>{ try{return localStorage.getItem("fs_mod")==="1";}catch(e){return false;} });
  const [modCodeInput,setModCodeInput] = useState("");
  const [modCodeError,setModCodeError] = useState(false);
  const refCode = (() => { try { const fp=getFP(); return "FS"+Math.abs(parseInt(fp.replace("fp_",""),36)).toString(36).toUpperCase().slice(0,6); } catch(e){return "FSGUEST";} })();
  const refUrl = "https://getfilmscout.com?ref="+refCode;
  const [refCount,setRefCount]        = useState(()=>{ try{return parseInt(localStorage.getItem("fs_rc")||"0");}catch(e){return 0;} });
  const [loginOpen,setLoginOpen]     = useState(false);
  const [loginMode,setLoginMode]     = useState(null);
  const [loginTab,setLoginTab]       = useState("social");
  const [emailInput,setEmailInput]   = useState("");
  const [passInput,setPassInput]     = useState("");
  const [emailError,setEmailError]   = useState("");
  const [trialUsed,setTrialUsed]     = useState(()=>{ try{const fp=getFP();return !!(JSON.parse(localStorage.getItem("fs_t")||"{}")[fp]);}catch(e){return false;} });

  const [username,setUsername]               = useState(null);
  const [oldUsernames,setOldUsernames]       = useState([]);
  const [oldEmails,setOldEmails]             = useState([]);
  const [hasPassword,setHasPassword]         = useState(false);
  const [unameEdit,setUnameEdit]             = useState(false);
  const [unameInput,setUnameInput]           = useState("");
  const [unameExpanded,setUnameExpanded]     = useState(false);
  const [emailEdit,setEmailEdit]             = useState(false);
  const [emailInput2,setEmailInput2]         = useState("");
  const [emailExpanded,setEmailExpanded]     = useState(false);
  const [pwModal,setPwModal]                 = useState(false);
  const [pwCurrentInput,setPwCurrentInput]   = useState("");
  const [pwNewInput,setPwNewInput]           = useState("");
  const [pwConfirmInput,setPwConfirmInput]   = useState("");
  const [pwSaving,setPwSaving]               = useState(false);
  const [refUserId]                          = useState(()=>{ try{ const p=new URLSearchParams(window.location.search); const r=p.get('ref'); if(r){try{localStorage.setItem('fs_ref',r);}catch(e){} return r;} return localStorage.getItem('fs_ref')||null; }catch(e){return null;} });
  const [unamePromptOpen,setUnamePromptOpen] = useState(false);
  const [unamePromptMode,setUnamePromptMode] = useState(null);
  const [unamePromptInput,setUnamePromptInput] = useState("");
  const [deleteConfirmOpen,setDeleteConfirmOpen] = useState(false);
  const [deleteConfirmInput,setDeleteConfirmInput] = useState("");

  const refreshUserData = async () => {
    try {
      const r = await apiFetch("/api/auth/me");
      const data = await r.json();
      if (!data.user) return;
      setCurrentUser(data.user);
      setUsername(data.user.username || null);
      setOldUsernames(data.user.old_usernames || []);
      setOldEmails(data.user.old_emails || []);
      setHasPassword(!!data.user.has_password);
      if (data.plan === "pro") setIsPro(true);
      else if (data.plan === "trial") setTrialActive(true);
      else if (data.plan === "beta_free") setIsBetaFree(true);
    } catch(e) {}
  };

  useEffect(()=>{ refreshUserData(); },[]);

  useEffect(()=>{
    fetch("/api/movies")
      .then(r=>r.json())
      .then(data=>{ setMovies(Array.isArray(data)?data:[]); setLoading(false); })
      .catch(()=>setLoading(false));
  },[]);

  // Handle Stripe return — ?payment=success cleans URL and waits for webhook to update JWT
  useEffect(()=>{
    try {
      const params = new URLSearchParams(window.location.search);
      const payment = params.get("payment");
      if (payment === "success") {
        // Clean URL
        window.history.replaceState({}, "", window.location.pathname);
        // Poll for updated JWT up to 10s (webhook may take a moment)
        let attempts = 0;
        const poll = setInterval(async () => {
          attempts++;
          try {
            const res = await apiFetch("/api/auth/me");
            const data = await res.json();
            if (data.plan === "pro") {
              if (data.token) { try { localStorage.setItem("fs_jwt", data.token); } catch(e) {} }
              setIsPro(true);
              setUpgradeOpen(false);
              showToast("🎉 FilmScout Pro activated!","#22c55e");
              clearInterval(poll);
            }
          } catch(e) {}
          if (attempts >= 10) {
            clearInterval(poll);
            showToast("Payment received — sign in to activate Pro","#d45b17");
          }
        }, 1000);
      } else if (payment === "cancelled") {
        window.history.replaceState({}, "", window.location.pathname);
        showToast("Checkout cancelled","#94a3b8");
      }

      // Handle Google OAuth return
      const auth = params.get("auth");
      if (auth === "success") {
        const hash = window.location.hash;
        const token = hash.match(/token=([^&]+)/)?.[1];
        window.history.replaceState({}, "", window.location.pathname);
        if (token) {
          try { localStorage.setItem("fs_jwt", token); } catch(e) {}
          try {
            const parts = token.split(".");
            const payload = JSON.parse(atob(parts[1].replace(/-/g,"+").replace(/_/g,"/")));
            if (payload.email) setCurrentUser({email: payload.email});
            if (payload.plan === "pro") { setIsPro(true); showToast("Welcome back — FilmScout Pro!","#22c55e"); }
            else if (payload.plan === "beta_free") { setIsBetaFree(true); showToast("Signed in with Google ✓", "#22c55e"); }
            else { showToast("Signed in with Google ✓", "#22c55e"); }
          } catch(e) {}
          setLoginOpen(false);
        }
      } else if (auth === "error") {
        window.history.replaceState({}, "", window.location.pathname);
        showToast("Sign in failed — please try again","#f87171");
      } else if (auth === "cancelled") {
        window.history.replaceState({}, "", window.location.pathname);
      }
    } catch(e) {}
  },[]);

  const startRef=useRef(null), pausedRef=useRef(null), totalPausedRef=useRef(0);
  const playingRef=useRef(false), alarmRef=useRef(true), vibrationRef=useRef(true), timerRef=useRef(null), lastAlertRef=useRef(null), warnAheadRef=useRef(30);
  useEffect(()=>{playingRef.current=playing;},[playing]);
  useEffect(()=>{ alarmRef.current=alarmOn; try{localStorage.setItem('fs_alarm',alarmOn?'1':'0');}catch(e){}; },[alarmOn]);
  useEffect(()=>{ vibrationRef.current=vibrationOn; try{localStorage.setItem('fs_vib',vibrationOn?'1':'0');}catch(e){}; },[vibrationOn]);
  useEffect(()=>{ warnAheadRef.current=warnAhead; try{localStorage.setItem('fs_warn',String(warnAhead));}catch(e){}; },[warnAhead]);

  const showToast = (msg,color) => { setToast({msg,color:color||"#d45b17"}); setTimeout(()=>setToast(null),2800); };

  const alarmRef2=useRef(null);
  if(!alarmRef2.current) alarmRef2.current=createAlarm(()=>showToast("Audio blocked - tap screen to enable","#f87171"));
  const alarm=alarmRef2.current;

  useEffect(()=>{
    if(playing){ timerRef.current=setInterval(()=>{ const s=(Date.now()-startRef.current-totalPausedRef.current)/1000; setElapsed(Math.min(s,movie?.rt??99999)); },100); }
    else clearInterval(timerRef.current);
    return ()=>clearInterval(timerRef.current);
  },[playing,movie]);

  const sysDark = window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? true;
  const isDark = theme==="dark"||(theme==="system"&&sysDark);
  const hc = highContrast;
  const T = isDark ? {
    bg:hc?"#000":"#0d1117", surface:hc?"#0a0e14":"#0c1219", surface2:hc?"#000":"#0f0500",
    border:hc?"#3d5166":"#1e293b", border2:hc?"#7a3000":"#431407",
    text:hc?"#fff":"#f1f5f9", textMuted:hc?"#c8daea":"#94a3b8", textDim:hc?"#b0cce0":"#94afc7", textFaint:hc?"#90b4ca":"#7e95a8",
    accent:"#d45b17", accentLt:hc?"#ffe5c0":"#fed7aa", accentDk:"#c2410c", accentBg:hc?"#130800":"#1a0900",
    grad:"linear-gradient(135deg,#ff8f3c 0%,#d45b17 100%)",
    headerBg:hc?"#000":"#0d1117", headerBd:hc?"#3a1800":"#1a0900",
    sheetBg:hc?"#0a0800":"#130800", inputBg:hc?"#0a0800":"#130800",
  } : {
    bg:hc?"#fff":"#f8fafc", surface:hc?"#f0f4f8":"#fff", surface2:hc?"#e2e8f0":"#f1f5f9",
    border:hc?"#475569":"#e2e8f0", border2:hc?"#9a3412":"#fed7aa",
    text:hc?"#000":"#0f172a", textMuted:hc?"#1e293b":"#475569", textDim:hc?"#1e3a50":"#475569", textFaint:hc?"#2d4a60":"#64748b",
    accent:"#d45b17", accentLt:hc?"#7c2d12":"#9a3412", accentDk:"#c2410c", accentBg:hc?"#fff7ed":"#fff7ed",
    grad:"linear-gradient(135deg,#ff8f3c 0%,#d45b17 100%)",
    headerBg:hc?"#fff":"#fff", headerBd:hc?"#cbd5e1":"#e2e8f0",
    sheetBg:hc?"#f8fafc":"#fff", inputBg:hc?"#f0f4f8":"#f8fafc",
  };

  useEffect(()=>{
    if(phase!=="playing"||!movie) return;
    let found=null;
    for(const sc of movie.scenes){
      if(dismissed.has(sc.id)) continue;
      const ts=resolveTs(sc,platform), d=ts.s-elapsed;
      if(elapsed>=ts.s&&elapsed<=ts.e){ found={...sc,...ts,mode:"active"}; break; }
      if(d>0&&d<=warnAheadRef.current){ found={...sc,...ts,mode:"warning",countdown:Math.ceil(d)}; break; }
    }
    setAlertScene(found||null);
    if(found&&found.id!==lastAlertRef.current&&alarmRef.current){
      lastAlertRef.current=found.id;
      if(found.mode==="warning"){ alarm.warning(); if(vibrationRef.current&&navigator.vibrate) navigator.vibrate([150,80,150]); }
      if(found.mode==="active"){  alarm.active();  if(vibrationRef.current&&navigator.vibrate) navigator.vibrate([200,80,200,80,200]); }
    }
    if(!found) lastAlertRef.current=null;
  },[elapsed,phase,dismissed,movie,platform]);

  const nudge = n => { startRef.current-=n*1000; setElapsed(e=>Math.max(0,Math.min(e+n,movie.rt))); showToast((n>0?"+":"")+n+"s applied"); };
  const seekTo = useCallback(sec=>{
    const s=Math.max(0,Math.min(sec,movie?.rt??99999));
    startRef.current=Date.now()-s*1000-totalPausedRef.current;
    if(!playingRef.current) pausedRef.current=Date.now();
    setElapsed(s); lastAlertRef.current=null; setDismissed(new Set());
  },[movie]);
  const parseTime = str => { const p=str.trim().split(":").map(Number); if(p.some(isNaN))return null; if(p.length===2)return p[0]*60+p[1]; if(p.length===3)return p[0]*3600+p[1]*60+p[2]; return null; };

  const handlePlay = () => { alarm.init(); startRef.current=Date.now(); totalPausedRef.current=0; pausedRef.current=null; lastAlertRef.current=null; setElapsed(0); setPlaying(true); setPhase("playing"); setDismissed(new Set()); setAlertScene(null); setScenesOpen(true); };
  const togglePause = () => { if(playingRef.current){pausedRef.current=Date.now();setPlaying(false);}else{if(pausedRef.current){totalPausedRef.current+=Date.now()-pausedRef.current;pausedRef.current=null;}setPlaying(true);} };
  const goHome = () => {
    if(phase==="playing"&&playing){ setConfirmLeave(true); return; }
    goHomeImmediate();
  };
  const goHomeImmediate = () => { setPhase("home"); setPlaying(false); setElapsed(0); setAlertScene(null); setDismissed(new Set()); setMovie(null); setScenesOpen(false); setShowGreen(false); setPlatform(""); setPendingMovie(null); setConfirmLeave(false); };
  const canAccess = (m) => {
    if(isPro||isBetaFree||trialActive) return true;
    if(isGuest && m && guestMovieId === m.id) return true;
    return false;
  };

  const handleGuest = () => {
    if(!pendingMovie) return;
    setGuestMovieId(pendingMovie.id);
    setIsGuest(true);
    try{ localStorage.setItem("fs_gm", pendingMovie.id); }catch(e){}
    apiFetch("/api/guest", {method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ fp: getFP(), movieId: pendingMovie.id })}).catch(()=>{});
    setLoginOpen(false);
    showToast("Guest access granted - 1 free movie", "#22c55e");
    setMovie(pendingMovie); setPhase("platform"); setPendingMovie(null);
  };

  const handleLogin = async (provider) => {
    // Google — redirect to real OAuth flow
    if (provider === "Google") {
      window.location.href = API_BASE + "/api/auth/google/redirect";
      return;
    }
    if(loginMode==="trial") {
      try {
        const res = await apiFetch("/api/auth/trial", {method:"POST",headers:{"Content-Type":"application/json"}});
        const data = await res.json();
        if(data.ok) {
          setTrialActive(true); setTrialUsed(true); setLoginOpen(false);
          showToast("7-day trial activated!",T.accent);
          if(pendingMovie){ setMovie(pendingMovie); setPhase("platform"); setPendingMovie(null); }
          return;
        }
      } catch(e) {}
    }
    if(loginMode==="trial"){
      try{ const fp=getFP(),used=JSON.parse(localStorage.getItem("fs_t")||"{}"); used[fp]=Date.now(); localStorage.setItem("fs_t",JSON.stringify(used)); }catch(e){}
      setTrialUsed(true); setTrialActive(true); setLoginOpen(false);
      showToast("Signed in with "+provider+" — trial active!",T.accent);
      if(pendingMovie){ setMovie(pendingMovie); setPhase("platform"); setPendingMovie(null); }
    } else {
      setIsPro(true); setLoginOpen(false);
      showToast("FilmScout Pro unlocked!",T.accent);
      if(pendingMovie){ setMovie(pendingMovie); setPhase("platform"); setPendingMovie(null); }
    }
  };

  const handleUpgrade = async (plan) => {
    // TODO live: PRICE_IDS must match your Stripe dashboard price IDs
    // plan "monthly" → price_monthly, plan "annual" → price_annual
    setCheckoutLoading(plan);
    try {
      const res = await apiFetch("/api/stripe/create-checkout", {
        method: "POST",
        body: JSON.stringify({ plan, fp: getFP() }),
      });
      const data = await res.json();
      if (data.url) {
        window.location.href = data.url; // redirect to Stripe checkout
      } else if (res.status === 401) {
        setCheckoutLoading(null);
        setUpgradeOpen(false);
        setLoginOpen(true);
        setLoginMode("upgrade");
        showToast("Sign in first to subscribe","#d45b17");
      } else {
        showToast("Could not start checkout — try again","#f87171");
        setCheckoutLoading(null);
      }
    } catch(e) {
      showToast("Network error — try again","#f87171");
      setCheckoutLoading(null);
    }
  };

  const handleBetaAccess = async () => {
    setCheckoutLoading("beta");
    try {
      const res = await apiFetch("/api/auth/beta-access", { method: "POST" });
      if (res.status === 401) {
        setCheckoutLoading(null);
        setUpgradeOpen(false);
        setLoginOpen(true);
        setLoginMode("upgrade");
        showToast("Sign in first","#d45b17");
        return;
      }
      const data = await res.json();
      if (data.ok) {
        setIsBetaFree(true);
        setUpgradeOpen(false);
        showToast("Welcome to the FilmScout beta — thank you for helping us test!","#22c55e");
      } else {
        showToast("Could not activate beta access — try again","#f87171");
      }
    } catch(e) {
      showToast("Network error — try again","#f87171");
    }
    setCheckoutLoading(null);
  };

  const selectMovie = m => { if(canAccess(m)){setMovie(m);setPhase("platform");}else{setPendingMovie(m);setLoginOpen(true);setLoginMode("trial");} };
  const confirmPlatform = p => { setPlatform(p); setPhase("detail"); setScenesOpen(false); setFilterAct([]); setShowGreen(false); };

  const saveUsername = async () => {
    const val = unameInput.toLowerCase().trim();
    if (!/^[a-z0-9_]{3,20}$/.test(val)) { showToast("3–20 chars: lowercase letters, numbers, underscores only","#f87171"); return; }
    const RESERVED = ['admin','filmscout','support','help','api','app','u','join','account','settings','login','signup','register','home','about','terms','privacy'];
    if (RESERVED.includes(val)) { showToast("Reserved username","#f87171"); return; }
    try {
      const r = await apiFetch("/api/account/username",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:val})});
      const d = await r.json();
      if (!r.ok) { showToast(d.error||"Error saving username","#f87171"); return; }
      setUsername(d.username);
      setOldUsernames(d.old_usernames||[]);
      setUnameEdit(false);
      showToast("Username saved","#22c55e");
    } catch(e) { showToast("Network error","#f87171"); }
  };

  const saveEmail2 = async () => {
    const val = emailInput2.toLowerCase().trim();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val)) { showToast("Invalid email address","#f87171"); return; }
    try {
      const r = await apiFetch("/api/account/email",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:val})});
      const d = await r.json();
      if (!r.ok) { showToast(d.error||"Error saving email","#f87171"); return; }
      setCurrentUser(u=>({...u,email:d.email}));
      setOldEmails(d.old_emails||[]);
      setEmailEdit(false);
      showToast("Email updated","#22c55e");
    } catch(e) { showToast("Network error","#f87171"); }
  };

  const savePassword = async () => {
    if (pwNewInput !== pwConfirmInput) { showToast("Passwords don't match","#f87171"); return; }
    if (pwNewInput.length < 8) { showToast("Password must be at least 8 characters","#f87171"); return; }
    setPwSaving(true);
    try {
      const r = await apiFetch("/api/account/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({current:pwCurrentInput,new:pwNewInput})});
      const d = await r.json();
      if (!r.ok) { showToast(d.error||"Error changing password","#f87171"); setPwSaving(false); return; }
      setPwModal(false); setPwCurrentInput(""); setPwNewInput(""); setPwConfirmInput("");
      showToast("Password changed","#22c55e");
    } catch(e) { showToast("Network error","#f87171"); }
    setPwSaving(false);
  };

  const openWithUsernameGate = (mode) => {
    if (!currentUser) { setLoginOpen(true); setLoginMode(null); return; }
    if (!username) { setUnamePromptMode(mode); setUnamePromptInput(''); setUnamePromptOpen(true); return; }
    if (mode === 'feedback') setFeedbackOpen(true);
    if (mode === 'share') handleShare();
  };

  const savePromptUsername = async () => {
    const val = unamePromptInput.toLowerCase().trim();
    if (!/^[a-z0-9_]{3,20}$/.test(val)) { showToast("3–20 chars: lowercase letters, numbers, underscores only","#f87171"); return; }
    const RESERVED = ['admin','filmscout','support','help','api','app','u','join','account','settings','login','signup','register','home','about','terms','privacy'];
    if (RESERVED.includes(val)) { showToast("Reserved username","#f87171"); return; }
    try {
      const r = await apiFetch("/api/account/username",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:val})});
      const d = await r.json();
      if (!r.ok) { showToast(d.error||"Error saving username","#f87171"); return; }
      setUsername(d.username); setOldUsernames(d.old_usernames||[]);
      const mode = unamePromptMode;
      setUnamePromptOpen(false);
      showToast("Username saved","#22c55e");
      if (mode === 'feedback') setFeedbackOpen(true);
      if (mode === 'share') handleShare();
    } catch(e) { showToast("Network error","#f87171"); }
  };

  const handleDeleteAccount = async () => {
    if (deleteConfirmInput !== "DELETE") return;
    try {
      const r = await apiFetch("/api/account",{method:"DELETE",credentials:"include"});
      const d = await r.json();
      if (!r.ok) { showToast(d.error||"Error deleting account","#f87171"); return; }
      try{ Object.keys(localStorage).filter(k=>k.startsWith("fs_")).forEach(k=>localStorage.removeItem(k)); }catch(e){}
      setIsPro(false); setIsBetaFree(false); setTrialActive(false); setCurrentUser(null); setIsGuest(false);
      setCorrections([]); setIsMod(false); setUsername(null); setOldUsernames([]); setOldEmails([]); setHasPassword(false);
      setUnameEdit(false); setEmailEdit(false); setDeleteConfirmOpen(false); setDeleteConfirmInput("");
      setPhase("home"); showToast("Account deleted","#94a3b8");
    } catch(e) { showToast("Network error","#f87171"); }
  };

  const handleShare = async () => {
    const url = username ? `https://getfilmscout.com/u/${username}` : refUrl;
    const text = "I'm using FilmScout to watch movies with my kids — check it out:";
    if (navigator.share) {
      try { await navigator.share({ title:"FilmScout", text, url }); }
      catch(e) { if(e.name!=="AbortError") showToast("Could not open share sheet","#f87171"); }
    } else {
      try { await navigator.clipboard.writeText(url); showToast("Link copied to clipboard","#22c55e"); }
      catch(e) { showToast("Copy: "+url,"#d45b17"); }
    }
  };

  const openTsEdit = (sc) => {
    const ts = resolveTs(sc, platform);
    const allScenes = [...(movie?.scenes||[]), ...(movie?.green||[])]
      .sort((a,b) => resolveTs(a,platform).s - resolveTs(b,platform).s);
    const idx = allScenes.findIndex(s => s.id === sc.id && s.a === sc.a);
    const prevSc = idx > 0 ? allScenes[idx-1] : null;
    const nextSc = idx < allScenes.length-1 ? allScenes[idx+1] : null;
    setTsNeighbors({
      prev: prevSc ? { title: prevSc.t, end: fmt(resolveTs(prevSc,platform).e), endS: resolveTs(prevSc,platform).e } : null,
      next: nextSc ? { title: nextSc.t, start: fmt(resolveTs(nextSc,platform).s), startS: resolveTs(nextSc,platform).s } : null,
    });
    setTsScene(sc); setTsPlatform(platform||"default"); setTsType([]); setTsStart(fmt(ts.s)); setTsEnd(fmt(ts.e)); setTsOpen(true);
  };

  const submitTs = () => {
    const s=parseTime(tsStart), e=parseTime(tsEnd);
    if(s===null||e===null||e<=s){ showToast("Invalid timestamps","#f87171"); return; }
    const corr = {
      id: Date.now(), movieId: movie.id, movieTitle: movie.title,
      sceneId: tsScene.id, sceneTitle: tsScene.t,
      scene_type: tsScene.a === GL ? "green" : "flagged",
      platform: tsPlatform, types: tsType, newStart: s, newEnd: e,
      note: "", submittedBy: isPro?"pro":"user", status:"pending",
    };
    const updated = [...corrections, corr];
    setCorrections(updated);
    try{ localStorage.setItem("fs_c", JSON.stringify(updated)); }catch(e){}
    apiFetch("/api/corrections", {
      method:"POST", headers:{"Content-Type":"application/json"},
      body: JSON.stringify(corr)
    }).catch(()=>{});
    setMovies(prev=>prev.map(m=>{ if(m.id!==movie.id)return m; return {...m,scenes:m.scenes.map(sc=>sc.id!==tsScene.id?sc:{...sc,verified_by:isPro?"pro":"user"})}; }));
    if(movie) setMovie(prev=>({...prev,scenes:prev.scenes.map(sc=>sc.id!==tsScene.id?sc:{...sc,verified_by:isPro?"pro":"user"})}));
    setTsOpen(false); showToast("Correction submitted — thank you!","#22c55e");
  };

  const pct = movie ? Math.min(elapsed/movie.rt,1)*100 : 0;

  const filteredMovies = movies.filter(m=>{
    if(search && !m.title.toLowerCase().includes(search.toLowerCase()) && !(m.sub||"").toLowerCase().includes(search.toLowerCase())) return false;
    if(genre.length>0 && !genre.includes(genreOf(m))) return false;
    if(service.length>0 && !(m.stream||[]).some(s=>service.includes(s))) return false;
    return true;
  });

  const allConversations = {
    SKIP:      { type:"SKIP",      q:"Why did we skip that part?",              a:"Some scenes can be scary or confusing. We can talk about what happened in the story without watching those parts." },
    MUTE:      { type:"MUTE",      q:"Why did we mute the sound?",              a:"Sometimes people in movies say things we don't want filling our home. The story is still great — we just chose not to hear that part." },
    "HEADS UP":{ type:"HEADS UP",  q:"That scene looked intense — is everything okay?", a:"Yes! It was intense, but it's all made up. The actors are safe. Feeling a little uneasy during movies is totally normal." },
    "ALL CLEAR":{ type:"ALL CLEAR",q:"I loved that happy part!",                a:"Me too! What was your favorite moment so far?" },
  };
  const conversations = movie
    ? [...new Set(movie.scenes.map(s=>s.a))].map(a=>allConversations[a]).filter(Boolean)
    : [];

  return (
    <div style={{background:T.bg,minHeight:"100vh"}}>
    <div style={{fontFamily:"-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif",background:T.bg,color:T.text,minHeight:"100vh",maxWidth:500,margin:"0 auto",position:"relative",overflowX:"hidden",overflowY:"auto",paddingBottom:80}}>
      <style>{`
        html, body { overflow: auto !important; height: auto !important; }
        @keyframes sheet-up { from { transform: translateY(100%); } to { transform: translateY(0); } }
        @keyframes pulse-glow { 0%,100% { box-shadow: 0 0 0 0 rgba(212,91,23,0); } 50% { box-shadow: 0 0 0 8px rgba(212,91,23,0.15); } }
        @keyframes alert-pulse { 0%,100% { opacity:1; } 50% { opacity:0.7; } }
        @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes alert-slide-in { from { opacity:0; transform:translateY(-10px); } to { opacity:1; transform:translateY(0); } }
        @keyframes toast-up { from { opacity:0; transform:translateX(-50%) translateY(8px); } to { opacity:1; transform:translateX(-50%) translateY(0); } }
        @keyframes fade-in-up { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:translateY(0); } }
        @keyframes minute-tick { 0% { opacity:1; } 15% { opacity:0.55; } 30% { opacity:1; } }
        * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        input, button { font-family: inherit; }
        button { transition: transform 0.12s cubic-bezier(0.34,1.56,0.64,1); }
        button:active { transform: scale(0.97); }
        ::-webkit-scrollbar { width: 4px; height: 0px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #334155; border-radius: 2px; }
        .pill-row { scrollbar-width: none; -ms-overflow-style: none; }
        .pill-row::-webkit-scrollbar { display: none; }
      `}</style>

      {/* Header */}
      <div style={{position:"sticky",top:0,zIndex:100,background:T.headerBg,borderBottom:"1px solid "+T.headerBd,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12}}>
        <button onClick={goHome} style={{background:"none",border:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:8,padding:0,color:T.text}}>
          <Logo size={28} gid="hdr"/>
          <span style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:16,color:T.text}}>Film<span style={{color:T.accent}}>Scout</span></span>
        </button>
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          {(isPro||isBetaFree||trialActive) ? (
            <span style={{fontSize:10,fontWeight:700,color:T.accent,background:T.accentBg,border:"1px solid "+T.accent+"40",borderRadius:20,padding:"3px 8px"}}>{isPro?"PRO":isBetaFree?"BETA":"TRIAL"}</span>
          ) : (
            <button onClick={()=>{ if(!currentUser){setLoginOpen(true);setLoginMode("upgrade");}else setUpgradeOpen(true); }} style={{fontSize:10,fontWeight:700,color:"#fff",background:T.grad,border:"none",borderRadius:20,padding:"4px 10px",cursor:"pointer"}}>Get Pro</button>
          )}
          {!currentUser && (
            <button onClick={()=>{setLoginOpen(true);setLoginMode(null);}} style={{fontSize:12,fontWeight:600,color:T.accent,background:"transparent",border:"1px solid "+T.accent+"60",borderRadius:8,padding:"5px 10px",cursor:"pointer"}}>Sign In</button>
          )}
          <button onClick={()=>setPhase(phase==="settings"?"home":"settings")} style={{background:T.surface,border:"1px solid "+T.border,borderRadius:8,width:32,height:32,display:"flex",alignItems:"center",justifyContent:"center",color:phase==="settings"?T.accent:T.textDim,cursor:"pointer"}}>{phase==="settings"?IC.home:IC.settings}</button>
        </div>
      </div>

      {/* Toast */}
      {toast && (
        <div style={{position:"fixed",top:64,left:"50%",background:toast.color,color:"#fff",borderRadius:20,padding:"8px 18px",fontSize:13,fontWeight:600,zIndex:999,whiteSpace:"nowrap",boxShadow:"0 4px 20px rgba(0,0,0,0.3)",pointerEvents:"none",animation:"toast-up 0.25s cubic-bezier(0.34,1.56,0.64,1) forwards"}}>
          {toast.msg}
        </div>
      )}

      {/* Disclaimer — first-run modal */}
      {showDisclaimer && (
        <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.8)",zIndex:300,display:"flex",alignItems:"center",justifyContent:"center",padding:"24px"}}>
          <div style={{background:T.sheetBg,border:"1px solid "+T.border,borderRadius:20,padding:"28px 24px",maxWidth:400,width:"100%"}}>
            <div style={{display:"flex",alignItems:"center",gap:12,marginBottom:16}}>
              <Logo size={48} gid="wlc"/>
              <div>
                <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:22,color:T.text,lineHeight:1.1}}>Film<span style={{color:T.accent}}>Scout</span></div>
                <div style={{fontSize:12,color:T.textDim,marginTop:2}}>Family-safe movie companion</div>
              </div>
            </div>
            <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:17,color:T.text,marginBottom:10}}>👋 Welcome</div>
            <div style={{fontSize:13,color:T.textDim,lineHeight:1.7,marginBottom:10}}>FilmScout counts up from zero alongside your movie. Tap <strong style={{color:T.text}}>"I'm pressing Play"</strong> the moment your movie starts on TV and we'll alert you before flagged scenes arrive.</div>
            <div style={{fontSize:12,color:T.textFaint,lineHeight:1.6,marginBottom:20}}>⏱ Timestamps are community-sourced and approximate. The more families use FilmScout, the more accurate they become.</div>
            <label style={{display:"flex",alignItems:"center",gap:10,marginBottom:16,cursor:"pointer"}}>
              <input type="checkbox" id="disc-check" style={{width:16,height:16,accentColor:T.accent,cursor:"pointer"}}/>
              <span style={{fontSize:12,color:T.textDim}}>Don't show this again</span>
            </label>
            <button onClick={()=>{
              const checked=document.getElementById("disc-check")?.checked;
              setShowDisclaimer(false);
              if(checked){try{localStorage.setItem('fs_disc','1');}catch(e){}}
            }} style={{background:T.grad,border:"none",borderRadius:10,padding:"13px 0",color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer",width:"100%"}}>Got it — Let's Browse</button>
          </div>
        </div>
      )}

      {/* Home */}
      {phase==="home" && (
        <div style={{padding:"12px 16px 100px"}}>
          <div style={{display:"flex",gap:8,marginBottom:12,alignItems:"center"}}>
            <div style={{flex:1,position:"relative"}}>
              <span style={{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:T.textFaint,pointerEvents:"none"}}>{IC.search}</span>
              <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search movies…" style={{width:"100%",paddingLeft:30,paddingRight:12,paddingTop:9,paddingBottom:9,borderRadius:10,border:"1px solid "+T.border,background:T.surface,color:T.text,fontSize:13,outline:"none"}}/>
            </div>
            <button onClick={()=>setRequestOpen(true)} style={{flexShrink:0,background:T.surface,border:"1px solid "+T.border,borderRadius:10,padding:"9px 12px",color:T.textDim,fontSize:11,cursor:"pointer",display:"flex",alignItems:"center",gap:5,fontWeight:600,whiteSpace:"nowrap"}}>
              {IC.film} Request
            </button>
          </div>

          {/* Genre filter */}
          <div className="pill-row" style={{display:"flex",gap:6,overflowX:"auto",marginBottom:10,paddingBottom:2}}>
            {GENRES.map(g=>{
              const [ct,cb,cbr]=GENRE_COLOR[g]||["#94a3b8","transparent","#334155"];
              const isAll=g==="All";
              const active=isAll?genre.length===0:genre.includes(g);
              const toggle=()=>{
                if(isAll){setGenre([]);return;}
                setGenre(f=>f.includes(g)?f.filter(x=>x!==g):[...f,g]);
              };
              return <button key={g} onClick={toggle} style={{flexShrink:0,padding:"5px 11px",borderRadius:20,border:"2px solid "+(active?(isAll?T.accent:cbr):"transparent"),background:active?(isAll?T.accentBg:(isDark?cb:cbr+"22")):T.surface,color:active?(isAll?T.accent:ct):T.textDim,fontSize:11,fontWeight:active?700:500,cursor:"pointer",transition:"all 0.15s",outline:active?"none":"1px solid "+T.border,outlineOffset:-1}}>{g}</button>;
            })}
          </div>

          {/* Service filter */}
          <div className="pill-row" style={{display:"flex",gap:6,overflowX:"auto",marginBottom:14,paddingBottom:2}}>
            {SERVICES.map(sv=>{
              const [ct,cb,cbr,icon]=getSVC(sv,isDark);
              const isAll=sv==="All";
              const active=isAll?service.length===0:service.includes(sv);
              const toggle=()=>{
                if(isAll){setService([]);return;}
                setService(f=>f.includes(sv)?f.filter(x=>x!==sv):[...f,sv]);
              };
              return <button key={sv} onClick={toggle} style={{flexShrink:0,padding:"5px 10px",borderRadius:20,border:"2px solid "+(active?(isAll?T.accent:cbr):"transparent"),background:active?(isAll?T.accentBg:cb):T.surface,color:active?(isAll?T.accent:ct):T.textDim,fontSize:11,fontWeight:active?700:500,cursor:"pointer",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s",outline:active?"none":"1px solid "+T.border,outlineOffset:-1}}>
                {icon&&<span style={{fontSize:12}}>{icon}</span>}{sv}
              </button>;
            })}
          </div>

          {loading ? (
            <div style={{textAlign:"center",padding:"40px 0",color:T.textDim}}>
              <div style={{width:24,height:24,border:"2px solid "+T.border,borderTopColor:T.accent,borderRadius:"50%",animation:"spin 0.8s linear infinite",margin:"0 auto 12px"}}/>
              <div style={{fontSize:13}}>Loading movies…</div>
            </div>
          ) : filteredMovies.length === 0 ? (
            <div style={{textAlign:"center",padding:"40px 0",color:T.textDim}}>
              <div style={{fontSize:32,marginBottom:8}}>🎬</div>
              <div style={{fontSize:14,fontWeight:600,marginBottom:4}}>No movies found</div>
              <div style={{fontSize:12}}>Try a different search or filter</div>
            </div>
          ) : (
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
              {filteredMovies.map(m=>(
                <MovieCard key={m.id} movie={m} onSelect={selectMovie}
                  locked={!canAccess(m)&&!(guestMovieId===m.id)}
                  isGuestMovie={guestMovieId===m.id&&!isPro&&!isBetaFree&&!trialActive}
                  T={T} isDark={isDark}/>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Platform selection */}
      {phase==="platform" && movie && (
        <div style={{padding:"16px 16px 100px"}}>
          <button onClick={goHome} style={{background:"none",border:"none",color:T.textDim,cursor:"pointer",fontSize:13,display:"flex",alignItems:"center",gap:6,marginBottom:16,padding:0}}>← Back</button>
          <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,marginBottom:4,color:T.text}}>{movie.title}{movie.sub&&<span style={{color:T.accent}}> {movie.sub}</span>}</div>
          <div style={{fontSize:12,color:T.textDim,marginBottom:20}}>Choose the service you're watching on to get accurate timestamps</div>
          <div style={{display:"flex",flexDirection:"column",gap:10}}>
            {SERVICES.filter(sv=>sv!=="All").map((sv,i)=>{
              const [ct,cb,cbr,icon]=getSVC(sv,isDark);
              const known=(movie.stream||[]).includes(sv);
              return (
                <button key={sv} onClick={()=>confirmPlatform(sv)}
                  style={{background:isDark?cb:T.surface,border:"2px solid "+(known?cbr:T.border),borderRadius:12,padding:"14px 16px",display:"flex",alignItems:"center",gap:12,cursor:"pointer",transition:"border-color 0.15s, transform 0.15s cubic-bezier(0.34,1.56,0.64,1)",color:T.text,textAlign:"left",animation:`fade-in-up 0.3s ease both`,animationDelay:`${i*0.05}s`}}
                  onMouseEnter={e=>{e.currentTarget.style.borderColor=cbr;e.currentTarget.style.transform="translateY(-1px)";}}
                  onMouseLeave={e=>{e.currentTarget.style.borderColor=known?cbr:T.border;e.currentTarget.style.transform="";}}>
                  <span style={{fontSize:24}}>{icon}</span>
                  <div>
                    <div style={{fontWeight:700,fontSize:14,color:ct}}>{sv}</div>
                    <div style={{fontSize:11,color:T.textDim,marginTop:2}}>{known?"Platform-accurate timestamps":"Default timestamps"}</div>
                  </div>
                  <span style={{marginLeft:"auto",color:T.textDim}}>{IC.arrowR}</span>
                </button>
              );
            })}
            <button onClick={()=>confirmPlatform("default")}
              style={{background:T.surface,border:"1px dashed "+T.border,borderRadius:12,padding:"14px 16px",display:"flex",alignItems:"center",gap:12,cursor:"pointer",color:T.text,textAlign:"left"}}>
              <span style={{fontSize:20}}>📺</span>
              <div>
                <div style={{fontWeight:600,fontSize:13,color:T.textMuted}}>Other / Unknown</div>
                <div style={{fontSize:11,color:T.textDim,marginTop:2}}>Use default timestamps</div>
              </div>
              <span style={{marginLeft:"auto",color:T.textDim}}>{IC.arrowR}</span>
            </button>
          </div>
        </div>
      )}

      {/* Detail / scene list */}
      {phase==="detail" && movie && (
        <div style={{padding:"16px 16px 100px"}}>
          <button onClick={()=>setPhase("platform")} style={{background:"none",border:"none",color:T.textDim,cursor:"pointer",fontSize:13,display:"flex",alignItems:"center",gap:6,marginBottom:16,padding:0}}>← Back</button>

          <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:16}}>
            <div>
              <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:20,color:T.text,lineHeight:1.2}}>{movie.title}</div>
              {movie.sub&&<div style={{fontFamily:"Georgia,serif",fontSize:16,color:T.accent,marginTop:2}}>{movie.sub}</div>}
              <div style={{fontSize:12,color:T.textDim,marginTop:4}}>{movie.year} · {movie.genre} · {platform}</div>
            </div>
            <div style={{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:6}}>
              <button onClick={handlePlay} style={{background:T.grad,border:"none",borderRadius:10,padding:"10px 18px",color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer",flexShrink:0,display:"flex",alignItems:"center",gap:6,animation:"pulse-glow 2s ease infinite"}}>
                ▶ I'm pressing Play
              </button>
              <span style={{fontSize:10,color:T.textFaint,textAlign:"right"}}>Tap once your TV starts playing</span>
            </div>
          </div>

          {/* Safe scenes pill toggle */}
          <div style={{display:"flex",gap:6,alignItems:"center",marginBottom:12}}>
            <button onClick={()=>setShowGreen(g=>!g)}
              style={{padding:"5px 14px",borderRadius:20,border:"2px solid "+(showGreen?"#22c55e":"transparent"),background:showGreen?(isDark?"#061208":"#f0fdf4"):T.surface,color:showGreen?(isDark?"#86efac":"#166534"):T.textDim,fontSize:11,fontWeight:700,cursor:"pointer",outline:showGreen?"none":"1px solid "+T.border,outlineOffset:-1,transition:"all 0.15s"}}>
              ✅ Show Safe Scenes
            </button>
            <span style={{fontSize:11,color:T.textFaint}}>family-friendly, no flags</span>
          </div>

          {/* Unified scene list */}
          <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginBottom:12}}>
            <div style={{padding:"12px 16px",borderBottom:"1px solid "+T.border,display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <div style={{fontWeight:700,fontSize:13,color:T.text}}>{showGreen?"🎬 All Scenes":"⚠️ Flagged Scenes"}</div>
              <span style={{fontSize:11,color:T.textDim}}>{movie.scenes.length} scenes{showGreen?" + "+(movie.green?.length||0)+" safe":""}</span>
            </div>
            <div style={{padding:"0 16px"}}>
              {(()=>{
                if(!showGreen) {
                  if(movie.scenes.length===0) return <div style={{padding:"20px 0",textAlign:"center",fontSize:12,color:T.textDim}}>✅ No flagged scenes for this movie</div>;
                  return movie.scenes.map(sc=><SceneRow key={sc.id} sc={sc} platform={platform} onEdit={openTsEdit} T={T} isDark={isDark}/>);
                }
                const all=[...(movie.scenes||[]).map(s=>({...s,_type:"flagged"})),...(movie.green||[]).map(s=>({...s,_type:"green"}))].sort((a,b)=>resolveTs(a,platform).s-resolveTs(b,platform).s);
                return all.map((sc,i)=>sc._type==="green"?(
                  <div key={"g"+sc.id} style={{display:"flex",gap:8,padding:"9px 0",borderBottom:"1px solid "+T.border}}>
                    <div style={{background:isDark?"#22c55e":"#dcfce7",color:isDark?"#000":"#166534",border:isDark?"none":"1px solid #22c55e50",borderRadius:4,padding:"2px 6px",fontSize:10,fontWeight:800,whiteSpace:"nowrap",flexShrink:0,marginTop:1}}>✅ ALL CLEAR</div>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{display:"flex",justifyContent:"space-between",gap:4}}>
                        <div style={{fontSize:12,fontWeight:600,color:isDark?"#86efac":"#166534"}}>{sc.t}</div>
                        <div style={{display:"flex",alignItems:"flex-start",gap:6,flexShrink:0}}>
                          <div style={{textAlign:"right"}}>
                            <div style={{fontSize:11,fontFamily:"monospace",color:"#94afc7"}}>{fmt(resolveTs(sc,platform).s)} →</div>
                            <div style={{fontSize:11,fontFamily:"monospace",color:"#22c55e",fontWeight:700}}>{fmt(resolveTs(sc,platform).e)}</div>
                          </div>
                          <button onClick={()=>openTsEdit(sc)} style={{background:"none",border:"1px solid "+T.border,borderRadius:6,minWidth:32,minHeight:32,display:"flex",alignItems:"center",justifyContent:"center",color:"#22c55e",cursor:"pointer",flexShrink:0}}>{IC.pencil}</button>
                        </div>
                      </div>
                    </div>
                  </div>
                ):<SceneRow key={sc.id} sc={sc} platform={platform} onEdit={openTsEdit} T={T} isDark={isDark}/>);
              })()}
            </div>
          </div>

          {/* Timestamps disclaimer */}
          <div style={{display:"flex",gap:6,alignItems:"flex-start",padding:"8px 4px",marginBottom:4}}>
            <span style={{fontSize:13,flexShrink:0}}>⏱</span>
            <span style={{fontSize:11,color:T.textFaint,lineHeight:1.5}}>Timestamps are approximate and community-sourced. The more families use FilmScout, the more accurate they get.</span>
          </div>
          <div style={{fontSize:'11px',opacity:0.5,marginTop:'8px',textAlign:'center'}}>
            Streaming data powered by <a href="https://www.watchmode.com" target="_blank" rel="noopener noreferrer" style={{color:'inherit',textDecoration:'underline'}}>Watchmode.com</a>
          </div>

          {/* Conversation starters */}
          <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginTop:12}}>
            <div style={{padding:"12px 16px",borderBottom:"1px solid "+T.border}}>
              <div style={{fontWeight:700,fontSize:13,color:T.text}}>💬 Conversation Starters</div>
              <div style={{fontSize:11,color:T.textDim,marginTop:2}}>Use these to talk through tough scenes with your kids</div>
            </div>
            <div style={{padding:"8px 0"}}>
              {conversations.map((c,i)=>(
                <div key={i} style={{padding:"10px 16px",borderBottom:i<conversations.length-1?"1px solid "+T.border:"none"}}>
                  <div style={{fontSize:11,fontWeight:700,color:T.accent,marginBottom:3}}>{ICON[c.type]||"💬"} {c.type}</div>
                  <div style={{fontSize:12,color:T.text,fontWeight:600,marginBottom:3}}>"{c.q}"</div>
                  <div style={{fontSize:11,color:T.textDim,lineHeight:1.5}}>{c.a}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Playing view */}
      {phase==="playing" && movie && (
        <div style={{padding:"16px 16px 100px"}}>
          {/* Alert Banner */}
          {alertScene && (
            <div style={{
              background:(isDark?STYLE_D:STYLE_L)[alertScene.a]?.bg,
              border:"2px solid "+(isDark?STYLE_D:STYLE_L)[alertScene.a]?.border,
              borderRadius:16,padding:"16px",marginBottom:16,
              animation:alertScene.mode==="active"?"alert-slide-in 0.3s cubic-bezier(0.34,1.56,0.64,1), alert-pulse 1s ease 0.3s infinite":"alert-slide-in 0.3s cubic-bezier(0.34,1.56,0.64,1)"
            }}>
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:8}}>
                <div style={{display:"flex",alignItems:"center",gap:8}}>
                  <span style={{fontSize:20}}>{ICON[alertScene.a]}</span>
                  <div>
                    <div style={{fontWeight:800,fontSize:15,color:(isDark?STYLE_D:STYLE_L)[alertScene.a]?.text}}>
                      {alertScene.mode==="warning"?`${alertScene.countdown}s — ${alertScene.a}`:`NOW: ${alertScene.a}`}
                    </div>
                    <div style={{fontSize:12,color:(isDark?STYLE_D:STYLE_L)[alertScene.a]?.text,opacity:0.8,marginTop:2}}>{alertScene.t}</div>
                  </div>
                </div>
                <button onClick={()=>setDismissed(d=>new Set([...d,alertScene.id]))}
                  style={{background:"none",border:"1px solid "+(isDark?STYLE_D:STYLE_L)[alertScene.a]?.border,borderRadius:6,padding:"4px 10px",color:(isDark?STYLE_D:STYLE_L)[alertScene.a]?.text,fontSize:11,cursor:"pointer"}}>
                  Dismiss
                </button>
              </div>
              {alertScene.d && <div style={{fontSize:11,color:(isDark?STYLE_D:STYLE_L)[alertScene.a]?.text,opacity:0.75,marginBottom:8}}>{alertScene.d}</div>}
              <div style={{display:"flex",gap:6}}>
                <div style={{fontSize:11,fontFamily:"monospace",color:(isDark?STYLE_D:STYLE_L)[alertScene.a]?.text,opacity:0.8}}>
                  {LABEL[alertScene.a]}: {fmt(alertScene.e)}
                </div>
              </div>
            </div>
          )}

          {/* Timer */}
          <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:16,padding:"20px",marginBottom:16,textAlign:"center"}}>
            <div key={Math.floor(elapsed/60)} style={{fontSize:48,fontFamily:"monospace",fontWeight:700,color:T.text,letterSpacing:"0.05em",lineHeight:1,animation:elapsed>0?"minute-tick 0.6s ease":"none"}}>
              {fmt(elapsed)}
            </div>
            <div style={{fontSize:12,color:T.textDim,marginTop:6}}>{movie.title}{movie.sub?" "+movie.sub:""} · {platform}</div>
          </div>

          {/* Progress bar */}
          <div style={{marginBottom:16}}>
            <div
              style={{height:6,background:T.border,borderRadius:3,cursor:"pointer",position:"relative"}}
              onClick={e=>{
                const r=e.currentTarget.getBoundingClientRect();
                seekTo(((e.clientX-r.left)/r.width)*movie.rt);
              }}>
              <div style={{height:"100%",width:pct+"%",background:T.grad,borderRadius:3,transition:"width 0.1s linear"}}/>
              {/* Scene markers */}
              {movie.scenes.map(sc=>{
                const ts=resolveTs(sc,platform);
                const x=(ts.s/movie.rt)*100;
                const col=(isDark?STYLE_D:STYLE_L)[sc.a]?.border||"#d45b17";
                return <div key={sc.id} style={{position:"absolute",top:-2,width:3,height:10,background:col,borderRadius:1,left:x+"%",transform:"translateX(-50%)"}}/>;
              })}
            </div>
            <div style={{display:"flex",justifyContent:"space-between",marginTop:4}}>
              <span style={{fontSize:10,fontFamily:"monospace",color:T.textFaint}}>{fmt(elapsed)}</span>
              <span style={{fontSize:10,fontFamily:"monospace",color:T.textFaint}}>{fmt(movie.rt)}</span>
            </div>
          </div>

          {/* Controls */}
          <div style={{display:"flex",gap:8,justifyContent:"center",marginBottom:12}}>
            <button onClick={()=>nudge(-30)} style={{background:T.surface,border:"1px solid "+T.border,borderRadius:10,padding:"10px 14px",color:T.textDim,fontSize:12,cursor:"pointer",fontWeight:600}}>-30s</button>
            <button onClick={()=>nudge(-10)} style={{background:T.surface,border:"1px solid "+T.border,borderRadius:10,padding:"10px 14px",color:T.textDim,fontSize:12,cursor:"pointer",fontWeight:600}}>-10s</button>
            <button onClick={togglePause} style={{background:T.grad,border:"none",borderRadius:10,padding:"10px 24px",color:"#fff",fontSize:14,cursor:"pointer",fontWeight:700,minWidth:70}}>
              {playing ? "⏸" : "▶"}
            </button>
            <button onClick={()=>nudge(10)} style={{background:T.surface,border:"1px solid "+T.border,borderRadius:10,padding:"10px 14px",color:T.textDim,fontSize:12,cursor:"pointer",fontWeight:600}}>+10s</button>
            <button onClick={()=>nudge(30)} style={{background:T.surface,border:"1px solid "+T.border,borderRadius:10,padding:"10px 14px",color:T.textDim,fontSize:12,cursor:"pointer",fontWeight:600}}>+30s</button>
          </div>

          {/* Manual seek + resync */}
          <div style={{display:"flex",gap:8,marginBottom:12}}>
            <input value={manualTime} onChange={e=>setManualTime(e.target.value)} placeholder="Jump to… (e.g. 1:23:45)"
              style={{flex:1,padding:"9px 12px",borderRadius:10,border:"1px solid "+T.border,background:T.surface,color:T.text,fontSize:13,outline:"none"}}/>
            <button onClick={()=>{const s=parseTime(manualTime);if(s!==null){seekTo(s);setManualTime("");}else showToast("Invalid time","#f87171");}}
              style={{padding:"9px 16px",borderRadius:10,border:"none",background:T.grad,color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer"}}>Go</button>
            <button onClick={()=>setResyncOpen(true)}
              style={{padding:"9px 12px",borderRadius:10,border:"1px solid "+T.border,background:T.surface,color:T.textDim,cursor:"pointer"}}>{IC.resync}</button>
          </div>

          {/* Upcoming scenes */}
          <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:12,overflow:"hidden"}}>
            <div style={{padding:"10px 14px",borderBottom:"1px solid "+T.border,display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <span style={{fontSize:12,fontWeight:700,color:T.text}}>Upcoming Scenes</span>
              <button onClick={()=>setScenesOpen(s=>!s)} style={{background:"none",border:"none",color:T.textDim,fontSize:11,cursor:"pointer"}}>{scenesOpen?"Hide":"Show"}</button>
            </div>
            {scenesOpen && (
              <div style={{padding:"0 14px",maxHeight:250,overflowY:"auto"}}>
                {movie.scenes.filter(sc=>resolveTs(sc,platform).s>elapsed).slice(0,5).map(sc=>(
                  <SceneRow key={sc.id} sc={sc} platform={platform} onEdit={openTsEdit} T={T} isDark={isDark}/>
                ))}
                {movie.scenes.filter(sc=>resolveTs(sc,platform).s>elapsed).length===0 && (
                  <div style={{padding:"16px 0",textAlign:"center",fontSize:12,color:T.textDim}}>✅ No more flagged scenes ahead</div>
                )}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Settings */}
      {phase==="settings" && (
        <div style={{padding:"16px 16px 80px"}}>
          <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,marginBottom:16,color:T.text}}>Settings</div>

          {/* Theme */}
          <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginBottom:16}}>
            <div style={{padding:"14px 16px",borderBottom:"1px solid "+T.border}}><div style={{fontWeight:700,fontSize:13,color:T.text}}>Appearance</div></div>
            <div style={{padding:"14px 16px",display:"flex",gap:8}}>
              {["dark","light","system"].map(t=>(
                <button key={t} onClick={()=>setTheme(t)} style={{flex:1,padding:"9px 0",borderRadius:8,border:"1px solid "+(theme===t?T.accent:T.border),background:theme===t?T.accentBg:T.surface2,color:theme===t?T.accent:T.textDim,fontSize:12,fontWeight:theme===t?700:500,cursor:"pointer",textTransform:"capitalize"}}>{t}</button>
              ))}
            </div>
            <div style={{padding:"0 16px 14px",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <span style={{fontSize:13,color:T.text}}>High Contrast</span>
              <button onClick={()=>setHighContrast(h=>!h)} style={{width:44,height:24,borderRadius:12,border:"none",background:highContrast?T.accent:T.border,cursor:"pointer",position:"relative",transition:"background 0.2s"}}>
                <div style={{position:"absolute",top:2,left:highContrast?22:2,width:20,height:20,borderRadius:"50%",background:"#fff",transition:"left 0.2s"}}/>
              </button>
            </div>
            <div style={{padding:"0 16px 14px",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <div>
                <div style={{fontSize:13,color:T.text}}>Welcome Screen</div>
                <div style={{fontSize:11,color:T.textDim}}>Show on next open</div>
              </div>
              <button onClick={()=>{try{localStorage.removeItem('fs_disc');}catch(e){}showToast("Welcome screen will show on next open","#22c55e");}} style={{padding:"5px 12px",borderRadius:20,border:"1px solid "+T.border,background:T.surface2,color:T.textDim,fontSize:11,fontWeight:600,cursor:"pointer"}}>Reset</button>
            </div>
          </div>

          {/* Alerts */}
          <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginBottom:16}}>
            <div style={{padding:"14px 16px",borderBottom:"1px solid "+T.border}}><div style={{fontWeight:700,fontSize:13,color:T.text}}>Alerts</div></div>
            <div style={{padding:"14px 16px",display:"flex",justifyContent:"space-between",alignItems:"center",borderBottom:"1px solid "+T.border}}>
              <div>
                <div style={{fontSize:13,color:T.text}}>Sound Alarm</div>
                <div style={{fontSize:11,color:T.textDim}}>Audio beep before scenes</div>
              </div>
              <button onClick={()=>setAlarmOn(a=>!a)} style={{width:44,height:24,borderRadius:12,border:"none",background:alarmOn?T.accent:T.border,cursor:"pointer",position:"relative",transition:"background 0.2s"}}>
                <div style={{position:"absolute",top:2,left:alarmOn?22:2,width:20,height:20,borderRadius:"50%",background:"#fff",transition:"left 0.2s"}}/>
              </button>
            </div>
            <div style={{padding:"14px 16px",display:"flex",justifyContent:"space-between",alignItems:"center",borderBottom:"1px solid "+T.border}}>
              <div>
                <div style={{fontSize:13,color:T.text}}>Vibration</div>
                <div style={{fontSize:11,color:T.textDim}}>Haptic feedback on mobile</div>
              </div>
              <button onClick={()=>setVibrationOn(v=>!v)} style={{width:44,height:24,borderRadius:12,border:"none",background:vibrationOn?T.accent:T.border,cursor:"pointer",position:"relative",transition:"background 0.2s"}}>
                <div style={{position:"absolute",top:2,left:vibrationOn?22:2,width:20,height:20,borderRadius:"50%",background:"#fff",transition:"left 0.2s"}}/>
              </button>
            </div>
            <div style={{padding:"14px 16px"}}>
              <div style={{fontSize:13,color:T.text,marginBottom:8}}>Warn Ahead</div>
              <div style={{display:"flex",gap:8}}>
                {[15,30,60].map(s=>(
                  <button key={s} onClick={()=>setWarnAhead(s)} style={{flex:1,padding:"8px 0",borderRadius:8,border:"1px solid "+(warnAhead===s?T.accent:T.border),background:warnAhead===s?T.accentBg:T.surface2,color:warnAhead===s?T.accent:T.textDim,fontSize:12,fontWeight:warnAhead===s?700:500,cursor:"pointer"}}>{s}s</button>
                ))}
              </div>
            </div>
          </div>

          {/* Account */}
          <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginBottom:16}}>
            <div style={{padding:"14px 16px",borderBottom:"1px solid "+T.border}}><div style={{fontWeight:700,fontSize:13,color:T.text}}>Account</div></div>
            <div style={{padding:"14px 16px"}}>
              {isPro ? (
                <div style={{fontSize:13,color:"#22c55e",fontWeight:600,marginBottom:10}}>✓ FilmScout Pro — Active</div>
              ) : isBetaFree ? (
                <div style={{fontSize:13,color:"#22c55e",fontWeight:600,marginBottom:10}}>✓ Beta Access — Active</div>
              ) : trialActive ? (
                <div style={{fontSize:13,color:T.accent,fontWeight:600,marginBottom:10}}>✓ 7-Day Trial — Active</div>
              ) : (
                <button onClick={()=>{ if(!currentUser){setLoginOpen(true);setLoginMode("upgrade");}else setUpgradeOpen(true); }} style={{width:"100%",padding:"11px 0",borderRadius:10,border:"none",background:T.grad,color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer",marginBottom:10}}>Upgrade to Pro</button>
              )}
              {(isPro||trialActive) && (
                <button onClick={()=>setUpgradeOpen(true)} style={{width:"100%",padding:"9px 0",borderRadius:10,border:"1px solid "+T.border,background:T.surface2,color:T.textDim,fontWeight:600,fontSize:13,cursor:"pointer",marginBottom:8}}>Manage Subscription</button>
              )}
              {currentUser ? (
                <button onClick={()=>setConfirmClear(true)} style={{width:"100%",padding:"9px 0",borderRadius:10,border:"1px solid #f8717140",background:"transparent",color:"#f87171",fontWeight:600,fontSize:13,cursor:"pointer"}}>Sign Out</button>
              ) : (
                <button onClick={()=>{setLoginOpen(true);setLoginMode(null);}} style={{width:"100%",padding:"9px 0",borderRadius:10,border:"none",background:T.grad,color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer"}}>Sign In</button>
              )}
            </div>
          </div>

          {/* Username */}
          {currentUser&&(
            <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginBottom:16}}>
              <div style={{padding:"14px 16px",borderBottom:"1px solid "+T.border}}><div style={{fontWeight:700,fontSize:13,color:T.text}}>Username</div></div>
              <div style={{padding:"14px 16px"}}>
                {!unameEdit?(
                  <>
                    <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:oldUsernames.length>0?10:0}}>
                      <span style={{fontSize:15,fontWeight:600,color:username?T.text:T.textDim,fontFamily:username?"monospace":"inherit"}}>{username||"Not set"}</span>
                      <button onClick={()=>{setUnameInput(username||"");setUnameEdit(true);}} style={{padding:"5px 12px",borderRadius:20,border:"1px solid "+T.border,background:T.surface2,color:T.textDim,fontSize:11,fontWeight:600,cursor:"pointer"}}>Edit</button>
                    </div>
                    {oldUsernames.length>0&&(
                      <>
                        <button onClick={()=>setUnameExpanded(x=>!x)} style={{background:"none",border:"none",cursor:"pointer",color:T.textDim,fontSize:11,padding:0,marginBottom:unameExpanded?8:0}}>
                          Show previous usernames ({oldUsernames.length}) {unameExpanded?"▲":"▼"}
                        </button>
                        {unameExpanded&&(
                          <div style={{display:"flex",flexDirection:"column",gap:4,marginTop:6}}>
                            {oldUsernames.map((u,i)=><span key={i} style={{fontSize:12,color:T.textFaint,fontFamily:"monospace"}}>{u}</span>)}
                          </div>
                        )}
                      </>
                    )}
                  </>
                ):(
                  <>
                    <input value={unameInput} onChange={e=>setUnameInput(e.target.value.toLowerCase())} placeholder="username" maxLength={20}
                      style={{width:"100%",padding:"10px 12px",borderRadius:8,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:13,fontFamily:"monospace",outline:"none",marginBottom:6,boxSizing:"border-box"}}/>
                    <div style={{fontSize:11,color:T.textDim,marginBottom:10}}>3–20 characters: a–z, 0–9, underscores only</div>
                    <div style={{display:"flex",gap:8}}>
                      <button onClick={()=>setUnameEdit(false)} style={{flex:1,padding:"9px 0",borderRadius:8,border:"1px solid "+T.border,background:T.surface2,color:T.textDim,fontSize:13,fontWeight:600,cursor:"pointer"}}>Cancel</button>
                      <button onClick={saveUsername} style={{flex:1,padding:"9px 0",borderRadius:8,border:"none",background:T.grad,color:"#fff",fontSize:13,fontWeight:700,cursor:"pointer"}}>Save</button>
                    </div>
                  </>
                )}
              </div>
            </div>
          )}

          {/* Email */}
          {currentUser&&(
            <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginBottom:16}}>
              <div style={{padding:"14px 16px",borderBottom:"1px solid "+T.border}}><div style={{fontWeight:700,fontSize:13,color:T.text}}>Email</div></div>
              <div style={{padding:"14px 16px"}}>
                {!emailEdit?(
                  <>
                    <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:oldEmails.length>0?10:0}}>
                      <span style={{fontSize:13,color:T.text}}>{currentUser.email}</span>
                      <button onClick={()=>{setEmailInput2(currentUser.email||"");setEmailEdit(true);}} style={{padding:"5px 12px",borderRadius:20,border:"1px solid "+T.border,background:T.surface2,color:T.textDim,fontSize:11,fontWeight:600,cursor:"pointer"}}>Edit</button>
                    </div>
                    {oldEmails.length>0&&(
                      <>
                        <button onClick={()=>setEmailExpanded(x=>!x)} style={{background:"none",border:"none",cursor:"pointer",color:T.textDim,fontSize:11,padding:0,marginBottom:emailExpanded?8:0}}>
                          Show previous emails ({oldEmails.length}) {emailExpanded?"▲":"▼"}
                        </button>
                        {emailExpanded&&(
                          <div style={{display:"flex",flexDirection:"column",gap:4,marginTop:6}}>
                            {oldEmails.map((e,i)=><span key={i} style={{fontSize:12,color:T.textFaint}}>{e}</span>)}
                          </div>
                        )}
                      </>
                    )}
                  </>
                ):(
                  <>
                    <input value={emailInput2} onChange={e=>setEmailInput2(e.target.value)} type="email" placeholder="you@example.com"
                      style={{width:"100%",padding:"10px 12px",borderRadius:8,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:13,outline:"none",marginBottom:12,boxSizing:"border-box"}}/>
                    <div style={{display:"flex",gap:8}}>
                      <button onClick={()=>setEmailEdit(false)} style={{flex:1,padding:"9px 0",borderRadius:8,border:"1px solid "+T.border,background:T.surface2,color:T.textDim,fontSize:13,fontWeight:600,cursor:"pointer"}}>Cancel</button>
                      <button onClick={saveEmail2} style={{flex:1,padding:"9px 0",borderRadius:8,border:"none",background:T.grad,color:"#fff",fontSize:13,fontWeight:700,cursor:"pointer"}}>Save</button>
                    </div>
                  </>
                )}
              </div>
            </div>
          )}

          {/* Security */}
          {currentUser&&(
            <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginBottom:16}}>
              <div style={{padding:"14px 16px",borderBottom:"1px solid "+T.border}}><div style={{fontWeight:700,fontSize:13,color:T.text}}>Security</div></div>
              <div style={{padding:"14px 16px"}}>
                {hasPassword?(
                  <button onClick={()=>setPwModal(true)} style={{width:"100%",padding:"9px 0",borderRadius:10,border:"1px solid "+T.border,background:T.surface2,color:T.text,fontSize:13,fontWeight:600,cursor:"pointer"}}>Change Password</button>
                ):(
                  <div style={{fontSize:13,color:T.textDim,lineHeight:1.6}}>You signed in with Google — manage your password through your Google Account.</div>
                )}
              </div>
            </div>
          )}

          {/* Feedback */}
          <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginBottom:16}}>
            <div style={{padding:"14px 16px",borderBottom:"1px solid "+T.border}}><div style={{fontWeight:700,fontSize:13,color:T.text}}>Feedback</div></div>
            <div style={{padding:"14px 16px",display:"flex",flexDirection:"column",gap:8}}>
              <button onClick={()=>openWithUsernameGate('feedback')} style={{padding:"10px 0",borderRadius:10,border:"1px solid "+T.border,background:T.surface2,color:T.text,fontSize:13,fontWeight:600,cursor:"pointer"}}>💬 Send Feedback</button>
            </div>
          </div>

          {/* Your Corrections */}
          <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginBottom:16}}>
            <div style={{padding:"14px 16px",borderBottom:"1px solid "+T.border}}><div style={{fontWeight:700,fontSize:13,color:T.text}}>Your Corrections {corrections.length>0&&"("+corrections.length+")"}</div></div>
            {corrections.length===0?(
              <div style={{padding:"20px 16px",textAlign:"center"}}>
                <div style={{fontSize:13,color:T.textDim,marginBottom:4}}>No corrections yet</div>
                <div style={{fontSize:11,color:T.textFaint,lineHeight:1.6}}>Help improve timestamps for everyone — tap the edit icon on any scene while watching.</div>
              </div>
            ):(
              corrections.slice(-3).map(c=>(
                <div key={c.id} style={{padding:"11px 16px",borderBottom:"1px solid "+T.border,display:"flex",gap:10,alignItems:"flex-start"}}>
                  <Badge type={c.submittedBy} isDark={isDark}/>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:12,fontWeight:600,color:T.text,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{c.sceneTitle}</div>
                    <div style={{fontSize:11,color:T.textDim}}>{(c.types||[c.type]).slice(0,2).join(", ")}{(c.types||[]).length>2?" & "+(c.types.length-2)+" more":""} · {c.platform}
                      {c.status==="pending"&&<span style={{marginLeft:6,fontSize:10,color:"#f59e0b",fontWeight:600}}>● pending</span>}
                      {c.status==="approved"&&<span style={{marginLeft:6,fontSize:10,color:"#22c55e",fontWeight:600}}>● applied</span>}
                      {c.status==="rejected"&&<span style={{marginLeft:6,fontSize:10,color:"#f87171",fontWeight:600}}>● rejected</span>}
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>

          {/* Referral */}
          <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,overflow:"hidden",marginBottom:16}}>
            <div style={{padding:"14px 16px",borderBottom:"1px solid "+T.border}}>
              <div style={{fontWeight:700,fontSize:13,color:T.text}}>Refer a Friend</div>
            </div>
            <div style={{padding:"14px 16px"}}>
              {currentUser&&username?(
                <>
                  <div style={{fontSize:12,color:T.textDim,marginBottom:12,lineHeight:1.6}}>Share your link. When someone signs up through it, each of you gets an extra free week.</div>
                  <div style={{background:T.surface2,border:"1px solid "+T.border,borderRadius:8,padding:"10px 12px",display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
                    <span style={{fontFamily:"monospace",fontSize:12,fontWeight:700,color:T.accent}}>getfilmscout.com/u/{username}</span>
                    <button onClick={()=>{try{navigator.clipboard.writeText(`https://getfilmscout.com/u/${username}`);showToast("Link copied","#22c55e");}catch(e){}}} style={{background:"none",border:"none",cursor:"pointer",color:T.textDim,display:"flex",alignItems:"center",gap:4,fontSize:11}}>
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
                      Copy
                    </button>
                  </div>
                  <button onClick={()=>openWithUsernameGate('share')} style={{width:"100%",padding:"11px 0",borderRadius:10,border:"none",background:T.grad,color:"#fff",fontWeight:700,fontSize:14,display:"flex",alignItems:"center",justifyContent:"center",gap:8}}>{IC.share} Share FilmScout Code</button>
                </>
              ):currentUser&&!username?(
                <>
                  <div style={{fontSize:13,color:T.textDim,marginBottom:12,lineHeight:1.6}}>Set a username to get your referral link.</div>
                  <button onClick={()=>openWithUsernameGate('share')} style={{width:"100%",padding:"10px 0",borderRadius:10,border:"1px solid "+T.border,background:T.surface2,color:T.text,fontSize:13,fontWeight:600,cursor:"pointer"}}>Set Username</button>
                </>
              ):(
                <div style={{fontSize:13,color:T.textDim,lineHeight:1.6}}>Sign in to get your referral link.</div>
              )}
            </div>
          </div>

          {/* Moderator panel */}
          {isMod?(
            <div style={{background:T.surface,border:"2px solid #22c55e60",borderRadius:14,overflow:"hidden",marginBottom:16}}>
              <div style={{padding:"14px 16px",borderBottom:"1px solid "+T.border,display:"flex",alignItems:"center",justifyContent:"space-between"}}>
                <div style={{display:"flex",alignItems:"center",gap:8}}>
                  <span style={{color:"#22c55e",display:"flex"}}>{IC.shield}</span>
                  <div style={{fontWeight:700,fontSize:13,color:T.text}}>Moderator Mode</div>
                </div>
                <button onClick={()=>{setIsMod(false);try{localStorage.removeItem("fs_mod");}catch(e){}}} style={{fontSize:11,color:"#f87171",background:"none",border:"none",cursor:"pointer"}}>Sign out</button>
              </div>
              {(()=>{
                const pending = corrections.filter(c=>c.status==="pending");
                if(pending.length===0) return <div style={{padding:"16px",fontSize:12,color:T.textDim,textAlign:"center"}}>No pending corrections</div>;
                return pending.map(c=>(
                  <div key={c.id} style={{padding:"12px 16px",borderBottom:"1px solid "+T.border}}>
                    <div style={{fontSize:12,fontWeight:600,color:T.text,marginBottom:2}}>{c.movieTitle} — {c.sceneTitle}</div>
                    <div style={{fontSize:11,color:T.textDim,marginBottom:8}}>{(c.types||[c.type]).join(", ")} · {c.platform} · by {c.submittedBy}</div>
                    {c.note&&<div style={{fontSize:11,color:T.textDim,fontStyle:"italic",marginBottom:8}}>"{c.note}"</div>}
                    <div style={{display:"flex",gap:8}}>
                      <button onClick={()=>{
                        const updated=corrections.map(x=>x.id===c.id?{...x,status:"approved"}:x);
                        setCorrections(updated); try{localStorage.setItem("fs_c",JSON.stringify(updated));}catch(e){}
                        setMovies(prev=>prev.map(m=>{ if(m.id!==c.movieId)return m; return {...m,scenes:m.scenes.map(sc=>sc.id!==c.sceneId?sc:{...sc,verified_by:"mod"})}; }));
                        apiFetch("/api/corrections",{method:"PATCH",headers:{"Content-Type":"application/json","X-Mod-Token":MOD_CODE},body:JSON.stringify({id:String(c.id),action:"approve"})}).catch(()=>{});
                        showToast("Correction approved","#22c55e");
                      }} style={{flex:1,padding:"7px 0",borderRadius:8,border:"none",background:"#166534",color:"#fff",fontSize:12,fontWeight:700,cursor:"pointer"}}>Approve</button>
                      <button onClick={()=>{
                        const updated=corrections.map(x=>x.id===c.id?{...x,status:"rejected"}:x);
                        setCorrections(updated); try{localStorage.setItem("fs_c",JSON.stringify(updated));}catch(e){}
                        apiFetch("/api/corrections",{method:"PATCH",headers:{"Content-Type":"application/json","X-Mod-Token":MOD_CODE},body:JSON.stringify({id:String(c.id),action:"reject"})}).catch(()=>{});
                        showToast("Correction rejected","#f87171");
                      }} style={{flex:1,padding:"7px 0",borderRadius:8,border:"1px solid #f8717140",background:"transparent",color:"#f87171",fontSize:12,fontWeight:700,cursor:"pointer"}}>Reject</button>
                    </div>
                  </div>
                ));
              })()}
            </div>
          ):(
            <div style={{background:T.surface,border:"1px solid "+T.border,borderRadius:14,padding:"14px 16px",marginBottom:16}}>
              <div style={{fontSize:12,fontWeight:600,color:T.textDim,marginBottom:10}}>Moderator Access</div>
              <div style={{display:"flex",gap:8}}>
                <input value={modCodeInput} onChange={e=>{setModCodeInput(e.target.value);setModCodeError(false);}} placeholder="Enter mod code" type="password"
                  style={{flex:1,padding:"9px 12px",borderRadius:8,border:"1px solid "+(modCodeError?"#f87171":T.border),background:T.inputBg,color:T.text,fontSize:13}}/>
                <button onClick={()=>{
                  if(modCodeInput===MOD_CODE){setIsMod(true);setModCodeInput("");setModCodeError(false);try{localStorage.setItem("fs_mod","1");}catch(e){}showToast("Moderator mode active","#22c55e");}
                  else{setModCodeError(true);showToast("Invalid mod code","#f87171");}
                }} style={{padding:"9px 16px",borderRadius:8,border:"none",background:T.grad,color:"#fff",fontSize:13,fontWeight:700,cursor:"pointer"}}>Enter</button>
              </div>
              {modCodeError&&<div style={{fontSize:11,color:"#f87171",marginTop:6}}>Invalid code</div>}
            </div>
          )}

          {/* Danger Zone */}
          {currentUser&&(
            <div style={{background:T.surface,border:"1px solid #f8717140",borderRadius:14,overflow:"hidden",marginBottom:16}}>
              <div style={{padding:"14px 16px",borderBottom:"1px solid #f8717140"}}><div style={{fontWeight:700,fontSize:13,color:"#f87171"}}>Danger Zone</div></div>
              <div style={{padding:"14px 16px"}}>
                <button onClick={()=>{setDeleteConfirmInput("");setDeleteConfirmOpen(true);}} style={{width:"100%",padding:"9px 0",borderRadius:10,border:"1px solid #f8717140",background:"transparent",color:"#f87171",fontSize:13,fontWeight:600,cursor:"pointer"}}>Delete Account</button>
              </div>
            </div>
          )}

          {/* Version */}
          <div style={{textAlign:"center",padding:"8px 0 24px",color:T.textFaint,fontSize:11}}>
            Film<span style={{color:T.accent}}>Scout</span> · v1.0.0-beta
          </div>
        </div>
      )}

      {/* Bottom nav */}
      {phase!=="playing" && (
        <div style={{position:"fixed",bottom:0,left:0,right:0,maxWidth:500,margin:"0 auto",background:T.headerBg,borderTop:"1px solid "+T.headerBd,display:"flex",zIndex:100}}>
          {[
            {id:"home",label:"Browse",icon:IC.home},
            {id:"settings",label:"Settings",icon:IC.settings},
          ].map(tab=>(
            <button key={tab.id} onClick={()=>setPhase(tab.id)}
              style={{flex:1,padding:"12px 0",background:"none",border:"none",color:phase===tab.id?T.accent:T.textDim,cursor:"pointer",display:"flex",flexDirection:"column",alignItems:"center",gap:4,fontSize:10,fontWeight:phase===tab.id?700:500}}>
              {tab.icon}{tab.label}
            </button>
          ))}
        </div>
      )}

      {/* Login / Trial Modal */}
      {loginOpen && (
        <Sheet onClose={()=>{setLoginOpen(false);setPendingMovie(null);setLoginTab("social");setEmailInput("");setPassInput("");setEmailError("");}} T={T}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20}}>
            <div>
              <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,color:T.text}}>{loginMode==="trial"?"Start Free Trial":"Upgrade to Pro"}</div>
              <div style={{fontSize:12,color:T.textDim,marginTop:4}}>{pendingMovie?`Watch ${pendingMovie.title}${pendingMovie.sub?" "+pendingMovie.sub:""}`:""}</div>
            </div>
            <CloseBtn onClose={()=>{setLoginOpen(false);setPendingMovie(null);setLoginTab("social");setEmailInput("");setPassInput("");setEmailError("");}} T={T}/>
          </div>

          {loginMode==="trial" && !trialUsed && (
            <div style={{background:T.accentBg,border:"1px solid "+T.accent+"40",borderRadius:12,padding:"12px 14px",marginBottom:16}}>
              <div style={{fontSize:13,fontWeight:700,color:T.accent,marginBottom:4}}>🎬 7-Day Free Trial</div>
              <div style={{fontSize:12,color:T.textDim,lineHeight:1.5}}>Full access to all movies and scene alerts. No credit card required.</div>
            </div>
          )}

          {trialUsed && loginMode==="trial" && (
            <div style={{background:isDark?"#1a0808":"#fff1f1",border:"1px solid #dc262640",borderRadius:12,padding:"12px 14px",marginBottom:16}}>
              <div style={{fontSize:12,color:isDark?"#fca5a5":"#b91c1c",lineHeight:1.5}}>Your free trial has been used. Upgrade to Pro to continue.</div>
            </div>
          )}

          {/* Social login buttons */}
          <div style={{display:"flex",flexDirection:"column",gap:10,marginBottom:16}}>
            {[
              ["google","Google"],
              // TODO: Re-enable after Apple OAuth is implemented post-beta
              // ["apple","Apple"],
              // TODO: Re-enable after Facebook OAuth is implemented post-beta
              // ["facebook","Facebook"],
            ].map(([id,name])=>{
              const logos={
                google:<svg width="18" height="18" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>,
                apple:<svg width="18" height="18" viewBox="0 0 24 24" fill={isDark?"#fff":"#000"}><path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.8-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"/></svg>,
                facebook:<svg width="18" height="18" viewBox="0 0 24 24" fill="#1877F2"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>,
              };
              return (
                <button key={name} onClick={()=>handleLogin(name)}
                  style={{padding:"13px 16px",borderRadius:12,border:"1px solid "+T.border,background:T.surface,color:T.text,fontSize:14,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",gap:12}}>
                  <span style={{width:26,height:26,borderRadius:"50%",background:isDark?"#1e293b":"#f1f5f9",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>{logos[id]}</span>
                  Continue with {name}
                </button>
              );
            })}
          </div>

          {/* Email option */}
          <div style={{borderTop:"1px solid "+T.border,paddingTop:14,marginBottom:4}}>
            <button onClick={()=>setLoginTab(t=>t==="email"?"":"email")} style={{width:"100%",background:"none",border:"none",color:T.textDim,fontSize:12,cursor:"pointer",textAlign:"center",marginBottom:loginTab==="email"?12:0}}>
              {loginTab==="email"?"▲ Hide email sign-in":"or sign in with email ▼"}
            </button>
            {loginTab==="email" && (
              <div style={{display:"flex",flexDirection:"column",gap:10}}>
                <input value={emailInput} onChange={e=>setEmailInput(e.target.value)} placeholder="Email" type="email"
                  style={{padding:"11px 12px",borderRadius:10,border:"1px solid "+(emailError?T.accent:T.border),background:T.inputBg,color:T.text,fontSize:13,outline:"none"}}/>
                <input value={passInput} onChange={e=>setPassInput(e.target.value)} placeholder="Password" type="password"
                  style={{padding:"11px 12px",borderRadius:10,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:13,outline:"none"}}/>
                {emailError && <div style={{fontSize:11,color:"#f87171"}}>{emailError}</div>}
                <button onClick={async ()=>{
                  setEmailError("");
                  if(!emailInput||!passInput){setEmailError("Please fill in all fields");return;}
                  try{
                    const res = await apiFetch("/api/auth/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:emailInput,password:passInput,mode:loginMode,ref:refUserId||undefined})});
                    const data = await res.json();
                    if(data.ok){
                      await refreshUserData();
                      setLoginOpen(false);
                      showToast(data.restored?"Welcome back — your account has been restored.":"Signed in!", data.restored?"#22c55e":T.accent);
                      if(pendingMovie){setMovie(pendingMovie);setPhase("platform");setPendingMovie(null);}
                    } else { setEmailError(data.error||"Sign in failed"); }
                  }catch(e){setEmailError("Network error — please try again");}
                }} style={{padding:"13px 0",borderRadius:12,border:"none",background:T.grad,color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer"}}>
                  {loginMode==="trial"?"Start Free Trial":"Sign In"}
                </button>
              </div>
            )}
          </div>

          {loginMode==="trial" && !trialUsed && (
            <button onClick={handleGuest} style={{marginTop:12,width:"100%",padding:"11px 0",borderRadius:10,border:"1px solid "+T.border,background:"transparent",color:T.textDim,fontSize:13,fontWeight:600,cursor:"pointer"}}>
              Continue as Guest (1 free movie)
            </button>
          )}

          <div style={{textAlign:"center",marginTop:16,fontSize:11,color:T.textFaint,lineHeight:1.6}}>
            By continuing you agree to our{" "}
            <a href="https://getfilmscout.com/terms" target="_blank" rel="noopener" style={{color:T.textDim,textDecoration:"underline"}}>Terms</a>
            {" "}and{" "}
            <a href="https://getfilmscout.com/privacy" target="_blank" rel="noopener" style={{color:T.textDim,textDecoration:"underline"}}>Privacy Policy</a>
          </div>
        </Sheet>
      )}

      {/* Upgrade Modal */}
      {upgradeOpen && (
        <Sheet onClose={()=>setUpgradeOpen(false)} T={T} borderColor={T.accent}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20}}>
            <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,color:T.text}}>FilmScout Pro</div>
            <CloseBtn onClose={()=>setUpgradeOpen(false)} T={T}/>
          </div>
          <div style={{display:"flex",flexDirection:"column",gap:10,marginBottom:20}}>
            {["Unlimited access to all movies","30-second advance scene alerts","Platform-accurate timestamps","Audio alarm + vibration alerts","Support independent development"].map(f=>(
              <div key={f} style={{display:"flex",alignItems:"center",gap:10,fontSize:13,color:T.text}}>
                <span style={{color:"#22c55e",flexShrink:0}}>{IC.check}</span>{f}
              </div>
            ))}
          </div>
          <button
            onClick={handleBetaAccess}
            disabled={!!checkoutLoading}
            style={{width:"100%",padding:"14px 0",borderRadius:12,border:"2px solid #22c55e",background:"rgba(34,197,94,0.1)",color:"#22c55e",fontWeight:700,fontSize:15,cursor:checkoutLoading?"not-allowed":"pointer",marginBottom:10,opacity:checkoutLoading&&checkoutLoading!=="beta"?0.5:1,display:"flex",alignItems:"center",justifyContent:"center",gap:10}}>
            {checkoutLoading==="beta"
              ? <><div style={{width:16,height:16,border:"2px solid rgba(34,197,94,0.4)",borderTopColor:"#22c55e",borderRadius:"50%",animation:"spin 0.7s linear infinite"}}/> Activating…</>
              : "Free Beta Access"}
          </button>
          <button
            onClick={()=>handleUpgrade("monthly")}
            disabled={!!checkoutLoading}
            style={{width:"100%",padding:"14px 0",borderRadius:12,border:"none",background:T.grad,color:"#fff",fontWeight:700,fontSize:16,cursor:checkoutLoading?"not-allowed":"pointer",marginBottom:10,opacity:checkoutLoading&&checkoutLoading!=="monthly"?0.5:1,display:"flex",alignItems:"center",justifyContent:"center",gap:10}}>
            {checkoutLoading==="monthly"
              ? <><div style={{width:16,height:16,border:"2px solid rgba(255,255,255,0.4)",borderTopColor:"#fff",borderRadius:"50%",animation:"spin 0.7s linear infinite"}}/> Starting checkout…</>
              : "Monthly — $1.99/month"}
          </button>
          <button
            onClick={()=>handleUpgrade("annual")}
            disabled={!!checkoutLoading}
            style={{width:"100%",padding:"14px 0",borderRadius:12,border:"2px solid "+T.accent,background:T.accentBg,color:T.accent,fontWeight:700,fontSize:15,cursor:checkoutLoading?"not-allowed":"pointer",marginBottom:10,opacity:checkoutLoading&&checkoutLoading!=="annual"?0.5:1,display:"flex",alignItems:"center",justifyContent:"center",gap:8}}>
            {checkoutLoading==="annual"
              ? <><div style={{width:16,height:16,border:"2px solid "+T.accent+"60",borderTopColor:T.accent,borderRadius:"50%",animation:"spin 0.7s linear infinite"}}/> Starting checkout…</>
              : <><span>Annual — $14.99/year</span><span style={{fontSize:11,background:"#22c55e",color:"#fff",borderRadius:20,padding:"2px 8px",fontWeight:700}}>Save 37%</span></>}
          </button>
        </Sheet>
      )}

      {/* Feedback Modal */}
      {feedbackOpen && (
        <Sheet onClose={()=>{setFeedbackOpen(false);setFeedbackDone(false);setFeedbackText("");setFeedbackCategory("");}} T={T}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20}}>
            <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,color:T.text}}>Send Feedback</div>
            <CloseBtn onClose={()=>{setFeedbackOpen(false);setFeedbackDone(false);setFeedbackText("");setFeedbackCategory("");}} T={T}/>
          </div>
          {feedbackDone ? (
            <div style={{textAlign:"center",padding:"20px 0"}}>
              <div style={{fontSize:32,marginBottom:12}}>🙏</div>
              <div style={{fontSize:16,fontWeight:700,color:T.text,marginBottom:6}}>Thank you!</div>
              <div style={{fontSize:13,color:T.textDim}}>Your feedback helps improve FilmScout for every family.</div>
            </div>
          ) : (
            <>
              <div style={{display:"flex",gap:8,flexWrap:"wrap",marginBottom:14}}>
                {["Timestamp Wrong","Missing Scene","App Bug","Feature Request","Other"].map(cat=>(
                  <button key={cat} onClick={()=>setFeedbackCategory(cat)}
                    style={{padding:"6px 12px",borderRadius:20,border:"1px solid "+(feedbackCategory===cat?T.accent:T.border),background:feedbackCategory===cat?T.accentBg:T.surface,color:feedbackCategory===cat?T.accent:T.textDim,fontSize:12,fontWeight:feedbackCategory===cat?700:500,cursor:"pointer"}}>
                    {cat}
                  </button>
                ))}
              </div>
              <textarea value={feedbackText} onChange={e=>setFeedbackText(e.target.value)} placeholder="Describe the issue or idea…" rows={4}
                style={{width:"100%",padding:"11px 12px",borderRadius:10,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:13,outline:"none",resize:"none",marginBottom:12}}/>
              <button onClick={async ()=>{
                if(!feedbackText.trim()){showToast("Please enter feedback","#f87171");return;}
                setFeedbackSubmitting(true);
                try{
                  await apiFetch("/api/feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:feedbackCategory,message:feedbackText})});
                }catch(e){}
                setFeedbackSubmitting(false); setFeedbackDone(true);
              }} disabled={feedbackSubmitting} style={{width:"100%",padding:"13px 0",borderRadius:12,border:"none",background:T.grad,color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer",opacity:feedbackSubmitting?0.7:1}}>
                {feedbackSubmitting?"Sending…":"Submit Feedback"}
              </button>
            </>
          )}
        </Sheet>
      )}

      {/* Movie Request Modal */}
      {requestOpen && (
        <Sheet onClose={()=>{setRequestOpen(false);setRequestDone(false);setRequestText("");}} T={T}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20}}>
            <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,color:T.text}}>Request a Movie</div>
            <CloseBtn onClose={()=>{setRequestOpen(false);setRequestDone(false);setRequestText("");}} T={T}/>
          </div>
          {requestDone ? (
            <div style={{textAlign:"center",padding:"20px 0"}}>
              <div style={{fontSize:32,marginBottom:12}}>🎬</div>
              <div style={{fontSize:16,fontWeight:700,color:T.text,marginBottom:6}}>Request received!</div>
              <div style={{fontSize:13,color:T.textDim}}>We'll add it to the queue. Popular requests get added faster.</div>
            </div>
          ) : (
            <>
              <input value={requestText} onChange={e=>setRequestText(e.target.value)} placeholder="Movie title…"
                style={{width:"100%",padding:"11px 12px",borderRadius:10,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:13,outline:"none",marginBottom:12}}/>
              <button onClick={async ()=>{
                if(!requestText.trim()){showToast("Please enter a movie title","#f87171");return;}
                try{
                  await apiFetch("/api/movie-requests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:requestText})});
                }catch(e){}
                setRequestDone(true);
              }} style={{width:"100%",padding:"13px 0",borderRadius:12,border:"none",background:T.grad,color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer"}}>
                Submit Request
              </button>
            </>
          )}
        </Sheet>
      )}

      {/* Timestamp Edit Modal */}
      {tsOpen && tsScene && (
        <Sheet onClose={()=>setTsOpen(false)} T={T} borderColor={T.accent}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}}>
            <div>
              <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:16,color:T.text}}>Edit Timestamps</div>
              <div style={{fontSize:12,color:T.textDim,marginTop:2}}>{tsScene.t}</div>
            </div>
            <CloseBtn onClose={()=>setTsOpen(false)} T={T}/>
          </div>

          {tsNeighbors.prev && (
            <div style={{background:T.surface2,border:"1px solid "+T.border,borderRadius:8,padding:"8px 12px",marginBottom:10,fontSize:11,color:T.textDim}}>
              ↑ Previous ends at <span style={{fontFamily:"monospace",color:T.text}}>{tsNeighbors.prev.end}</span> — <span style={{color:T.textFaint,fontStyle:"italic"}}>{tsNeighbors.prev.title}</span>
            </div>
          )}

          <div style={{display:"flex",gap:10,marginBottom:10}}>
            <div style={{flex:1}}>
              <div style={{fontSize:11,color:T.textDim,marginBottom:4}}>Start</div>
              <input value={tsStart} onChange={e=>setTsStart(e.target.value)} placeholder="0:00"
                style={{width:"100%",padding:"10px 12px",borderRadius:8,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:14,fontFamily:"monospace",outline:"none"}}/>
            </div>
            <div style={{flex:1}}>
              <div style={{fontSize:11,color:T.textDim,marginBottom:4}}>End</div>
              <input value={tsEnd} onChange={e=>setTsEnd(e.target.value)} placeholder="0:00"
                style={{width:"100%",padding:"10px 12px",borderRadius:8,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:14,fontFamily:"monospace",outline:"none"}}/>
            </div>
          </div>

          {tsNeighbors.next && (
            <div style={{background:T.surface2,border:"1px solid "+T.border,borderRadius:8,padding:"8px 12px",marginBottom:10,fontSize:11,color:T.textDim}}>
              ↓ Next starts at <span style={{fontFamily:"monospace",color:T.text}}>{tsNeighbors.next.start}</span> — <span style={{color:T.textFaint,fontStyle:"italic"}}>{tsNeighbors.next.title}</span>
            </div>
          )}

          <div style={{marginBottom:14}}>
            <div style={{fontSize:11,color:T.textDim,marginBottom:6}}>What changed?</div>
            <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
              {["Start time off","End time off","Scene missing","Wrong scene type"].map(opt=>(
                <button key={opt} onClick={()=>setTsType(t=>t.includes(opt)?t.filter(x=>x!==opt):[...t,opt])}
                  style={{padding:"5px 10px",borderRadius:20,border:"1px solid "+(tsType.includes(opt)?T.accent:T.border),background:tsType.includes(opt)?T.accentBg:T.surface,color:tsType.includes(opt)?T.accent:T.textDim,fontSize:11,cursor:"pointer"}}>
                  {opt}
                </button>
              ))}
            </div>
          </div>

          <button onClick={submitTs} style={{width:"100%",padding:"13px 0",borderRadius:12,border:"none",background:T.grad,color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer"}}>
            Submit Correction
          </button>
        </Sheet>
      )}

      {/* Resync Modal */}
      {resyncOpen && (
        <Sheet onClose={()=>{setResyncOpen(false);setResyncTime("");}} T={T}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20}}>
            <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,color:T.text}}>Re-sync Timer</div>
            <CloseBtn onClose={()=>setResyncOpen(false)} T={T}/>
          </div>
          <div style={{fontSize:13,color:T.textDim,marginBottom:16,lineHeight:1.6}}>
            Is the timer ahead or behind your movie? Use the nudge buttons to adjust, or enter the exact time showing on screen.
          </div>
          <div style={{display:"flex",gap:8,justifyContent:"center",marginBottom:16}}>
            {[-60,-30,-10,10,30,60].map(n=>(
              <button key={n} onClick={()=>nudge(n)} style={{flex:1,padding:"10px 4px",borderRadius:8,border:"1px solid "+T.border,background:T.surface,color:n<0?"#f87171":"#22c55e",fontSize:12,fontWeight:600,cursor:"pointer"}}>
                {n>0?"+":""}{n}s
              </button>
            ))}
          </div>
          <div style={{display:"flex",gap:8}}>
            <input value={resyncTime} onChange={e=>setResyncTime(e.target.value)} placeholder="Enter exact time (e.g. 1:23:45)"
              style={{flex:1,padding:"11px 12px",borderRadius:10,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:13,outline:"none"}}/>
            <button onClick={()=>{const s=parseTime(resyncTime);if(s!==null){seekTo(s);setResyncTime("");setResyncOpen(false);}else showToast("Invalid time","#f87171");}}
              style={{padding:"11px 16px",borderRadius:10,border:"none",background:T.grad,color:"#fff",fontWeight:700,fontSize:13,cursor:"pointer"}}>Set</button>
          </div>
        </Sheet>
      )}

      {/* Confirm Leave */}
      {confirmLeave && (
        <Sheet onClose={()=>setConfirmLeave(false)} T={T}>
          <div style={{textAlign:"center",padding:"8px 0 16px"}}>
            <div style={{fontSize:28,marginBottom:12}}>⏹</div>
            <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,color:T.text,marginBottom:8}}>Stop Watching?</div>
            <div style={{fontSize:13,color:T.textDim,marginBottom:20,lineHeight:1.6}}>Your current position will be lost.</div>
            <div style={{display:"flex",gap:10}}>
              <button onClick={()=>setConfirmLeave(false)} style={{flex:1,padding:"13px 0",borderRadius:12,border:"1px solid "+T.border,background:T.surface,color:T.text,fontWeight:600,fontSize:14,cursor:"pointer"}}>Keep Watching</button>
              <button onClick={goHomeImmediate} style={{flex:1,padding:"13px 0",borderRadius:12,border:"none",background:"#dc2626",color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer"}}>Stop</button>
            </div>
          </div>
        </Sheet>
      )}

      {/* Confirm Clear */}
      {confirmClear && (
        <Sheet onClose={()=>setConfirmClear(false)} T={T}>
          <div style={{textAlign:"center",padding:"8px 0 16px"}}>
            <div style={{fontSize:28,marginBottom:12}}>👋</div>
            <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,color:T.text,marginBottom:8}}>Sign Out?</div>
            <div style={{fontSize:13,color:T.textDim,marginBottom:20,lineHeight:1.6}}>This will sign you out and clear your local settings, corrections, and preferences.</div>
            <div style={{display:"flex",gap:10}}>
              <button onClick={()=>setConfirmClear(false)} style={{flex:1,padding:"13px 0",borderRadius:12,border:"1px solid "+T.border,background:T.surface,color:T.text,fontWeight:600,fontSize:14,cursor:"pointer"}}>Cancel</button>
              <button onClick={()=>{
                try{ Object.keys(localStorage).filter(k=>k.startsWith("fs_")).forEach(k=>localStorage.removeItem(k)); }catch(e){}
                setIsPro(false); setIsBetaFree(false); setTrialActive(false); setCurrentUser(null); setIsGuest(false); setGuestMovieId(null);
                setCorrections([]); setIsMod(false); setAlarmOn(true); setVibrationOn(true); setWarnAhead(30);
                setTheme("dark"); setHighContrast(false); setConfirmClear(false);
                setUsername(null); setOldUsernames([]); setOldEmails([]); setHasPassword(false);
                setUnameEdit(false); setEmailEdit(false);
                showToast("Signed out","#94a3b8");
              }} style={{flex:1,padding:"13px 0",borderRadius:12,border:"none",background:"#dc2626",color:"#fff",fontWeight:700,fontSize:14,cursor:"pointer"}}>Sign Out</button>
            </div>
          </div>
        </Sheet>
      )}

      {/* Username Prompt Modal (C1/C2) */}
      {unamePromptOpen&&(
        <Sheet onClose={()=>{setUnamePromptOpen(false);setUnamePromptInput("");}} T={T}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}}>
            <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,color:T.text}}>Set a username first</div>
            <CloseBtn onClose={()=>{setUnamePromptOpen(false);setUnamePromptInput("");}} T={T}/>
          </div>
          <div style={{fontSize:13,color:T.textDim,lineHeight:1.6,marginBottom:16}}>
            {unamePromptMode==='share'
              ? "Your referral link will look like getfilmscout.com/u/yourname. You can change it anytime in Settings."
              : "This lets other families see who submitted feedback and corrections. You can change it anytime in Settings."}
          </div>
          <input value={unamePromptInput} onChange={e=>setUnamePromptInput(e.target.value.toLowerCase())} placeholder="username" maxLength={20}
            style={{width:"100%",padding:"11px 12px",borderRadius:10,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:13,fontFamily:"monospace",outline:"none",marginBottom:8,boxSizing:"border-box"}}/>
          <div style={{fontSize:11,color:T.textDim,marginBottom:14}}>3–20 characters: a–z, 0–9, underscores only</div>
          <div style={{display:"flex",gap:8}}>
            <button onClick={()=>{setUnamePromptOpen(false);setUnamePromptInput("");}} style={{flex:1,padding:"12px 0",borderRadius:10,border:"1px solid "+T.border,background:T.surface2,color:T.textDim,fontSize:13,fontWeight:600,cursor:"pointer"}}>Cancel</button>
            <button onClick={savePromptUsername} style={{flex:1,padding:"12px 0",borderRadius:10,border:"none",background:T.grad,color:"#fff",fontSize:13,fontWeight:700,cursor:"pointer"}}>Save</button>
          </div>
        </Sheet>
      )}

      {/* Delete Account Confirm Modal (E1) */}
      {deleteConfirmOpen&&(
        <Sheet onClose={()=>{setDeleteConfirmOpen(false);setDeleteConfirmInput("");}} T={T}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}}>
            <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,color:"#f87171"}}>Delete your account?</div>
            <CloseBtn onClose={()=>{setDeleteConfirmOpen(false);setDeleteConfirmInput("");}} T={T}/>
          </div>
          <div style={{fontSize:13,color:T.textDim,lineHeight:1.7,marginBottom:16}}>
            Your account, username, feedback, and corrections will be hidden immediately. If you change your mind, signing up again with the same email within 180 days will restore everything.
            <br/><br/>
            After 180 days, your username becomes available for anyone to claim and your data is permanently removed.
          </div>
          <div style={{fontSize:13,color:T.textDim,marginBottom:8}}>Type <strong style={{color:T.text}}>DELETE</strong> to confirm.</div>
          <input value={deleteConfirmInput} onChange={e=>setDeleteConfirmInput(e.target.value)} placeholder="DELETE"
            style={{width:"100%",padding:"10px 12px",borderRadius:8,border:"1px solid "+(deleteConfirmInput==="DELETE"?"#f87171":T.border),background:T.inputBg,color:T.text,fontSize:13,outline:"none",marginBottom:12,boxSizing:"border-box"}}/>
          <div style={{display:"flex",gap:8}}>
            <button onClick={()=>{setDeleteConfirmOpen(false);setDeleteConfirmInput("");}} style={{flex:1,padding:"12px 0",borderRadius:10,border:"1px solid "+T.border,background:T.surface2,color:T.textDim,fontSize:13,fontWeight:600,cursor:"pointer"}}>Cancel</button>
            <button onClick={handleDeleteAccount} disabled={deleteConfirmInput!=="DELETE"} style={{flex:1,padding:"12px 0",borderRadius:10,border:"none",background:deleteConfirmInput==="DELETE"?"#dc2626":"#555",color:"#fff",fontSize:13,fontWeight:700,cursor:deleteConfirmInput==="DELETE"?"pointer":"not-allowed"}}>Delete My Account</button>
          </div>
        </Sheet>
      )}

      {/* Password Change Modal */}
      {pwModal&&(
        <Sheet onClose={()=>{setPwModal(false);setPwCurrentInput("");setPwNewInput("");setPwConfirmInput("");}} T={T}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20}}>
            <div style={{fontFamily:"Georgia,serif",fontWeight:700,fontSize:18,color:T.text}}>Change Password</div>
            <CloseBtn onClose={()=>{setPwModal(false);setPwCurrentInput("");setPwNewInput("");setPwConfirmInput("");}} T={T}/>
          </div>
          <div style={{display:"flex",flexDirection:"column",gap:12}}>
            <div>
              <div style={{fontSize:12,color:T.textDim,marginBottom:4}}>Current Password</div>
              <input type="password" value={pwCurrentInput} onChange={e=>setPwCurrentInput(e.target.value)}
                style={{width:"100%",padding:"10px 12px",borderRadius:8,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:13,outline:"none",boxSizing:"border-box"}}/>
            </div>
            <div>
              <div style={{fontSize:12,color:T.textDim,marginBottom:4}}>New Password</div>
              <input type="password" value={pwNewInput} onChange={e=>setPwNewInput(e.target.value)}
                style={{width:"100%",padding:"10px 12px",borderRadius:8,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:13,outline:"none",boxSizing:"border-box"}}/>
            </div>
            <div>
              <div style={{fontSize:12,color:T.textDim,marginBottom:4}}>Confirm New Password</div>
              <input type="password" value={pwConfirmInput} onChange={e=>setPwConfirmInput(e.target.value)}
                style={{width:"100%",padding:"10px 12px",borderRadius:8,border:"1px solid "+T.border,background:T.inputBg,color:T.text,fontSize:13,outline:"none",boxSizing:"border-box"}}/>
            </div>
            <button onClick={savePassword} disabled={pwSaving} style={{width:"100%",padding:"13px 0",borderRadius:12,border:"none",background:pwSaving?"#666":T.grad,color:"#fff",fontWeight:700,fontSize:14,cursor:pwSaving?"not-allowed":"pointer",marginTop:4}}>
              {pwSaving?"Saving…":"Change Password"}
            </button>
          </div>
        </Sheet>
      )}

    </div>
    </div>
  );
}

window.FilmScout = FilmScout;
