// Main app — shell, tab switching, cloud-synced medals
const { useState: useStateApp, useEffect: useEffectApp, useRef: useRefApp } = React;

// --- Cloud sync (Firebase Realtime Database) ---
const firebaseConfig = {
  apiKey: "AIzaSyCSKfZDT1rKivThC8BeEgBURoiEBnvK5lw",
  authDomain: "oleampics.firebaseapp.com",
  databaseURL: "https://oleampics-default-rtdb.firebaseio.com",
  projectId: "oleampics",
  storageBucket: "oleampics.firebasestorage.app",
  messagingSenderId: "140240469665",
  appId: "1:140240469665:web:55431f250ae1d663e77ae0",
};
firebase.initializeApp(firebaseConfig);
const medalsRef = firebase.database().ref('medals');
const connectedRef = firebase.database().ref('.info/connected');

const TABS = [
  { key: 'home',     label: 'HOME',  icon: '🏠' },
  { key: 'schedule', label: 'PLAN',  icon: '🗓️' },
  { key: 'players',  label: 'CREW',  icon: '👥' },
  { key: 'vault',    label: 'VAULT', icon: '🔐' },
  { key: 'rankings', label: 'RANK',  icon: '🏆' },
  { key: 'admin',    label: 'ADMIN', icon: '🛠️' },
];

const TAB_ICONS = {
  home: <svg viewBox="0 0 16 16" width="22" height="22" shapeRendering="crispEdges">
    <rect x="7" y="2" width="2" height="2" fill="currentColor" />
    <rect x="5" y="4" width="6" height="2" fill="currentColor" />
    <rect x="3" y="6" width="10" height="2" fill="currentColor" />
    <rect x="3" y="8" width="2" height="6" fill="currentColor" />
    <rect x="11" y="8" width="2" height="6" fill="currentColor" />
    <rect x="5" y="8" width="6" height="6" fill="currentColor" opacity="0.4" />
    <rect x="7" y="11" width="2" height="3" fill="currentColor" />
  </svg>,
  players: <svg viewBox="0 0 16 16" width="22" height="22" shapeRendering="crispEdges">
    <rect x="3" y="3" width="3" height="3" fill="currentColor" />
    <rect x="2" y="7" width="5" height="4" fill="currentColor" />
    <rect x="10" y="3" width="3" height="3" fill="currentColor" />
    <rect x="9" y="7" width="5" height="4" fill="currentColor" />
  </svg>,
  vault: <svg viewBox="0 0 16 16" width="22" height="22" shapeRendering="crispEdges">
    <rect x="2" y="3" width="12" height="10" fill="currentColor" opacity="0.25" />
    <rect x="2" y="3" width="12" height="1" fill="currentColor" />
    <rect x="2" y="12" width="12" height="1" fill="currentColor" />
    <rect x="2" y="3" width="1" height="10" fill="currentColor" />
    <rect x="13" y="3" width="1" height="10" fill="currentColor" />
    <rect x="6" y="6" width="4" height="4" fill="currentColor" />
    <rect x="7" y="7" width="2" height="2" fill="none" stroke="#0e0a08" />
    <rect x="4" y="7" width="1" height="2" fill="currentColor" />
    <rect x="11" y="7" width="1" height="2" fill="currentColor" />
    <rect x="7" y="4" width="2" height="1" fill="currentColor" />
    <rect x="7" y="11" width="2" height="1" fill="currentColor" />
  </svg>,
  schedule: <svg viewBox="0 0 16 16" width="22" height="22" shapeRendering="crispEdges">
    <rect x="4" y="2" width="1" height="2" fill="currentColor" />
    <rect x="11" y="2" width="1" height="2" fill="currentColor" />
    <rect x="2" y="3" width="12" height="2" fill="currentColor" />
    <rect x="2" y="5" width="12" height="9" fill="currentColor" opacity="0.35" />
    <rect x="2" y="3" width="12" height="11" fill="none" stroke="currentColor" />
    <rect x="4" y="7" width="2" height="1" fill="currentColor" />
    <rect x="7" y="7" width="2" height="1" fill="currentColor" />
    <rect x="10" y="7" width="2" height="1" fill="currentColor" />
    <rect x="4" y="10" width="2" height="1" fill="currentColor" />
    <rect x="7" y="10" width="2" height="1" fill="currentColor" />
    <rect x="10" y="10" width="2" height="1" fill="currentColor" />
  </svg>,
  rankings: <svg viewBox="0 0 16 16" width="22" height="22" shapeRendering="crispEdges">
    <rect x="5" y="2" width="6" height="2" fill="currentColor" />
    <rect x="4" y="4" width="8" height="4" fill="currentColor" />
    <rect x="6" y="8" width="4" height="3" fill="currentColor" />
    <rect x="4" y="11" width="8" height="2" fill="currentColor" />
    <rect x="2" y="4" width="2" height="2" fill="currentColor" />
    <rect x="12" y="4" width="2" height="2" fill="currentColor" />
  </svg>,
  admin: <svg viewBox="0 0 16 16" width="22" height="22" shapeRendering="crispEdges">
    <rect x="6" y="2" width="4" height="2" fill="currentColor" />
    <rect x="5" y="4" width="6" height="2" fill="currentColor" />
    <rect x="6" y="6" width="4" height="2" fill="currentColor" />
    <rect x="7" y="8" width="2" height="6" fill="currentColor" />
    <rect x="3" y="13" width="3" height="1" fill="currentColor" />
    <rect x="10" y="13" width="3" height="1" fill="currentColor" />
  </svg>,
};

function App() {
  const [tab, setTab] = useStateApp('home');
  const [medals, setMedals] = useStateApp(() => {
    try {
      const saved = localStorage.getItem('lea30.medals');
      if (saved) return JSON.parse(saved);
    } catch {}
    return window.LEA30.DEFAULT_MEDALS;
  });
  const [adminAuthed, setAdminAuthed] = useStateApp(false);
  const [syncState, setSyncState] = useStateApp('syncing'); // syncing | idle | error
  const lastRemote = useRefApp('');
  const adminAuthedRef = useRefApp(false);
  useEffectApp(() => { adminAuthedRef.current = adminAuthed; }, [adminAuthed]);

  useEffectApp(() => {
    try { localStorage.setItem('lea30.medals', JSON.stringify(medals)); } catch {}
  }, [medals]);

  // Realtime subscribe: pushes from Firebase land here within ~200ms
  useEffectApp(() => {
    const onValue = (snap) => {
      const remote = snap.val();
      if (!remote || typeof remote !== 'object') return;
      const s = JSON.stringify(remote);
      lastRemote.current = s;
      // Don't clobber an admin's in-flight edits with our own echo
      if (!adminAuthedRef.current || s !== JSON.stringify(medals)) {
        setMedals(remote);
      }
    };
    const onErr = () => setSyncState('error');
    medalsRef.on('value', onValue, onErr);
    const onConn = (snap) => setSyncState(snap.val() ? 'idle' : 'error');
    connectedRef.on('value', onConn);
    return () => { medalsRef.off('value', onValue); connectedRef.off('value', onConn); };
  }, []);

  // Push admin changes (debounced). Skip if the change is just an echo of what we got.
  useEffectApp(() => {
    if (!adminAuthed) return;
    const s = JSON.stringify(medals);
    if (s === lastRemote.current) return;
    setSyncState('syncing');
    const t = setTimeout(() => {
      medalsRef.set(medals)
        .then(() => { lastRemote.current = s; setSyncState('idle'); })
        .catch(() => setSyncState('error'));
    }, 250);
    return () => clearTimeout(t);
  }, [medals, adminAuthed]);

  const goto = (k) => setTab(k);

  return (
    <div className="phone">
      <header className="app-header">
        <img className="logo" src="assets/logo.png" alt="Oléampics XXX" />
        <div className="title-bar">
          <span className="eyebrow">OLÉAMPICS XXX</span>
          <span className="h1">{tabTitle(tab)}</span>
        </div>
        <span
          title={syncState === 'error' ? 'Cloud sync offline — using local copy' : syncState === 'syncing' ? 'Syncing…' : 'Live'}
          style={{
            marginLeft: 'auto',
            width: 8, height: 8, borderRadius: '50%',
            background: syncState === 'error' ? '#ff6e6e' : syncState === 'syncing' ? '#ffd24a' : '#3ec46a',
            boxShadow: '0 0 0 2px rgba(0,0,0,.4)',
            flexShrink: 0,
          }}
        />
      </header>

      <main className="app-main">
        {tab === 'home'     && <HomeTab medals={medals} goto={goto} />}
        {tab === 'players'  && <PlayersTab />}
        {tab === 'vault'    && <VaultTab />}
        {tab === 'schedule' && <ScheduleTab />}
        {tab === 'rankings' && <RankingsTab medals={medals} setMedals={setMedals} hostMode={false} />}
        {tab === 'admin'    && <AdminTab medals={medals} setMedals={setMedals} onAuthChange={setAdminAuthed} />}
      </main>

      <nav className="tabbar">
        {TABS.map(t => (
          <button
            key={t.key}
            className={`tab ${tab === t.key ? 'active' : ''}`}
            onClick={() => setTab(t.key)}
          >
            <span className="ico">{TAB_ICONS[t.key]}</span>
            <span className="lbl">{t.label}</span>
          </button>
        ))}
      </nav>
    </div>
  );
}

function tabTitle(t) {
  return ({
    home: 'HOME',
    players: 'CREW',
    vault: 'THE VAULT',
    schedule: 'SCHEDULE',
    rankings: 'RANKINGS',
    admin: 'ADMIN',
  })[t] || '';
}

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

// Hide boot splash once mounted
setTimeout(() => {
  const boot = document.getElementById('boot');
  if (boot) {
    boot.classList.add('hide');
    setTimeout(() => boot.remove(), 500);
  }
}, 400);
