/* Track & Throw — Main App shell */

const TABS = [
  { id: 'comps',    label: 'Comps',    icon: Icon.list },
  { id: 'stats',    label: 'Stats',    icon: Icon.stats },
  { id: 'settings', label: 'Settings', icon: Icon.settings },
];

function App() {
  const [data, setData] = useState(() => loadData() || blankData());
  const [tab, setTab] = useState('comps');
  const [openCompId, setOpenCompId] = useState(null);
  const [scrolled, setScrolled] = useState(false);

  // Persist on every change
  useEffect(() => { saveData(data); }, [data]);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 4);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const updateComp = (cId, fn) => {
    setData(d => ({ ...d, competitions: d.competitions.map(c => c.id === cId ? fn(c) : c) }));
  };
  const replaceComp = (next) => {
    setData(d => ({ ...d, competitions: d.competitions.map(c => c.id === next.id ? next : c) }));
  };
  const deleteComp = (cId) => {
    setData(d => ({ ...d, competitions: d.competitions.filter(c => c.id !== cId) }));
    setOpenCompId(null);
  };
  const addComp = () => {
    const today = new Date().toISOString().slice(0, 10);
    const c = {
      id: uid('cmp'),
      name: '',
      date: today,
      location: '',
      event: data.settings.defaultEvent || 'javelin',
      ranking: null,
      notes: '',
      throws: [],
    };
    setData(d => ({ ...d, competitions: [c, ...d.competitions] }));
    setOpenCompId(c.id);
  };

  const openComp = (id) => { setOpenCompId(id); };
  const closeComp = () => setOpenCompId(null);

  const openComp_ = openCompId ? data.competitions.find(c => c.id === openCompId) : null;

  return (
    <ToastProvider>
      <div className="app">
        <header className={'topbar ' + (scrolled ? 'scrolled' : '')}>
          <div className="logo"><img src="icon.png" alt=""/></div>
          <h1>Track &amp; Throw</h1>
        </header>

        <main className="main">
          {tab === 'comps' && (
            <CompetitionsView
              data={data}
              onUpdate={setData}
              onOpenComp={openComp}
              onAddComp={addComp}
            />
          )}
          {tab === 'stats' && (
            <StatsView data={data} onOpenComp={openComp} />
          )}
          {tab === 'settings' && (
            <SettingsView data={data} onUpdate={setData} />
          )}
        </main>

        {tab === 'comps' && data.competitions.length > 0 && (
          <button className="btn-fab" onClick={addComp} aria-label="New competition"><Icon.plus/></button>
        )}

        <nav className="tabbar">
          {TABS.map(t => (
            <button key={t.id} className={'tab ' + (tab === t.id ? 'active' : '')} onClick={() => setTab(t.id)}>
              <t.icon/> {t.label}
            </button>
          ))}
        </nav>

        <ModalFull
          open={!!openComp_}
          onClose={closeComp}
          title={openComp_ ? (openComp_.name || 'Untitled') : ''}
        >
          {openComp_ && (
            <CompetitionDetail
              comp={openComp_}
              onChange={replaceComp}
              onDelete={deleteComp}
            />
          )}
        </ModalFull>
      </div>
    </ToastProvider>
  );
}

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