// app-web.jsx — root for the deployed website (no phone frame, mobile-first responsive)

const TWEAK_DEFAULTS_WEB = /*EDITMODE-BEGIN*/{
  "palette": "auto",
  "season": "pentecost",
  "useSeasonAccent": false,
  "typePair": "classic",
  "density": "spacious",
  "nav": "tabs",
  "hero": "image",
  "feastDemo": "auto"
}/*EDITMODE-END*/;

function WebApp() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS_WEB);
  const autoSeason = detectSeason();
  const effective = { ...tweaks, season: tweaks.seasonAuto === false ? tweaks.season : autoSeason };

  // Re-render when the OS color-scheme preference changes (auto dark/light).
  // No-op when palette isn't 'auto', but cheap and handles user toggling
  // their phone's appearance setting while the page is open.
  const [, _bumpColor] = React.useState(0);
  React.useEffect(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    const onChange = () => _bumpColor(k => k + 1);
    if (mq.addEventListener) mq.addEventListener('change', onChange);
    else if (mq.addListener) mq.addListener(onChange);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', onChange);
      else if (mq.removeListener) mq.removeListener(onChange);
    };
  }, []);

  const theme = buildTheme(effective);

  // Hash-routing — gives real shareable URLs (#/give, #/visit, etc.) without a build step.
  const parseHash = () => {
    const h = (window.location.hash || '').replace(/^#\/?/, '').trim();
    return h || 'home';
  };
  const [route, _setRoute] = React.useState(parseHash);
  React.useEffect(() => {
    const onHash = () => _setRoute(parseHash());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  const setRoute = (r) => {
    window.location.hash = r === 'home' ? '' : '#/' + r;
    _setRoute(r);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const [modal, setModal] = React.useState(null);
  const welcome = useWelcomeFlow(90000);
  const feast = tweaks.feastDemo && tweaks.feastDemo !== 'auto' ? tweaks.feastDemo : detectFeast();

  const screen = (() => {
    switch (route) {
      case 'give':    return <GiveScreen   theme={theme} onBack={() => setRoute('home')} />;
      case 'visit':   return <VisitScreen  theme={theme} onBack={() => setRoute('home')} />;
      case 'prayer':  return <PrayerScreen theme={theme} onBack={() => setRoute('home')} setModal={setModal} />;
      case 'events':  return <EventsScreen theme={theme} onBack={() => setRoute('home')} />;
      case 'about':   return <AboutScreen  theme={theme} onBack={() => setRoute('home')} />;
      case 'office':  return <OfficeScreen theme={theme} onBack={() => setRoute('home')} />;
      // /sunday → land on home (legacy bookmarks won't 404)
      case 'sunday':  return <HomeScreen   theme={theme} onNav={setRoute} setModal={setModal} />;
      default:        return <HomeScreen   theme={theme} onNav={setRoute} setModal={setModal} />;
    }
  })();

  // Page title sync for shareable URLs
  React.useEffect(() => {
    const titles = {
      home: 'Monticello United Methodist Church',
      give: 'Offerings — Monticello UMC',
      visit: 'You Are Welcome Here — Monticello UMC',
      prayer: 'Prayer Wall — Monticello UMC',
      events: 'Calendar and Events — Monticello UMC',
      about: 'What We Believe — Monticello UMC',
      office: 'The Daily Office — Monticello UMC',
    };
    document.title = titles[route] || titles.home;
  }, [route]);

  return (
    <div style={{
      position: 'relative',
      width: '100%',
      minHeight: '100vh',
      background: theme.bg,
      color: theme.ink,
    }}>
      {/* Mobile-first column. On desktop, content stays in a comfortable reading column
          centered on a parchment field — preserves the missal/devotional feel. */}
      <div className="mumc-shell" style={{
        position: 'relative',
        margin: '0 auto',
        minHeight: '100vh',
        background: theme.bg,
        boxShadow: 'var(--mumc-shell-shadow, none)',
      }} key={route}>
        {screen}
      </div>

      {/* Navigation overlays — fixed to viewport on the website */}
      {theme.nav === 'tower' && <WebTowerNav theme={theme} route={route} setRoute={setRoute} />}
      {theme.nav === 'tabs'  && <WebTabBarNav theme={theme} route={route} setRoute={setRoute} />}
      {theme.nav === 'float' && <WebFloatNav theme={theme} route={route} setRoute={setRoute} />}

      {/* Modals */}
      {modal === 'office' && <OfficeModal theme={theme} onClose={() => setModal(null)} />}
      {modal === 'pray'   && <PrayWithUsModal theme={theme} onClose={() => setModal(null)} />}
      {modal && modal.kind === 'lectionary' && <LectionaryModal theme={theme} onClose={() => setModal(null)} reading={modal.reading} />}
      {modal && modal.kind === 'share-verse' && (
        <VerseShareModal open={true} onClose={() => setModal(null)} theme={theme}
                         verse={modal.verse} cite={modal.cite} />
      )}

      {feast && <FeastOverlay feast={feast} theme={theme} />}
      {welcome && welcome.open && <WelcomeCard theme={theme} onClose={welcome.dismiss} />}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Color theme">
          <TweakRadio value={tweaks.palette} onChange={v => setTweak('palette', v)}
            options={[
              { value: 'auto',        label: 'Auto (system)' },
              { value: 'parchment',   label: 'Parchment' },
              { value: 'candlelight', label: 'Candlelight' },
              { value: 'sepia',       label: 'Sepia' },
            ]} />
        </TweakSection>
        <TweakSection title="Liturgical season">
          <TweakSelect value={tweaks.season} onChange={v => setTweak('season', v)}
            options={Object.entries(SEASONS).map(([k, v]) => ({ value: k, label: v.name }))} />
          <TweakToggle value={tweaks.useSeasonAccent} onChange={v => setTweak('useSeasonAccent', v)}
            label="Use season color as accent" />
        </TweakSection>
        <TweakSection title="Hero variation">
          <TweakSelect value={tweaks.hero} onChange={v => setTweak('hero', v)}
            options={[
              { value: 'manuscript', label: 'Manuscript + Chalice' },
              { value: 'verse',      label: 'Verse of the day' },
              { value: 'image',      label: 'Stained-glass image' },
              { value: 'livestream', label: 'Livestream' },
              { value: 'countdown',  label: 'Pure countdown' },
            ]} />
        </TweakSection>
        <TweakSection title="Navigation style">
          <TweakRadio value={tweaks.nav} onChange={v => setTweak('nav', v)}
            options={[
              { value: 'tower',  label: 'Bell tower' },
              { value: 'tabs',   label: 'Bottom tabs' },
              { value: 'float',  label: 'Floating' },
            ]} />
        </TweakSection>
        <TweakSection title="Typography">
          <TweakSelect value={tweaks.typePair} onChange={v => setTweak('typePair', v)}
            options={Object.entries(TYPE_PAIRS).map(([k, v]) => ({ value: k, label: v.name }))} />
        </TweakSection>
        <TweakSection title="Feast preview" subtitle="Try a feast-day Easter egg out of season">
          <TweakSelect value={tweaks.feastDemo} onChange={v => setTweak('feastDemo', v)}
            options={[
              { value: 'auto', label: 'Auto-detect (today)' },
              ...Object.entries(FEAST_INFO).map(([k, v]) => ({ value: k, label: v.name })),
            ]} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// Web-tuned navs — fixed-position on the viewport rather than absolute inside a phone

function WebTabBarNav({ theme, route, setRoute }) {
  const items = [
    { id: 'home',   icon: 'cross',  label: 'Home' },
    { id: 'about',  icon: 'book',   label: 'We Believe' },
    { id: 'prayer', icon: 'candle', label: 'Prayer' },
    { id: 'events', icon: 'star',   label: 'Calendar' },
    { id: 'give',   icon: 'alms',   label: 'Give' },
  ];
  return (
    <div style={{
      position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 100,
      paddingBottom: 'max(10px, env(safe-area-inset-bottom))', paddingTop: 8,
      background: theme.chrome === 'dark' ? 'rgba(34,26,19,0.96)' : 'rgba(250,245,232,0.96)',
      backdropFilter: 'blur(14px)',
      WebkitBackdropFilter: 'blur(14px)',
      borderTop: `1px solid ${theme.rule}`,
      display: 'flex', justifyContent: 'space-around',
    }}>
      {items.map(it => {
        const active = route === it.id;
        return (
          <button key={it.id} onClick={() => setRoute(it.id)} style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            color: active ? theme.accent : theme.inkMute, padding: '6px 8px',
          }}>
            {Icons[it.icon](22, active ? theme.accent : theme.inkMute)}
            <span style={{ ...smallCaps(theme, 8) }}>{it.label}</span>
          </button>
        );
      })}
    </div>
  );
}

function WebTowerNav({ theme, route, setRoute }) {
  const items = [
    { id: 'home',   icon: 'cross',  label: 'Home' },
    { id: 'about',  icon: 'book',   label: 'We Believe' },
    { id: 'prayer', icon: 'candle', label: 'Prayer' },
    { id: 'events', icon: 'star',   label: 'Calendar' },
    { id: 'give',   icon: 'alms',   label: 'Give' },
  ];
  return (
    <div style={{
      position: 'fixed', right: 12, top: '50%', transform: 'translateY(-50%)',
      zIndex: 100,
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      padding: '10px 6px',
      background: theme.chrome === 'dark' ? 'rgba(34,26,19,0.92)' : 'rgba(250,245,232,0.94)',
      backdropFilter: 'blur(10px)',
      WebkitBackdropFilter: 'blur(10px)',
      border: `1px solid ${theme.gold}55`,
      borderRadius: 4,
      boxShadow: '0 6px 24px rgba(0,0,0,0.18)',
    }}>
      <svg width="32" height="14" viewBox="0 0 32 14" style={{ marginBottom: 4 }}>
        <path d="M16 1 L31 13 L1 13 Z" fill={theme.gold} stroke={theme.gold} strokeWidth="1"/>
      </svg>
      <div style={{ width: 1, height: 6, background: theme.gold, marginBottom: 6 }} />
      {items.map((it) => {
        const active = route === it.id;
        return (
          <button key={it.id} onClick={() => setRoute(it.id)} style={{
            width: 36, height: 36, padding: 0,
            background: active ? theme.accent : 'transparent',
            border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: active ? theme.paper : theme.ink,
            margin: '2px 0', borderRadius: 2,
            transition: 'background 0.18s',
          }}>{Icons[it.icon](18, active ? theme.paper : theme.ink)}</button>
        );
      })}
      <div style={{ width: 1, height: 8, background: theme.gold, marginTop: 4 }} />
      <div style={{ width: 6, height: 6, borderRadius: '50%', background: theme.gold }} />
    </div>
  );
}

function WebFloatNav({ theme, route, setRoute }) {
  const [open, setOpen] = React.useState(false);
  const items = [
    { id: 'home',   icon: 'cross',  label: 'Home' },
    { id: 'about',  icon: 'book',   label: 'We Believe' },
    { id: 'prayer', icon: 'candle', label: 'Prayer' },
    { id: 'events', icon: 'star',   label: 'Calendar' },
    { id: 'give',   icon: 'alms',   label: 'Give' },
  ];
  return (
    <>
      {open && (
        <div onClick={() => setOpen(false)} style={{
          position: 'fixed', inset: 0, zIndex: 99,
          background: 'rgba(0,0,0,0.4)',
          animation: 'fadein 0.2s',
        }} />
      )}
      <div style={{
        position: 'fixed', right: 16, bottom: 'max(20px, env(safe-area-inset-bottom))', zIndex: 101,
        display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 10,
      }}>
        {open && items.map((it, i) => {
          const active = route === it.id;
          return (
            <button key={it.id} onClick={() => { setRoute(it.id); setOpen(false); }} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              background: 'transparent', border: 'none', cursor: 'pointer',
              animation: `fadein 0.2s ${i * 0.04}s both`,
            }}>
              <span style={{
                ...smallCaps(theme, 9), color: '#fff',
                background: 'rgba(0,0,0,0.6)', padding: '4px 8px', borderRadius: 2,
              }}>{it.label}</span>
              <span style={{
                width: 44, height: 44, borderRadius: '50%',
                background: active ? theme.accent : theme.paper,
                color: active ? theme.paper : theme.ink,
                border: `1px solid ${theme.gold}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
              }}>{Icons[it.icon](20, active ? theme.paper : theme.ink)}</span>
            </button>
          );
        })}
        <button onClick={() => setOpen(!open)} style={{
          width: 56, height: 56, borderRadius: '50%',
          background: theme.accent, color: theme.paper,
          border: `2px solid ${theme.gold}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
          boxShadow: '0 6px 20px rgba(0,0,0,0.3)',
          fontFamily: theme.fonts.display, fontSize: 28, lineHeight: 1,
          transform: open ? 'rotate(45deg)' : 'none',
          transition: 'transform 0.2s',
        }}>†</button>
      </div>
    </>
  );
}

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