// Simple mode home: greeting, draggable card carousel, today's events.
const UD_VERSES = ['Philippians 4:13','Joshua 1:9','Isaiah 40:31','Proverbs 3:5-6','Jeremiah 29:11','Psalm 23:1','Romans 8:28','Matthew 11:28','Psalm 46:1','2 Timothy 1:7','Colossians 3:23','Psalm 118:24','Proverbs 16:3','Lamentations 3:22-23','Isaiah 41:10','Psalm 37:5','Galatians 6:9','1 Corinthians 16:14','Hebrews 12:1','Psalm 121:1-2','Matthew 6:34','Romans 12:12','Psalm 34:8','Ecclesiastes 9:10','Micah 6:8','John 14:27','1 Peter 5:7','Psalm 19:14','Nehemiah 8:10','Zephaniah 3:17','James 1:5'];
function DailyVerse() {
  const today = new Date().toISOString().slice(0, 10);
  const [v, setV] = React.useState(() => { try { const c = JSON.parse(localStorage.getItem('ud_verse') || 'null'); return c && c.day === today ? c : null; } catch (e) { return null; } });
  React.useEffect(() => {
    if (v) return;
    const day = Math.floor(Date.now() / 86400000); const ref = UD_VERSES[day % UD_VERSES.length];
    fetch('https://bible-api.com/' + encodeURIComponent(ref) + '?translation=web').then((r) => r.json()).then((d) => { const x = { day: today, text: String(d.text || '').replace(/\s+/g, ' ').trim(), ref: d.reference || ref }; if (x.text) { setV(x); try { localStorage.setItem('ud_verse', JSON.stringify(x)); } catch (e) {} } }).catch(() => {});
  }, []);
  if (!v) return null;
  return <div className="ud-verse" style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginTop: 12, maxWidth: 640, color: 'rgba(255,255,255,.88)' }}>
    <i className="hgi hgi-stroke hgi-rounded hgi-book-open-01" style={{ fontSize: 18, color: 'var(--orange-300, #F2A46B)', marginTop: 3, flexShrink: 0 }}></i>
    <div style={{ minWidth: 0, fontSize: 14, lineHeight: 1.5, fontStyle: 'italic', textWrap: 'pretty' }}>“{v.text}” <span style={{ fontStyle: 'normal', fontWeight: 700, color: 'white', whiteSpace: 'nowrap' }}>{v.ref}</span></div>
  </div>;
}

const UD_WX = { 0: ['Clear', 'sun-03'], 1: ['Mostly clear', 'sun-03'], 2: ['Partly cloudy', 'sun-cloud-01'], 3: ['Cloudy', 'cloud'], 45: ['Foggy', 'cloud'], 48: ['Foggy', 'cloud'], 51: ['Light drizzle', 'cloud-angled-rain'], 53: ['Drizzle', 'cloud-angled-rain'], 55: ['Heavy drizzle', 'cloud-angled-rain'], 61: ['Light rain', 'cloud-angled-rain'], 63: ['Rain', 'cloud-angled-rain'], 65: ['Heavy rain', 'cloud-angled-rain'], 80: ['Rain showers', 'cloud-angled-rain'], 81: ['Rain showers', 'cloud-angled-rain'], 82: ['Heavy showers', 'cloud-angled-rain'], 95: ['Thunderstorm', 'cloud-angled-zap'], 96: ['Thunderstorm', 'cloud-angled-zap'], 99: ['Thunderstorm', 'cloud-angled-zap'] };
const udWx = (c, night) => { const w = UD_WX[c] || ['Cloudy', 'cloud']; return night && c <= 1 ? [w[0], 'moon-02'] : w; };
function WxRow({ cls, children }) {
  const ref = React.useRef(null);
  const [edge, setEdge] = React.useState({ l: false, r: false });
  const upd = () => { const el = ref.current; if (!el) return; setEdge({ l: el.scrollLeft > 4, r: el.scrollLeft + el.clientWidth < el.scrollWidth - 4 }); };
  React.useEffect(() => { upd(); const ro = new ResizeObserver(upd); if (ref.current) ro.observe(ref.current); return () => ro.disconnect(); }, []);
  const by = (dir) => { const el = ref.current; if (el) el.scrollBy({ left: dir * el.clientWidth * 0.8, behavior: 'smooth' }); };
  return <div className="ud-wx-row">
    <button type="button" className="ud-wx-arrow l" aria-label="Scroll left" disabled={!edge.l} onClick={() => by(-1)}><i className="hgi hgi-stroke hgi-rounded hgi-arrow-left-01"></i></button>
    <div ref={ref} className={cls} onScroll={upd}>{children}</div>
    <button type="button" className="ud-wx-arrow r" aria-label="Scroll right" disabled={!edge.r} onClick={() => by(1)}><i className="hgi hgi-stroke hgi-rounded hgi-arrow-right-01"></i></button>
  </div>;
}

function WeatherPanel({ onBack }) {
  const [d, setD] = React.useState(() => window.__udWxCache || null);
  const [err, setErr] = React.useState(false);
  const [why, setWhy] = React.useState('');
  const [pct, setPct] = React.useState(() => window.__udWxCache ? 100 : 0);
  const [shown, setShown] = React.useState(() => window.__udWxCache || null);
  React.useEffect(() => { if (shown || err) return; const id = setInterval(() => setPct((p) => d ? Math.min(100, p + 12) : Math.min(92, p + Math.max(0.6, (92 - p) * 0.06))), 60); return () => clearInterval(id); }, [d, shown, err]);
  React.useEffect(() => { if (d && pct >= 100) { const tm = setTimeout(() => setShown(d), 180); return () => clearTimeout(tm); } }, [d, pct]);
  const load = React.useCallback(() => {
    setErr(false); setWhy(''); setPct(0); setShown(null); setD(null);
    const base = 'https://api.open-meteo.com/v1/forecast?latitude=14.5869&longitude=121.0614&timezone=Asia%2FManila&forecast_days=7';
    const full = base + '&current=temperature_2m,apparent_temperature,relative_humidity_2m,wind_speed_10m,weather_code,is_day&hourly=temperature_2m,weather_code,precipitation_probability,is_day&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max';
    const get2 = (u) => { const ctl = new AbortController(); const tm = setTimeout(() => ctl.abort(), 12000); return fetch(u, { signal: ctl.signal }).then((r) => { clearTimeout(tm); if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); }); };
    const get = (u) => { const ctl = new AbortController(); const tm = setTimeout(() => ctl.abort(), 7000); return fetch(u, { signal: ctl.signal }).then((r) => r.json().then((x) => { clearTimeout(tm); if (!r.ok || x.error || !x.current) throw new Error(x.reason || ('HTTP ' + r.status)); return x; })); };
    const wwo = (c) => { c = Number(c); return c === 113 ? 0 : c === 116 ? 2 : (c === 119 || c === 122) ? 3 : [143, 248, 260].includes(c) ? 45 : [200, 386, 389, 392, 395].includes(c) ? 95 : [176, 263, 266, 293, 296, 353].includes(c) ? 61 : [299, 302, 356].includes(c) ? 63 : [305, 308, 359].includes(c) ? 65 : 3; };
    const viaWttr = () => get2('https://wttr.in/Ortigas,Pasig?format=j1').then((w) => {
      const cc = w.current_condition[0], hn = Number(new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Manila', hour: 'numeric', hourCycle: 'h23' }).format(new Date()));
      const hourly = { time: [], temperature_2m: [], weather_code: [], precipitation_probability: [], is_day: [] };
      w.weather.forEach((dd) => dd.hourly.forEach((x) => { const hh = Math.floor(Number(x.time) / 100); hourly.time.push(dd.date + 'T' + String(hh).padStart(2, '0') + ':00'); hourly.temperature_2m.push(Number(x.tempC)); hourly.weather_code.push(wwo(x.weatherCode)); hourly.precipitation_probability.push(Number(x.chanceofrain) || 0); hourly.is_day.push(hh >= 6 && hh < 18 ? 1 : 0); }));
      const today = w.weather[0].date;
      return { current: { time: today + 'T' + String(hn).padStart(2, '0') + ':00', temperature_2m: Number(cc.temp_C), apparent_temperature: Number(cc.FeelsLikeC), relative_humidity_2m: Number(cc.humidity), wind_speed_10m: Number(cc.windspeedKmph), weather_code: wwo(cc.weatherCode), is_day: hn >= 6 && hn < 18 ? 1 : 0 },
        hourly, daily: { time: w.weather.map((x) => x.date), weather_code: w.weather.map((x) => wwo((x.hourly[4] || x.hourly[0]).weatherCode)), temperature_2m_max: w.weather.map((x) => Number(x.maxtempC)), temperature_2m_min: w.weather.map((x) => Number(x.mintempC)), precipitation_probability_max: w.weather.map((x) => Math.max.apply(null, x.hourly.map((y) => Number(y.chanceofrain) || 0))) }, short: true };
    });
    get(full).catch((e1) => { console.warn('[weather] open-meteo failed, trying wttr.in:', e1); return viaWttr(); })
      .then((x) => { window.__udWxCache = x; setD(x); }).catch((e) => { console.error('[weather] failed:', e); setWhy(e && e.name === 'AbortError' ? 'The weather service took too long to answer.' : String((e && e.message) || e)); setErr(true); });
  }, []);
  React.useEffect(() => { if (!window.__udWxCache) load(); }, []);
  const back = <button type="button" className="ud-wx-back" onClick={onBack}><i className="hgi hgi-stroke hgi-rounded hgi-arrow-left-01"></i>Back to tasks</button>;
  if (err) return <div className="ud-wx">{back}<div className="ud-wx-msg">Weather is not available right now.<small>{why}</small><button type="button" className="ud-wx-back" onClick={load}><i className="hgi hgi-stroke hgi-rounded hgi-refresh"></i>Try again</button></div></div>;
  if (!shown) return <div className="ud-wx">{back}<div className="ud-wx-load"><i className="hgi hgi-stroke hgi-rounded hgi-sun-cloud-01"></i><div className="ud-wx-load-t">Getting the forecast for Ortigas, Pasig</div><div className="ud-wx-load-bar"><span style={{ width: pct + '%' }}></span></div><b>{Math.round(pct)}%</b></div></div>;
  const dd = shown; const c = dd.current, now = udWx(c.weather_code, !c.is_day);
  const i0 = Math.max(0, dd.hourly.time.findIndex((t) => t >= c.time.slice(0, 13) + ':00'));
  const hours = dd.hourly.time.slice(i0, i0 + 12).map((t, k) => ({ t, temp: dd.hourly.temperature_2m[i0 + k], rain: dd.hourly.precipitation_probability[i0 + k], w: udWx(dd.hourly.weather_code[i0 + k], !dd.hourly.is_day[i0 + k]) }));
  const hr = (t) => { const n = Number(t.slice(11, 13)); return n === 0 ? '12 AM' : n < 12 ? n + ' AM' : n === 12 ? '12 PM' : (n - 12) + ' PM'; };
  const day = (t, k) => k === 0 ? 'Today' : new Date(t + 'T12:00:00+08:00').toLocaleDateString('en-US', { weekday: 'short', timeZone: 'Asia/Manila' });
  return <div className="ud-wx">
    {back}
    <WxRow cls="ud-wx-grid">
      <div className="ud-wx-now">
        <div className="ud-wx-place"><i className="hgi hgi-stroke hgi-rounded hgi-location-01"></i>Ortigas, Pasig</div>
        <div className="ud-wx-temp"><i className={'hgi hgi-stroke hgi-rounded hgi-' + now[1]}></i><b>{Math.round(c.temperature_2m)}°</b></div>
        <div className="ud-wx-cond">{now[0]}</div>
        <div className="ud-wx-meta"><span>Feels like <b>{Math.round(c.apparent_temperature)}°</b></span><span>Humidity <b>{c.relative_humidity_2m}%</b></span><span>Wind <b>{Math.round(c.wind_speed_10m)} km/h</b></span><span>High <b>{Math.round(dd.daily.temperature_2m_max[0])}°</b> · Low <b>{Math.round(dd.daily.temperature_2m_min[0])}°</b></span></div>
      </div>
      <div className="ud-wx-side">
        <div className="ud-wx-card"><div className="ud-wx-h">Next 12 hours</div>
          <WxRow cls="ud-wx-hours">{hours.map((x, k) => <div key={x.t}><span>{k === 0 ? 'Now' : hr(x.t)}</span><i className={'hgi hgi-stroke hgi-rounded hgi-' + x.w[1]}></i><b>{Math.round(x.temp)}°</b><small>{x.rain > 0 ? x.rain + '%' : ''}</small></div>)}</WxRow>
        </div>
        <div className="ud-wx-card"><div className="ud-wx-h">{dd.short ? dd.daily.time.length + '-day forecast' : '7-day forecast'}</div>
          <WxRow cls="ud-wx-days">{dd.daily.time.map((t, k) => { const w = udWx(dd.daily.weather_code[k]); return <div key={t}><span className="d">{day(t, k)}</span><i className={'hgi hgi-stroke hgi-rounded hgi-' + w[1]}></i><span className="c">{w[0]}</span><span className="r">{dd.daily.precipitation_probability_max[k] ? dd.daily.precipitation_probability_max[k] + '% rain' : ''}</span><span className="t"><b>{Math.round(dd.daily.temperature_2m_max[k])}°</b> {Math.round(dd.daily.temperature_2m_min[k])}°</span></div>; })}</WxRow>
        </div>
      </div>
    </WxRow>
  </div>;
}

function ManilaClock({ onClick, open }) {
  const [now, setNow] = React.useState(() => new Date());
  React.useEffect(() => { const id = setInterval(() => setNow(new Date()), 15000); return () => clearInterval(id); }, []);
  const tz = 'Asia/Manila';
  const hr = Number(new Intl.DateTimeFormat('en-US', { timeZone: tz, hour: 'numeric', hourCycle: 'h23' }).format(now));
  const part = hr < 5 ? ['Midnight', 'moon-02'] : hr < 12 ? ['Morning', 'sunrise'] : hr < 13 ? ['Noon', 'sun-03'] : hr < 18 ? ['Afternoon', 'sun-cloud-01'] : ['Evening', 'sunset'];
  const date = new Intl.DateTimeFormat('en-US', { timeZone: tz, month: 'long', day: 'numeric', year: 'numeric' }).format(now);
  const time = new Intl.DateTimeFormat('en-US', { timeZone: tz, hour: 'numeric', minute: '2-digit' }).format(now);
  return <button type="button" className={'ud-clock' + (open ? ' on' : '')} title={open ? 'Back to tasks' : 'See the weather in Ortigas'} onClick={onClick}>
    <i className={'hgi hgi-stroke hgi-rounded hgi-' + part[1]}></i>
    <div><b>{time}</b><span>{date}</span></div>
    <i className="hgi hgi-stroke hgi-rounded hgi-arrow-right-01 ud-clock-go"></i>
  </button>;
}

function HomeScreen({ adminUser, go }) {
  const [pending, setPending] = React.useState(null);
  const [today, setToday] = React.useState(null);
  const [active, setActive] = React.useState(2);
  const [wx, setWxRaw] = React.useState(false);
  const [wxMounted, setWxMounted] = React.useState(false);
  const wxRef = React.useRef(false);
  const lastActive = React.useRef(2);
  const setWx = (v) => { const next = typeof v === 'function' ? v(wxRef.current) : v; wxRef.current = next; if (next) setWxMounted(true); else setTimeout(() => { if (!wxRef.current) setWxMounted(false); }, 450); setWxRaw(next); };
  const track = React.useRef(null);
  const drag = React.useRef(null);
  React.useEffect(() => {
    window.sb.from('orders').select('id', { count: 'exact', head: true }).eq('status', 'pending_verification')
      .then(({ count }) => setPending(count || 0)).catch(() => setPending(0));
    const d = new Date(), start = new Date(d.getFullYear(), d.getMonth(), d.getDate()), end = new Date(start.getTime() + 864e5);
    window.sb.from('sub_events').select('id,title,starts_at,ends_at,main_events(title,deleted_at)').is('deleted_at', null)
      .lt('starts_at', end.toISOString()).gte('ends_at', start.toISOString()).order('starts_at')
      .then(({ data }) => setToday((data || []).filter((s) => !s.main_events || !s.main_events.deleted_at))).catch(() => setToday([]));
  }, []);
  const manilaHour = () => Number(new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Manila', hour: 'numeric', hourCycle: 'h23' }).format(new Date()));
  const [h, setH] = React.useState(manilaHour);
  React.useEffect(() => { const id = setInterval(() => setH(manilaHour()), 15000); return () => clearInterval(id); }, []);
  const hello = h < 5 ? 'Good evening' : h < 12 ? 'Good morning' : h < 18 ? 'Good afternoon' : 'Good evening';
  const t = (iso) => new Date(iso).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
  const ico = (d, s) => <svg width={s || 34} height={s || 34} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d={d} /></svg>;
  const cards = [
    { key: 'find', hgi: 'search-01', title: 'Find a person or order', sub: 'Search by name, email or booking reference.', cta: 'Search', icon: 'M11 19a8 8 0 100-16 8 8 0 000 16zM21 21l-4.3-4.3' },
    { key: 'forms', hgi: 'check-list', title: 'Participant forms', sub: 'See who filled in their form, plus food, health and emergency lists.', cta: 'Open forms', icon: 'M9 2h6a1 1 0 011 1v2H8V3a1 1 0 011-1zM8 4H6a2 2 0 00-2 2v14a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-2M9 13l2 2 4-4' },
    { key: 'verify', hgi: 'task-done-01', big: pending == null ? '…' : String(pending), bigLabel: pending === 1 ? 'payment waiting' : 'payments waiting', title: 'Verify payments', sub: 'Check the proof of payment and approve it so the person gets their confirmation.', cta: 'Start verifying', icon: 'M9 12l2 2 4-4M12 22a10 10 0 100-20 10 10 0 000 20z' },
    { key: 'create', hgi: 'add-circle', title: 'Create an event', sub: 'Add a new event with its dates, tickets and prices.', cta: 'Create', icon: 'M12 5v14M5 12h14' },
    { key: 'money', hgi: 'money-bag-02', title: 'See money in', sub: 'Payments received and totals for each event.', cta: 'Open Money', icon: 'M12 1v22M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6' },
    { key: 'admin', hgi: 'user-add-01', title: 'Add an admin', sub: 'Give someone from the team access to this dashboard.', cta: 'Add admin', icon: 'M16 21v-2a4 4 0 00-4-4H6a4 4 0 00-4 4v2M9 11a4 4 0 100-8 4 4 0 000 8zM19 8v6M22 11h-6' },
  ];
  const START = cards.findIndex((c) => c.key === 'verify');
  const pad = () => { const el = track.current; if (!el || !el.children[0]) return; const p = Math.max(0, (el.clientWidth - el.children[0].offsetWidth) / 2); el.style.paddingLeft = p + 'px'; el.style.paddingRight = p + 'px'; };
  const scrollTo = (i, instant) => { const el = track.current; if (!el) return; i = Math.max(0, Math.min(cards.length - 1, i)); const c = el.children[i]; if (c) el.scrollTo({ left: c.offsetLeft - (el.clientWidth - c.offsetWidth) / 2, behavior: instant ? 'auto' : 'smooth' }); };
  const onScroll = () => {
    const el = track.current; if (!el) return; const mid = el.scrollLeft + el.clientWidth / 2; let best = 0, bd = 1e9;
    Array.prototype.forEach.call(el.children, (c, i) => { const cm = c.offsetLeft + c.offsetWidth / 2; const dist = Math.abs(cm - mid); if (dist < bd) { bd = dist; best = i; } const k = Math.min(1, dist / (c.offsetWidth * 1.2)); c.style.setProperty('--k', k.toFixed(3)); });
    if (wxRef.current) return;
    lastActive.current = best; setActive(best);
  };
  React.useEffect(() => { pad(); scrollTo(START, true); onScroll(); requestAnimationFrame(() => { scrollTo(START, true); onScroll(); }); const r = () => { pad(); onScroll(); }; window.addEventListener('resize', r); return () => window.removeEventListener('resize', r); }, []);
  const down = (e) => { if (e.pointerType !== 'mouse') return; const el = track.current; drag.current = { x: e.clientX, l: el.scrollLeft, moved: false }; el.classList.add('dragging'); };
  const move = (e) => { const d = drag.current; if (!d) return; const dx = e.clientX - d.x; if (Math.abs(dx) > 4) d.moved = true; track.current.scrollLeft = d.l - dx; };
  const up = () => { const d = drag.current; if (!d) return; drag.current = null; track.current.classList.remove('dragging'); if (d.moved) { setTimeout(() => scrollTo(active), 10); } };
  const click = (i) => { if (drag.current && drag.current.moved) return; if (i !== active) scrollTo(i); };
  return (
    <div className="ud-home">
      <div className="ud-home-hero">
        <div className="ud-home-hi">
          <ManilaClock open={wx} onClick={() => setWx((v) => !v)} />
          <h1>{hello}, {adminUser.first_name || 'there'}</h1>
          <DailyVerse />
        </div>
        <div className={'ud-home-swap' + (wx ? ' wx' : '')}>
        {wxMounted ? <div className="ud-wx-layer" aria-hidden={!wx}><WeatherPanel onBack={() => setWx(false)} /></div> : null}
        <div className="ud-car-wrap" aria-hidden={wx}>
          <button type="button" className="ud-car-arrow l" aria-label="Previous" disabled={active <= 0} onClick={() => scrollTo(active - 1)}><i className="hgi hgi-stroke hgi-rounded hgi-arrow-left-01" style={{ fontSize: 22 }}></i></button>
          <div ref={track} className="ud-car" onScroll={onScroll} onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerLeave={up}>
            {cards.map((c, i) => (
              <div key={c.key} className={'ud-card' + (i === active ? ' on' : '')} onClick={() => click(i)} aria-label={c.title}>
                <div className="ud-card-top">
                  {c.big != null ? <div className="ud-card-big"><b>{c.big}</b><span>{c.bigLabel}</span></div> : <span className="ud-card-ico"><i className={'hgi hgi-stroke hgi-rounded hgi-' + c.hgi} style={{ fontSize: 32 }}></i></span>}
                </div>
                <div className="ud-card-title">{c.title}</div>
                <div className="ud-card-sub">{c.sub}</div>
                <button type="button" className="ud-card-cta" tabIndex={i === active ? 0 : -1} onClick={(e) => { e.stopPropagation(); if (i === active) go(c.key); else scrollTo(i); }}>{c.cta}<i className="hgi hgi-stroke hgi-rounded hgi-arrow-right-02" style={{ fontSize: 18 }}></i></button>
              </div>
            ))}
          </div>
          <button type="button" className="ud-car-arrow r" aria-label="Next" disabled={active >= cards.length - 1} onClick={() => scrollTo(active + 1)}><i className="hgi hgi-stroke hgi-rounded hgi-arrow-right-01" style={{ fontSize: 22 }}></i></button>
        </div>
        </div>
      </div>
      <section className="ud-glass ud-today">
        <div className="ud-today-h">Today's events</div>
        {today === null ? <window.UdSkeleton variant="table" /> : today.length === 0 ? <div className="ud-today-empty">No events today.</div> : today.map((s) => (
          <div key={s.id} className="ud-today-row">
            <span className="ud-today-time">{t(s.starts_at)} to {t(s.ends_at)}</span>
            <span className="ud-today-name"><b>{s.title}</b>{s.main_events && <small>{s.main_events.title}</small>}</span>
            <window.UdUI.Btn onClick={() => go('checkin')}>Check people in</window.UdUI.Btn>
          </div>
        ))}
      </section>
    </div>
  );
}
window.HomeScreen = HomeScreen;
