/* Summer camp teaser and public-site announcement. Details are unannounced. */

const CAMP_ANNOUNCEMENT_SESSION_KEY = 'wkyhb:camp-announcement:2028';
const CAMP_POPUP_SESSION_KEY = 'wkyhb:camp-popup:2028';
const CAMP_POPUP_DELAY_MS = 5000;
const CAMP_ANNOUNCEMENT_DISMISSED_EVENT = 'wkCampAnnouncementDismissed';

// Keep real URLs for sharing and new tabs while using the site's router for
// ordinary clicks. A blocked navigation (e.g. unsaved form) stays blocked.
function followCampLink(event, key) {
  if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
  event.preventDefault();
  window.U.goTo(key);
}

function CampAnnouncement({ route }) {
  const [dismissed, setDismissed] = React.useState(() => {
    try { return window.sessionStorage.getItem(CAMP_ANNOUNCEMENT_SESSION_KEY) === 'dismissed'; }
    catch { return false; }
  });
  const camp = window.WKYHB.camp;
  // Keep private workspaces free of promotional content. The camp page is
  // already the announcement, so don't repeat the banner there.
  if (!camp.announcementActive || dismissed || ['camp', 'admin', 'scholarship-demo'].includes(route)) return null;

  const dismiss = (event) => {
    const hadFocus = document.activeElement === event.currentTarget;
    try { window.sessionStorage.setItem(CAMP_ANNOUNCEMENT_SESSION_KEY, 'dismissed'); }
    catch { /* Dismissal still works when browser storage is unavailable. */ }
    setDismissed(true);
    window.dispatchEvent(new Event(CAMP_ANNOUNCEMENT_DISMISSED_EVENT));
    if (hadFocus) document.querySelector('.wk-nav-brand')?.focus();
  };

  return (
    <aside className="wk-camp-announcement" aria-label="Summer camp announcement">
      <div className="wk-container wk-camp-announcement-inner">
        <span className="wk-camp-announcement-year" aria-hidden="true">2028</span>
        <div className="wk-camp-announcement-copy">
          <span className="wk-camp-kicker">Something big is coming</span>
          <p>FC summer camp <span className="wk-camp-announcement-season"><span className="wk-camp-announcement-separator" aria-hidden="true">· </span>{camp.season}</span></p>
        </div>
        <a className="wk-camp-button wk-camp-button-light" href="/camp" onClick={(event) => followCampLink(event, 'camp')}>
          See what’s coming <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6" /></svg>
        </a>
        <button className="wk-camp-dismiss" type="button" aria-label="Dismiss summer camp announcement" onClick={dismiss}>
          <span aria-hidden="true">×</span>
        </button>
      </div>
    </aside>
  );
}

function CampPopup({ route }) {
  const U = window.U;
  const camp = window.WKYHB.camp;
  const [open, setOpen] = React.useState(false);
  const seen = React.useRef(false);
  const returnFocus = React.useRef(null);
  const timer = React.useRef(null);

  // Remember banner dismissal on any public page, even without storage.
  React.useEffect(() => {
    const cancel = () => {
      window.clearTimeout(timer.current);
      seen.current = true;
      setOpen(false);
    };
    window.addEventListener(CAMP_ANNOUNCEMENT_DISMISSED_EVENT, cancel);
    return () => window.removeEventListener(CAMP_ANNOUNCEMENT_DISMISSED_EVENT, cancel);
  }, []);

  React.useEffect(() => {
    if (route !== 'home') { setOpen(false); return; }
    if (!camp.popupActive || seen.current) return;
    try {
      if (window.sessionStorage.getItem(CAMP_POPUP_SESSION_KEY) === 'seen'
        || window.sessionStorage.getItem(CAMP_ANNOUNCEMENT_SESSION_KEY) === 'dismissed') {
        seen.current = true;
        return;
      }
    } catch { /* The current app still remembers that the popup was shown. */ }
    // Give visitors a quiet moment to settle in. Navigation cancels the wait;
    // scrolling, keyboard use and clicks restart it rather than interrupting.
    const schedule = () => {
      window.clearTimeout(timer.current);
      if (seen.current || document.visibilityState !== 'visible') return;
      timer.current = window.setTimeout(() => {
        try {
          if (window.sessionStorage.getItem(CAMP_POPUP_SESSION_KEY) === 'seen'
            || window.sessionStorage.getItem(CAMP_ANNOUNCEMENT_SESSION_KEY) === 'dismissed') {
            seen.current = true;
            return;
          }
        } catch { /* Storage may be unavailable; in-memory dismissal still works. */ }
        // Let an existing dialog finish before introducing the announcement.
        if (document.querySelector('dialog[open]')) { schedule(); return; }
        seen.current = true;
        try { window.sessionStorage.setItem(CAMP_POPUP_SESSION_KEY, 'seen'); }
        catch { /* Showing the announcement does not depend on browser storage. */ }
        returnFocus.current = document.activeElement === document.body
          ? document.querySelector('.wk-nav-brand') : document.activeElement;
        setOpen(true);
      }, CAMP_POPUP_DELAY_MS);
    };
    schedule();
    document.addEventListener('visibilitychange', schedule);
    window.addEventListener('scroll', schedule, { passive: true });
    window.addEventListener('pointerdown', schedule, { passive: true });
    window.addEventListener('keydown', schedule);
    return () => {
      window.clearTimeout(timer.current);
      document.removeEventListener('visibilitychange', schedule);
      window.removeEventListener('scroll', schedule);
      window.removeEventListener('pointerdown', schedule);
      window.removeEventListener('keydown', schedule);
    };
  }, [route, camp.popupActive]);

  const close = () => {
    setOpen(false);
    requestAnimationFrame(() => {
      if (returnFocus.current?.isConnected) returnFocus.current.focus({ preventScroll: true });
    });
  };

  return (
    <U.Modal open={open && camp.popupActive && route === 'home'} onClose={close} maxWidth={680} restoreFocus={false}>
      <div className="wk-camp-popup">
        <button className="wk-camp-popup-close" type="button" aria-label="Close summer camp announcement" onClick={close} autoFocus><span aria-hidden="true">×</span></button>
        <p className="wk-camp-kicker">FC summer camp <span className="wk-camp-popup-coming">Coming soon</span></p>
        <div className="wk-camp-popup-season" aria-hidden="true">
          <span className="wk-camp-popup-summer">Summer</span>
          <span className="wk-camp-popup-year">2028</span>
        </div>
        <h2 id="camp-popup-title">Something big is coming.</h2>
        <p className="wk-camp-popup-body">An FC summer camp is coming in summer 2028. More details will be announced here.</p>
        <div className="wk-camp-popup-actions">
          <a className="wk-camp-button wk-camp-button-crimson" href="/camp" onClick={(event) => {
            if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
            close();
            followCampLink(event, 'camp');
          }}>See the camp announcement <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6" /></svg></a>
          <button className="wk-camp-popup-later" type="button" onClick={close}>Keep exploring</button>
        </div>
      </div>
    </U.Modal>
  );
}

function Camp() {
  const camp = window.WKYHB.camp;
  return (
    <React.Fragment>
      <header className="wk-camp-hero">
        <div className="wk-container wk-camp-hero-inner">
          <div className="wk-camp-hero-copy">
            <p className="wk-camp-kicker">Florida College · Summer camp</p>
            <h1>Something big<br />is coming.</h1>
            <p className="wk-camp-hero-lead">A new summer is on the horizon.</p>
            <p className="wk-camp-hero-body">An FC summer camp is coming in summer 2028. We’re just getting started, and there’s more to share as plans take shape.</p>
            <span className="wk-camp-status"><span aria-hidden="true" />Coming {camp.season.toLowerCase()}</span>
          </div>
          <div className="wk-camp-poster" aria-hidden="true">
            <div className="wk-camp-poster-sun" />
            <span className="wk-camp-poster-kicker">On the horizon</span>
            <span className="wk-camp-poster-summer">Summer</span>
            <span className="wk-camp-poster-year">2028</span>
            <div className="wk-camp-poster-horizon" />
            <span className="wk-camp-poster-footer">FC summer camp · Coming soon</span>
          </div>
        </div>
        <div className="wk-camp-hero-footer"><span>Summer 2028</span><span>More to come</span><span>Stay tuned</span></div>
      </header>
      <section className="wk-camp-updates" aria-labelledby="camp-updates-heading">
        <div className="wk-container wk-camp-updates-inner">
          <div>
            <p className="wk-camp-kicker">This is just the beginning</p>
            <h2 id="camp-updates-heading">The details are still ahead.</h2>
            <p>For now, keep summer 2028 on your radar. Check back here for the camp name, dates, location, and everything else as it’s announced.</p>
          </div>
          <div className="wk-camp-update-actions">
            <a className="wk-camp-button wk-camp-button-crimson" href={window.WKYHB.links.newsletter} target="_blank" rel="noopener">Follow chapter updates <window.U.IconExternal /></a>
            <a className="wk-camp-home-link" href={window.WKYHB.links.camps} target="_blank" rel="noopener">About FC summer camps <window.U.IconExternal /></a>
            <a className="wk-camp-home-link" href="/" onClick={(event) => followCampLink(event, 'home')}>Back to home <span aria-hidden="true">→</span></a>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

window.CampAnnouncement = CampAnnouncement;
window.CampPopup = CampPopup;
window.Pages = window.Pages || {};
window.Pages.camp = Camp;
