// Florio Analytics — Live tab (real-time, big-screen / TV view).
// Ported from js/pages/live.js. Subscribes to the analytics_counters Firestore
// docs ("today" + "global") via FlorioAPI.subscribeToCounter and counts total
// plants once via fetchTotalPlants. Numbers update live; subscriptions are
// cleaned up on unmount. Range prop is ignored (this page is not date-range based).
(function () {
  const I = window.HyperIcons;
  const { useState, useEffect, useRef } = React;

  // formatNumber from the data layer (lazy — FlorioAPI may not exist at definition time).
  function fmt(n) {
    if (n == null) return '--';
    return (window.FlorioAPI && window.FlorioAPI.formatNumber) ? window.FlorioAPI.formatNumber(n) : String(n);
  }

  // Card definitions mirror the old page. `counter` selects which live snapshot
  // (or "manual" one-shot fetch) supplies the value; `key` is the field on the doc.
  const CARDS = [
    { key: 'waterings', counter: 'today', label: 'Waterings Today', accent: '#2ACF56', icon: 'droplet' },
    { key: 'totalWaterings', counter: 'global', label: 'Waterings All Time', accent: 'var(--app-accent)', icon: 'droplet' },
    { key: 'totalPlants', counter: 'manual', label: 'Total Plants', accent: '#2ACF56', icon: 'leaf' },
    { key: 'totalUsers', counter: 'global', label: 'Total Users', accent: 'var(--app-accent)', icon: 'users' },
  ];

  function Live({ range }) {
    // values keyed by card.key; null until first snapshot/fetch arrives.
    const [values, setValues] = useState({ waterings: null, totalWaterings: null, totalPlants: null, totalUsers: null });
    const [tvMode, setTvMode] = useState(false);
    const [ready, setReady] = useState(false);

    useEffect(() => {
      let alive = true;
      const unsubs = [];
      (async () => {
        await window.FlorioReady;
        if (!alive) return;
        const API = window.FlorioAPI;
        setReady(true);

        const applyCounter = (counterName) => (data) => {
          if (!alive) return;
          setValues((prev) => {
            const next = Object.assign({}, prev);
            for (const c of CARDS) {
              if (c.counter === counterName) next[c.key] = data[c.key] ?? 0;
            }
            return next;
          });
        };

        try { unsubs.push(API.subscribeToCounter('global', applyCounter('global'))); }
        catch (e) { console.error('[Live] subscribe global failed:', e); }
        try { unsubs.push(API.subscribeToCounter('today', applyCounter('today'))); }
        catch (e) { console.error('[Live] subscribe today failed:', e); }

        // Total plants — one-shot count of every user's plants subcollection.
        API.fetchTotalPlants()
          .then((total) => { if (alive) setValues((prev) => Object.assign({}, prev, { totalPlants: total })); })
          .catch((e) => console.error('[Live] fetchTotalPlants failed:', e));
      })();

      return () => {
        alive = false;
        for (const u of unsubs) { try { if (typeof u === 'function') u(); } catch (e) { /* noop */ } }
      };
    }, []);

    if (!ready) {
      return (
        <div style={{ display: 'grid', placeItems: 'center', minHeight: '60vh' }}>
          <div className="pa-spin" style={{ width: 38, height: 38, borderRadius: '50%', border: '3px solid var(--border-default)', borderTopColor: 'var(--app-accent)' }} />
        </div>
      );
    }

    const valueSize = tvMode ? 'clamp(56px, 11vw, 168px)' : 'clamp(40px, 6vw, 84px)';
    const labelSize = tvMode ? 'clamp(16px, 1.8vw, 28px)' : 16;

    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
        {/* Header + TV-mode toggle */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ width: 40, height: 40, borderRadius: 11, display: 'grid', placeItems: 'center', background: 'color-mix(in srgb, var(--app-accent) 14%, transparent)', color: 'var(--app-accent)' }}>
            {I.monitor ? I.monitor({ size: 20 }) : null}
          </span>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 18, color: 'var(--text-primary)' }}>Live activity</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-sans)', fontSize: 12.5, color: 'var(--text-muted)' }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#2ACF56', boxShadow: '0 0 0 4px color-mix(in srgb, #2ACF56 24%, transparent)' }} />
              Real-time counters — updates as events arrive.
            </div>
          </div>
          <button onClick={() => setTvMode((v) => !v)}
            style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 14px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)', background: tvMode ? 'var(--app-accent)' : 'var(--surface-card)', color: tvMode ? '#fff' : 'var(--text-secondary)', cursor: 'pointer', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 13 }}>
            <span style={{ display: 'flex' }}>{I.monitor ? I.monitor({ size: 16 }) : null}</span>
            {tvMode ? 'Exit big screen' : 'Big screen'}
          </button>
        </div>

        {/* Counter grid — big numbers */}
        <div style={{ display: 'grid', gridTemplateColumns: tvMode ? 'repeat(2, 1fr)' : 'repeat(auto-fit, minmax(240px, 1fr))', gap: tvMode ? 24 : 18 }}>
          {CARDS.map((c) => {
            const v = values[c.key];
            return (
              <div key={c.key} style={{
                background: 'var(--surface-card)', border: '1px solid var(--border-subtle)',
                borderRadius: 'var(--radius-2xl)', boxShadow: 'var(--shadow-card)',
                padding: tvMode ? '48px 32px' : '28px 24px',
                display: 'flex', flexDirection: 'column', gap: tvMode ? 16 : 10,
                alignItems: 'center', justifyContent: 'center', textAlign: 'center', minWidth: 0,
                minHeight: tvMode ? '34vh' : undefined,
              }}>
                <span style={{ width: tvMode ? 56 : 40, height: tvMode ? 56 : 40, borderRadius: 12, display: 'grid', placeItems: 'center', background: 'color-mix(in srgb, ' + c.accent + ' 14%, transparent)', color: c.accent }}>
                  {I[c.icon] ? I[c.icon]({ size: tvMode ? 28 : 20 }) : null}
                </span>
                <span style={{
                  fontFamily: 'var(--font-mono-display)', fontWeight: 700, lineHeight: 1,
                  letterSpacing: '-.02em', color: c.accent, fontSize: valueSize,
                  fontVariantNumeric: 'tabular-nums',
                }}>
                  {fmt(v)}
                </span>
                <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, color: 'var(--text-secondary)', fontSize: labelSize, textTransform: 'uppercase', letterSpacing: '.06em' }}>
                  {c.label}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  (window.FlorioTabs = window.FlorioTabs || {}).live = Live;
})();
