// app.jsx — VideoHub root: auth, casts, video detail nav

const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#e11d48"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = ['#e11d48', '#f59e0b', '#a855f7', '#22d3ee', '#10b981', '#f5f5f7'];

function App() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const accent = t.accent;

  // Tab + nested screen state. The bottom-tab id is the "root"; openVideo / openCast
  // push a transient sub-screen on top of the root.
  const [tab, setTab] = useState('library');       // library | search | cast | profile
  const [openVideoId, setOpenVideoId] = useState(null);
  const [openCastId,  setOpenCastId]  = useState(null);
  // { id, name } for category/studio overlays
  const [openCategory, setOpenCategory] = useState(null);
  const [openStudio,   setOpenStudio]   = useState(null);

  // Modals
  const [authOpen, setAuthOpen] = useState(false);
  const [addOpen, setAddOpen]   = useState(false);

  // Auth + data
  const [user, setUser] = useState(null);
  const [authReady, setAuthReady] = useState(false);
  const [privacyLocked, setPrivacyLocked] = useState(false);
  const [rawItems, setRawItems] = useState([]);
  const [rawCasts, setRawCasts] = useState([]);
  const [rawCategories, setRawCategories] = useState([]);
  const [rawStudios, setRawStudios] = useState([]);
  const [itemsLoading, setItemsLoading] = useState(false);

  useEffect(() => {
    const unsub = window.VHFirebase.onAuthChanged((u) => {
      setUser(u);
      setAuthReady(true);
      if (!u) { setRawItems([]); setRawCasts([]); }
    });
    return unsub;
  }, []);

  useEffect(() => {
    if (!user) return;
    setItemsLoading(true);
    const unsubV   = window.VHFirebase.subscribeVideos(user.uid, (list) => { setRawItems(list || []); setItemsLoading(false); });
    const unsubC   = window.VHFirebase.subscribeCasts(user.uid, (list) => setRawCasts(list || []));
    const unsubCat = window.VHFirebase.subscribeCategories(user.uid, (list) => setRawCategories(list || []));
    const unsubSt  = window.VHFirebase.subscribeStudios(user.uid, (list) => setRawStudios(list || []));
    return () => { unsubV(); unsubC(); unsubCat(); unsubSt(); };
  }, [user]);

  // Items the screens see. Signed-out → sample shapes rendered locked.
  const items = useMemo(() => {
    if (user) return rawItems.map(window.normalizeItem);
    return window.SAMPLE_ITEMS.map(window.normalizeItem);
  }, [user, rawItems]);
  const casts      = user ? rawCasts      : [];
  const categories = user ? rawCategories : [];
  const studios    = user ? rawStudios    : [];

  const lockedValue = !user || privacyLocked;
  const lockedApi = {
    value: lockedValue,
    signedIn: !!user,
    topPad: (!user && (tab === 'library' || tab === 'search' || tab === 'cast')) ? 80 : 20,
    toggle: () => {
      if (!user) { setAuthOpen(true); return; }
      setPrivacyLocked(v => !v);
    },
    openAuth: () => setAuthOpen(true),
    openAdd:  () => handleAdd(),
  };

  const handleAdd = () => {
    if (!user) { setAuthOpen(true); return; }
    setAddOpen(true);
  };
  const handleSignOut = async () => {
    await window.VHFirebase.signOut();
    setPrivacyLocked(false);
    setOpenVideoId(null); setOpenCastId(null);
    setTab('library');
  };

  const openVideo = (id) => {
    if (!user) { setAuthOpen(true); return; }
    setOpenVideoId(id);
  };
  const openCast = (id) => {
    if (!user) { setAuthOpen(true); return; }
    setOpenCastId(id);
  };
  const handleOpenCategory = (id, name) => {
    if (!user) { setAuthOpen(true); return; }
    setOpenCategory({ id, name });
    setOpenVideoId(null); setOpenCastId(null); setOpenStudio(null);
  };
  const handleOpenStudio = (id, name) => {
    if (!user) { setAuthOpen(true); return; }
    setOpenStudio({ id, name });
    setOpenVideoId(null); setOpenCastId(null); setOpenCategory(null);
  };

  // Render which screen?
  const renderScreen = () => {
    if (openCategory) {
      return <window.CategoryDetailScreen
        categoryId={openCategory.id} categoryName={openCategory.name}
        items={items} categories={categories}
        locked={lockedApi} accent={accent}
        onBack={() => setOpenCategory(null)}
        onOpenVideo={(id) => { setOpenCategory(null); openVideo(id); }}/>;
    }
    if (openStudio) {
      return <window.StudioDetailScreen
        studioId={openStudio.id} studioName={openStudio.name}
        items={items} studios={studios}
        locked={lockedApi} accent={accent}
        onBack={() => setOpenStudio(null)}
        onOpenVideo={(id) => { setOpenStudio(null); openVideo(id); }}/>;
    }
    if (openVideoId) {
      return <window.VideoDetailScreen
        videoId={openVideoId} items={items} casts={casts}
        categories={categories} studios={studios}
        locked={lockedApi} accent={accent} uid={user?.uid}
        onBack={() => setOpenVideoId(null)}
        onOpenCast={(id) => { setOpenVideoId(null); openCast(id); }}
        onOpenVideo={(id) => setOpenVideoId(id)}
        onOpenCategory={handleOpenCategory}
        onOpenStudio={handleOpenStudio}/>;
    }
    if (openCastId) {
      return <window.CastDetailScreen
        castId={openCastId} items={items} casts={casts}
        locked={lockedApi} accent={accent} uid={user?.uid}
        onBack={() => setOpenCastId(null)}
        onOpenVideo={(id) => { setOpenCastId(null); openVideo(id); }}/>;
    }
    switch (tab) {
      case 'library':
        return <window.LibraryScreen items={items} locked={lockedApi} accent={accent}
          loading={user && itemsLoading} onOpenVideo={openVideo} onOpenAdd={handleAdd}/>;
      case 'search':
        return <window.SearchScreen items={items} locked={lockedApi} accent={accent}
          onOpenVideo={openVideo} onOpenCast={openCast}/>;
      case 'cast':
        return <window.CastLibraryScreen items={items} casts={casts} locked={lockedApi} accent={accent}
          onOpenCast={openCast}/>;
      case 'profile':
        return <window.ProfileScreen user={user} items={items} locked={lockedApi} accent={accent}
          onSignOut={handleSignOut} onOpenAuth={() => setAuthOpen(true)}/>;
      default: return null;
    }
  };

  const screenKey = openCategory ? 'cat:' + openCategory.id
    : openStudio ? 'st:' + openStudio.id
    : openVideoId ? 'v:' + openVideoId
    : openCastId ? 'c:' + openCastId : tab;

  return (
    <div style={{
      position: 'fixed', inset: 0,
      background: window.VH_BG,
      color: window.VH_TEXT,
      fontFamily: '-apple-system, "SF Pro Text", system-ui, sans-serif',
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'fixed', inset: 0, zIndex: 0, pointerEvents: 'none',
        background: `radial-gradient(60% 50% at 30% 20%, ${accent}1a, transparent 70%),
                     radial-gradient(60% 50% at 80% 90%, ${accent}10, transparent 70%)`,
      }} />

      {authReady && !user && !openVideoId && !openCastId && tab !== 'profile' && (
        <SignedOutBanner accent={accent} onOpen={() => setAuthOpen(true)}/>
      )}

      <div key={screenKey} style={{
        flex: 1, overflowY: 'auto', overflowX: 'hidden',
        position: 'relative', zIndex: 1,
        animation: 'vhFadeIn 240ms ease-out',
      }}>
        <div style={{ maxWidth: 1280, margin: '0 auto', minHeight: '100%' }}>
          {renderScreen()}
        </div>
      </div>

      {user && !openVideoId && tab !== 'profile' && (
        <window.FAB accent={accent} onClick={handleAdd}/>
      )}
      <window.BottomTabs active={tab} onChange={(id) => {
        setOpenVideoId(null); setOpenCastId(null);
        setOpenCategory(null); setOpenStudio(null);
        setTab(id);
      }} accent={accent}/>

      <window.AuthModal open={authOpen} onClose={() => setAuthOpen(false)} accent={accent}/>
      <window.AddModal
        open={addOpen}
        onClose={() => setAddOpen(false)}
        uid={user?.uid}
        items={items}
        casts={casts}
        categories={categories}
        studios={studios}
        accent={accent}
        onSaved={() => {}}
        onOpenVideo={(id) => { setAddOpen(false); openVideo(id); }}
        onOpenCategory={handleOpenCategory}
        onOpenStudio={handleOpenStudio}
      />

      <window.TweaksPanel>
        <window.TweakSection label="Theme" />
        <window.TweakColor
          label="Accent" value={accent}
          options={ACCENT_OPTIONS}
          onChange={(v) => setTweak('accent', v)}
        />
      </window.TweaksPanel>

      <style>{`
        @keyframes vhFadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes vhSlideUp { from { transform: translateY(40px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        ::-webkit-scrollbar { display: none; }
      `}</style>
    </div>
  );
}

function SignedOutBanner({ accent, onOpen }) {
  return (
    <div style={{
      position: 'fixed', left: 12, right: 12, top: 12, zIndex: 50,
      maxWidth: 600, margin: '0 auto',
      padding: '10px 12px', borderRadius: 12,
      background: 'rgba(20,20,24,0.92)',
      backdropFilter: 'blur(16px) saturate(160%)',
      border: `0.5px solid ${accent}55`,
      display: 'flex', alignItems: 'center', gap: 10,
      boxShadow: '0 10px 30px rgba(0,0,0,0.45)',
    }}>
      <div style={{
        width: 26, height: 26, borderRadius: 8,
        background: `${accent}22`, border: `0.5px solid ${accent}55`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>
        <svg width="11" height="13" viewBox="0 0 14 16" fill="none">
          <rect x="2" y="7" width="10" height="8" rx="1.5" stroke={accent} strokeWidth="1.6"/>
          <path d="M4 7V4.5a3 3 0 016 0V7" stroke={accent} strokeWidth="1.6"/>
        </svg>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 600, color: window.VH_TEXT, lineHeight: 1.3 }}>
          Demo locked
        </div>
        <div style={{ fontSize: 11, color: window.VH_DIM, lineHeight: 1.3, marginTop: 1 }}>
          Sign in to see your real library.
        </div>
      </div>
      <button onClick={onOpen} style={{
        padding: '7px 12px', borderRadius: 99, border: 'none', cursor: 'pointer',
        background: accent, color: '#fff', fontSize: 12, fontWeight: 600,
        fontFamily: 'inherit', flexShrink: 0,
      }}>
        Sign in
      </button>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
