/* global React, ReactDOM, useHyttenData, AlmanakkLayout, FeltLayout, sunTimes,
   TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakToggle, TweakSelect */

const { useState, useEffect, useMemo } = React;

function App() {
  const { data, plannedMap } = useHyttenData();
  const [tweaks, setTweak] = useTweaks(window.HYTTEN_TWEAKS);

  const today = new Date();
  const [currentYear, setYear] = useState(today.getFullYear());
  const [currentMonth, setMonth] = useState(today.getMonth());
  const setMonthFn = (y, m) => {
    if (m < 0) { m = 11; y--; }
    if (m > 11) { m = 0; y++; }
    setYear(y); setMonth(m);
  };

  // Auto theme by time of day
  const themeMode = tweaks.themeMode || 'auto';
  useEffect(() => {
    const apply = () => {
      let theme = themeMode;
      if (theme === 'auto') {
        const h = new Date().getHours();
        theme = (h < 7 || h >= 19) ? 'night' : 'day';
      }
      document.body.dataset.theme = theme;
      document.body.dataset.direction = tweaks.direction || 'almanakk';
      document.body.dataset.showTopo = String(tweaks.showTopography !== false);
    };
    apply();
    const id = setInterval(apply, 60000);
    return () => clearInterval(id);
  }, [themeMode, tweaks.direction, tweaks.showTopography]);

  // tick clock for video corner
  useEffect(() => {
    const id = setInterval(() => {
      const el = document.getElementById('video-clock');
      if (el) el.textContent = new Date().toLocaleTimeString('nb-NO', { hour: '2-digit', minute: '2-digit' });
    }, 30000);
    return () => clearInterval(id);
  }, []);

  // Sun times
  const sun = useMemo(() => tweaks.showSunMoon !== false ? sunTimes(new Date()) : null, [tweaks.showSunMoon]);

  // Days since last visit / until next planned
  const { daysSince, daysUntil } = useMemo(() => {
    if (!data?.occupancy?.dates) return { daysSince: null, daysUntil: null };
    if (tweaks.showCounter === false) return { daysSince: null, daysUntil: null };
    const todayKey = new Date().toISOString().slice(0, 10);
    const dates = data.occupancy.dates;
    let lastOcc = null;
    for (const [k, v] of Object.entries(dates)) {
      if (v?.occupied && k <= todayKey && (!lastOcc || k > lastOcc)) lastOcc = k;
    }
    let ds = null;
    if (lastOcc) {
      const a = new Date(todayKey + 'T00:00:00');
      const b = new Date(lastOcc + 'T00:00:00');
      ds = Math.max(0, Math.round((a - b) / 86400000));
    }
    // next planned
    let next = null;
    for (const e of (data.planned?.entries || [])) {
      const start = e.from || e.date;
      if (!start || start <= todayKey) continue;
      if (!next || start < next.from) next = { from: start, label: e.label || 'Planlagt' };
    }
    let du = null;
    if (next) {
      const a = new Date(todayKey + 'T00:00:00');
      const b = new Date(next.from + 'T00:00:00');
      du = { days: Math.round((b - a) / 86400000), label: next.label };
    }
    return { daysSince: ds, daysUntil: du };
  }, [data, tweaks.showCounter]);

  if (!data) {
    return (
      <div style={{ padding: 60, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', fontSize: '0.8rem', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
        Laster almanakk…
      </div>
    );
  }

  const Layout = (tweaks.direction === 'felt') ? FeltLayout : AlmanakkLayout;

  return (
    <>
      <Layout
        data={data}
        plannedMap={plannedMap}
        currentYear={currentYear}
        currentMonth={currentMonth}
        setMonth={setMonthFn}
        sun={sun}
        daysSince={daysSince}
        daysUntil={daysUntil}
      />
      <TweaksPanel title="Tweaks">
        <TweakSection label="Retning" />
        <TweakRadio
          label="Stil"
          value={tweaks.direction}
          onChange={(v) => setTweak('direction', v)}
          options={['almanakk', 'felt']}
        />
        <TweakSection label="Tema" />
        <TweakRadio
          label="Modus"
          value={tweaks.themeMode}
          onChange={(v) => setTweak('themeMode', v)}
          options={['auto', 'day', 'night']}
        />
        <TweakSection label="Elementer" />
        <TweakToggle label="Topografi" value={tweaks.showTopography !== false} onChange={(v) => setTweak('showTopography', v)} />
        <TweakToggle label="Sol & måne" value={tweaks.showSunMoon !== false} onChange={(v) => setTweak('showSunMoon', v)} />
        <TweakToggle label="Besøksteller" value={tweaks.showCounter !== false} onChange={(v) => setTweak('showCounter', v)} />
      </TweaksPanel>
    </>
  );
}

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