/* journify.ai — CookieBanner: the cookie choice, on every route. Words: content/cookie-banner.json.
   It shows until the visitor chooses (components/consent.js keeps the choice and loads Google Tag Manager
   behind it). Accept and Reject are the same button, side by side, and nothing is ticked beforehand
   (Autoriteit Persoonsgegevens: saying no takes the same one click as saying yes). "Choose" opens the
   two rows. Any link whose href is #cookie-settings reopens it on the rows (content/footer.json,
   content/workshop-confirmed.json, the footer in the-sprint/sprint-sections-6-10.jsx), so consent can be
   withdrawn from every page. Its styles are here, written against styles/tokens-v2.css only, because
   /workshop/confirmed does not load styles/tokens.css. It sits bottom left; Sally sits bottom right. */

const COOKIE_CSS = `
.ck { position: fixed; z-index: 40; left: max(16px, env(safe-area-inset-left, 0px)); bottom: calc(16px + env(safe-area-inset-bottom, 0px)); width: min(420px, calc(100vw - 32px)); max-height: calc(100vh - 32px); overflow: auto; background: var(--card); color: var(--ink); border: 1px solid var(--ink-2); border-radius: var(--r-card); padding: var(--s-5); font-family: var(--font-text); }
.ck:focus { outline: none; }
.ck-title { margin: 0; font-family: var(--font-display); font-weight: var(--w-heading); font-stretch: var(--stretch-display); font-size: var(--fs-h3); line-height: var(--lh-h3); letter-spacing: var(--ls-h3); }
.ck-body { margin: var(--s-2) 0 0; font-size: var(--fs-small); line-height: var(--lh-small); }
.ck-body a { color: var(--link); text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 4px; }
.ck-body a:hover { color: var(--link-hover); }
.ck-actions { display: flex; gap: var(--s-2); margin-top: var(--s-4); }
.ck-btn { flex: 1 1 0; height: var(--control-h); padding: 0 var(--control-px); border: 0; border-radius: var(--r-control); background: var(--action); color: var(--on-action); font-family: var(--font-text); font-size: var(--fs-control); font-weight: var(--w-semibold); line-height: 1; cursor: pointer; transition: background-color var(--t-micro) var(--ease); }
.ck-btn:hover { background: var(--action-hover); }
.ck-text { display: block; margin: var(--s-2) auto 0; height: 36px; padding: 0 var(--text-button-px); border: 0; background: none; color: var(--link); font-family: var(--font-text); font-size: var(--fs-small); font-weight: var(--w-medium); cursor: pointer; }
.ck-text:hover { color: var(--link-hover); }
.ck-btn:focus-visible, .ck-text:focus-visible, .ck-body a:focus-visible, .ck-row input:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
.ck-rows { margin-top: var(--s-4); border-bottom: 1px solid var(--hairline); }
.ck-row { display: grid; grid-template-columns: var(--check) minmax(0, 1fr); column-gap: var(--s-3); padding: var(--s-3) 0; border-top: 1px solid var(--hairline); cursor: pointer; }
.ck-row.is-locked { cursor: default; }
.ck-row input { width: var(--check); height: var(--check); margin: 1px 0 0; accent-color: var(--action); }
.ck-row-name { display: block; font-size: var(--fs-small); line-height: var(--lh-small); font-weight: var(--w-medium); }
.ck-row-text { display: block; font-size: var(--fs-meta); line-height: var(--lh-meta); color: var(--ink-2); }
@media (max-width: 759px) { .ck { left: 12px; right: 12px; bottom: calc(12px + env(safe-area-inset-bottom, 0px)); width: auto; padding: var(--s-4); } }
@media print { .ck { display: none; } }
`;

function CookieBanner() {
  const [words, setWords] = React.useState(null);
  const [open, setOpen] = React.useState(() => !window.JournifyConsent.read());
  const [choosing, setChoosing] = React.useState(false);
  const [analytics, setAnalytics] = React.useState(false);
  const box = React.useRef(null), reopened = React.useRef(false);

  React.useEffect(() => {
    fetch('/content/cookie-banner.json').then(r => r.json()).then(setWords);
  }, []);

  /* a #cookie-settings link opens the rows, ticked as the visitor last saved them */
  React.useEffect(() => {
    const onClick = e => {
      if (!e.target.closest || !e.target.closest('a[href="#cookie-settings"]')) return;
      e.preventDefault();
      const saved = window.JournifyConsent.read();
      setAnalytics(!!(saved && saved.analytics));
      setChoosing(true);
      setOpen(true);
      reopened.current = true;
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);

  /* the keyboard follows the banner only when the visitor asked for it; on arrival it takes no focus */
  React.useEffect(() => {
    if (open && reopened.current && box.current) { box.current.focus(); reopened.current = false; }
  }, [open, words]);

  if (!words || !open) return null;

  const save = value => { window.JournifyConsent.save(value); setOpen(false); setChoosing(false); };

  return (
    <section ref={box} className="ck" role="dialog" aria-modal="false" aria-labelledby="ck-title" tabIndex={-1}>
      <style>{COOKIE_CSS}</style>
      <h2 id="ck-title" className="ck-title">{words.title}</h2>
      <p className="ck-body">{words.body} <a href={words.policy.href}>{words.policy.label}</a></p>
      {choosing ? (
        <>
          <div className="ck-rows">
            {words.rows.map(r => (
              <label key={r.key} className={'ck-row' + (r.locked ? ' is-locked' : '')}>
                <input type="checkbox" checked={r.locked ? true : analytics} disabled={!!r.locked}
                  onChange={e => setAnalytics(e.target.checked)} />
                <span>
                  <span className="ck-row-name">{r.name}</span>
                  <span className="ck-row-text">{r.text}</span>
                </span>
              </label>
            ))}
          </div>
          <div className="ck-actions">
            <button type="button" className="ck-btn" onClick={() => save(analytics)}>{words.save}</button>
          </div>
        </>
      ) : (
        <>
          <div className="ck-actions">
            <button type="button" className="ck-btn" onClick={() => save(true)}>{words.accept}</button>
            <button type="button" className="ck-btn" onClick={() => save(false)}>{words.reject}</button>
          </div>
          <button type="button" className="ck-text" onClick={() => setChoosing(true)}>{words.choose}</button>
        </>
      )}
    </section>
  );
}

Object.assign(window, { CookieBanner });

/* Its own root, beside #root: snapshot.sh copies what is inside #root into each index.html, and the
   banner is not page content. One script tag per route shell is the whole mount. */
(() => {
  const host = document.createElement('div');
  host.id = 'cookie-banner';
  document.body.appendChild(host);
  ReactDOM.createRoot(host).render(<CookieBanner />);
})();
