/* global React, ReactDOM, window */
/* CartoonforChrist v2 — shared shell.
 * TopStrip, CascadeMenu, Footer (newsletter + contact + colophon),
 * useContestCountdown hook, and renderV2Page() wrapper that wires
 * FxLayer + TweaksPanel.
 *
 * Each page calls renderV2Page({ active: "watch"|"draw"|..., body: ({lang, motion}) => <>... </> })
 */

const { useState: useStateV2, useEffect: useEffectV2 } = React;
const { SECTIONS: V2_SECTIONS, LINKS: V2_LINKS } = window.CFC;

/* ---------- Animated cascade menu ---------- */
function CascadeMenu({ open, onClose, current }) {
  useEffectV2(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  return (
    <div className={`menu-overlay ${open ? "is-open" : ""}`} aria-hidden={!open}>
      <div className="menu-overlay__scrim" onClick={onClose} />
      <div className="menu-overlay__bars" style={{ "--menu-n": V2_SECTIONS.length + 1 }}>
        <a href="index.html"
           className={`menu-bar menu-bar--home ${current === "home" ? "is-current" : ""}`}
           style={{ "--menu-i": 0 }}
           aria-label="Home">
          <div className="menu-bar__inner">
            <div className="menu-bar__num">00</div>
            <div>
              <h2 className="menu-bar__title">Home</h2>
              <span className="menu-bar__sub">Back to the CartoonforChrist homepage</span>
            </div>
            <div className="menu-bar__arrow">{current === "home" ? "•" : "→"}</div>
            <div className="menu-bar__stamp">🏠</div>
          </div>
        </a>
        {V2_SECTIONS.map((s, i) => (
          <a key={s.id} href={s.href}
             className={`menu-bar menu-bar--${s.id} ${current === s.id ? "is-current" : ""}`}
             style={{ "--menu-i": i + 1 }}
             aria-label={s.title}>
            <div className="menu-bar__inner">
              <div className="menu-bar__num">{s.num}</div>
              <div>
                <h2 className="menu-bar__title">{s.title}</h2>
                <span className="menu-bar__sub">{s.sub}</span>
              </div>
              <div className="menu-bar__arrow">{current === s.id ? "•" : "→"}</div>
              <div className="menu-bar__stamp">{s.glyph}</div>
            </div>
          </a>
        ))}
      </div>
      <button className="menu-close" onClick={onClose} aria-label="Close menu">✕</button>
      <div className="menu-hint">press <b>esc</b> or click anywhere to close</div>
    </div>
  );
}

/* ---------- TopStrip (sticky brand bar + MENU button) ---------- */
function TopStrip({ menuOpen, onOpen, tickerCopy }) {
  const ticker = tickerCopy || (
    <>
      <b>✦</b>&nbsp;CARTOONFORCHRIST &nbsp;<b className="ticker__dot">●</b>&nbsp;
      KIDS SINGING CONTEST 2026 · ENTRIES OPEN &nbsp;<b className="ticker__dot">●</b>&nbsp;
      LAST DATE 31 JULY 2026 &nbsp;<b className="ticker__dot">●</b>&nbsp;
      ORIGINAL SONGS · HINDI + ENGLISH &nbsp;<b className="ticker__dot">●</b>&nbsp;
      5 YEARS OF CDBS ARCHIVED &nbsp;<b className="ticker__dot">●</b>&nbsp;
      FAMILY-BUILT WITH LOVE &nbsp;<b className="ticker__dot">●</b>&nbsp;
    </>
  );
  return (
    <header className="strip">
      <a href="index.html" className="strip__logo">
        <img src={(window.__resources && window.__resources.cfcLogo) || "assets/CFC_Logo.png"} alt="" />
        <div>
          <div>CartoonforChrist</div>
          <small>Helping children connect with God</small>
        </div>
      </a>
      <div className="ticker" aria-hidden="true">
        <div className="ticker__track">
          <span>{ticker}</span>
          <span>{ticker}</span>
        </div>
      </div>
      <button
        className={`menu-btn ${menuOpen ? "is-open" : ""}`}
        onClick={onOpen}
        aria-expanded={menuOpen}
        aria-controls="menu-overlay">
        <span>MENU</span>
        <span className="menu-btn__bars" aria-hidden="true">
          <i/><i/><i/><i/><i/>
        </span>
      </button>
    </header>
  );
}

/* ---------- Spotify logo glyph ---------- */
function SpotifyGlyph() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
      <path d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0m5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.84-.179-.96-.601-.122-.42.18-.84.6-.96 4.561-1.021 8.52-.6 11.64 1.32.361.181.481.66.241 1.02m1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6s.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2m.12-3.36C15.24 8.4 8.819 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.42 1.56-.299.421-1.02.599-1.561.3"/>
    </svg>
  );
}

/* ---------- Floating social rail (left edge of every page) ---------- */
function SideRail({ motion = true }) {
  return (
    <nav className={`side-rail ${motion ? "" : "is-still"}`} aria-label="CartoonforChrist elsewhere">
      <a href={V2_LINKS.youtube} target="_blank" rel="noreferrer" title="YouTube"
         style={{ "--bg": "#FF0000", "--fg": "#fff", "--i": 0 }}>▶</a>
      <a href={V2_LINKS.bibleBuddies} target="_blank" rel="noreferrer" title="biblebuddies.space"
         style={{ "--bg": "var(--cfc-yellow)", "--i": 1 }}>🐝</a>
      <a href={V2_LINKS.playStore} target="_blank" rel="noreferrer" title="Bible Buddies on Play Store"
         style={{ "--bg": "var(--cfc-green)", "--i": 2 }}>📱</a>
      <a href={V2_LINKS.contestForm} title="Contest 2026"
         style={{ "--bg": "var(--cfc-pink)", "--fg": "#fff", "--i": 3 }}>🎤</a>
      <a href={V2_LINKS.spotify} target="_blank" rel="noreferrer" title="Listen on Spotify"
         style={{ "--bg": "#1DB954", "--fg": "#fff", "--i": 4 }}><SpotifyGlyph /></a>
    </nav>
  );
}

/* ---------- Countdown to Contest 2026 deadline ---------- */
function useContestCountdown() {
  const [t, setT] = useStateV2({ d: 0, h: 0, m: 0, s: 0, expired: false });
  useEffectV2(() => {
    const tick = () => {
      const now = new Date();
      // 31 July 2026, 23:59 IST = 18:29 UTC
      const target = new Date(Date.UTC(2026, 6, 31, 18, 29, 0));
      let ms = target - now;
      const expired = ms <= 0;
      if (ms < 0) ms = 0;
      const d = Math.floor(ms / 86400000);
      const h = Math.floor((ms / 3600000) % 24);
      const m = Math.floor((ms / 60000) % 60);
      const s = Math.floor((ms / 1000) % 60);
      setT({ d, h, m, s, expired });
    };
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, []);
  return t;
}

/* ---------- Form submission → Google Apps Script (Sheet + Gmail) ---------- */
// Posts as text/plain so the browser sends a "simple" request (no CORS
// preflight); the Apps Script reads e.postData.contents. We use no-cors mode
// because Apps Script web apps don't return CORS headers — the request still
// reaches the server; we just can't read the opaque response, so a resolved
// fetch is treated as success. A rejected fetch (network down) shows the error.
async function submitToForms(payload) {
  const url = V2_LINKS.formsEndpoint;
  if (!url) {
    console.warn("[forms] LINKS.formsEndpoint is not set in shared/v2-data.jsx — submission NOT saved:", payload);
    return; // resolve so the visitor still sees the thank-you
  }
  await fetch(url, {
    method: "POST",
    mode: "no-cors",
    headers: { "Content-Type": "text/plain;charset=utf-8" },
    body: JSON.stringify(payload),
  });
}

function NewsletterForm() {
  const [state, setState] = useStateV2("idle"); // idle | sending | done | error
  const onSubmit = async (e) => {
    e.preventDefault();
    const email = (e.target.elements.email.value || "").trim();
    if (!email) return;
    setState("sending");
    try {
      await submitToForms({ type: "newsletter", email, page: location.pathname, ts: new Date().toISOString() });
      setState("done");
    } catch (err) {
      console.error("[forms] newsletter submit failed:", err);
      setState("error");
    }
  };

  if (state === "done") {
    return (
      <div className="form-thanks">
        Welcome to the family ✨
        <span>Your first letter arrives the first week of next month.</span>
      </div>
    );
  }
  return (
    <>
      <form onSubmit={onSubmit}>
        <input type="email" name="email" placeholder="your@email.com" required disabled={state === "sending"} />
        <button type="submit" disabled={state === "sending"}>{state === "sending" ? "Sending…" : "Subscribe →"}</button>
      </form>
      <div className="small">
        {state === "error"
          ? <span style={{ color: "var(--cfc-pink)" }}>Hmm, that didn't go through — please try again, or email us directly.</span>
          : <span style={{ color: "rgb(110, 255, 0)" }}>Reaches you first week of every month</span>}
      </div>
    </>
  );
}

function MessageForm() {
  const [state, setState] = useStateV2("idle");
  const onSubmit = async (e) => {
    e.preventDefault();
    const message = (e.target.elements.message.value || "").trim();
    const email = (e.target.elements.email.value || "").trim();
    if (!message) return;
    setState("sending");
    try {
      await submitToForms({ type: "message", message, email, page: location.pathname, ts: new Date().toISOString() });
      setState("done");
    } catch (err) {
      console.error("[forms] message submit failed:", err);
      setState("error");
    }
  };

  if (state === "done") {
    return (
      <div className="form-thanks">
        Thank you — we'll write back soon ✨
        <span>We read every message personally.</span>
      </div>
    );
  }
  return (
    <>
      <form className="is-message" onSubmit={onSubmit}>
        <textarea name="message" placeholder="Write us a quick note — a song that helped, a prayer request, an idea…" rows={3} required disabled={state === "sending"} />
        <input type="email" name="email" placeholder="your email (optional — so we can write back)" disabled={state === "sending"} />
        <button type="submit" disabled={state === "sending"}>{state === "sending" ? "Sending…" : "Send →"}</button>
      </form>
      <div className="small">
        {state === "error"
          ? <span style={{ color: "var(--cfc-pink)" }}>That didn't send — please try again, or WhatsApp us.</span>
          : <>Or WhatsApp <b>{V2_LINKS.whatsapp}</b> · {V2_LINKS.email}</>}
      </div>
    </>
  );
}

/* ---------- Shared footer: newsletter + contact + colophon ---------- */
function FooterColophon() {
  return (
    <section className="colophon">
      <div className="letter-card letter-card--news">
        <div>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 12, letterSpacing: "0.16em", textTransform: "uppercase" }}>The monthly newsletter</span>
          <h2>One short letter — the new song, the next study, the question for your table.</h2>
          <p style={{ margin: 0, maxWidth: 480 }}>No tracking, no spam. Unsubscribe in one click whenever it stops serving your family.</p>
        </div>
        <div>
          <NewsletterForm />
        </div>
      </div>

      <div className="letter-card">
        <div className="stamp">WRITE<br/>TO US<br/>···</div>
        <div>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 12, letterSpacing: "0.16em", textTransform: "uppercase" }}>We'd love to hear from you</span>
          <h2>Tell us how a song or study has met your family.</h2>
          <p style={{ margin: 0, maxWidth: 480 }}>We're a family too — we read every message personally. If you share a prayer request, we'll pray for you by name.</p>
        </div>
        <div>
          <MessageForm />
        </div>
      </div>

      <div className="footrow">
        <div>
          <h4>About us</h4>
          <div className="imp">
            An ordinary family with one extraordinary conviction — that God's Word is for every child, and creativity is a gift meant to be given away. Since the Covid summer of 2020. Hindi and English.
          </div>
        </div>
        <div>
          <h4>Rooms</h4>
          {V2_SECTIONS.map(s => (
            <a key={s.id} href={s.href}>{s.title}</a>
          ))}
        </div>
        <div>
          <h4>Family projects</h4>
          <a href={V2_LINKS.playStore} target="_blank" rel="noreferrer">Bible Buddies Chat (app)</a>
          <a href={V2_LINKS.bibleBuddies} target="_blank" rel="noreferrer">biblebuddies.space</a>
          <a href="projects.html">Berean Play · coming soon</a>
          <a href="projects.html">Family community · coming soon</a>
        </div>
        <div>
          <h4>Reach us</h4>
          <a href={`mailto:${V2_LINKS.email}`}>{V2_LINKS.email}</a>
          <a href={V2_LINKS.whatsappUrl} target="_blank" rel="noreferrer">WhatsApp · {V2_LINKS.whatsapp}</a>
          <a href={V2_LINKS.youtube} target="_blank" rel="noreferrer">@cartoonforchrist on YouTube</a>
        </div>
      </div>
      <div className="signoff">© CartoonforChrist · Since 2020 · "Whatever you do, work at it with all your heart" — Col 3:23</div>
    </section>
  );
}

/* ---------- Shareable contest poster (home + contest pages) ---------- */
const CONTEST_POSTER = "assets/Contest2026_Poster.png";
const CONTEST_POSTER_FILE = "CartoonforChrist-Singing-Contest-2026.png";

function ContestPoster() {
  const sharePoster = async () => {
    const url = new URL(CONTEST_POSTER, location.href).href;
    const title = "CartoonforChrist Kids Singing Contest 2026";
    const text = "Join the CartoonforChrist Kids Singing Contest 2026! 🎤 Sing in English or Hindi.";
    try {
      if (navigator.canShare) {
        const blob = await (await fetch(CONTEST_POSTER)).blob();
        const file = new File([blob], CONTEST_POSTER_FILE, { type: blob.type || "image/png" });
        if (navigator.canShare({ files: [file] })) {
          await navigator.share({ files: [file], title, text });
          return;
        }
      }
      if (navigator.share) { await navigator.share({ title, text, url }); return; }
      window.open(CONTEST_POSTER, "_blank"); // no share support → just open it
    } catch (e) {
      /* user dismissed the share sheet, or it failed — nothing to do */
    }
  };

  return (
    <section className="poster-card">
      <a className="poster-card__thumb" href={CONTEST_POSTER} target="_blank" rel="noreferrer" title="View full size">
        <img src={CONTEST_POSTER} alt="CartoonforChrist Kids Singing Contest 2026 poster" loading="lazy" />
      </a>
      <div className="poster-card__body">
        <span className="poster-card__kicker">📣 Spread the word</span>
        <h3>Share the contest poster</h3>
        <p>Know a child who'd love to sing? Download the poster and share it on WhatsApp, with your church, or your homeschool group.</p>
        <div className="poster-card__btns">
          <a className="cbtn cbtn--pink" href={CONTEST_POSTER} download={CONTEST_POSTER_FILE}>⬇ Download poster</a>
          <button className="cbtn cbtn--ghost" type="button" onClick={sharePoster}>↗ Share</button>
          <a className="cbtn cbtn--ghost" href={CONTEST_POSTER} target="_blank" rel="noreferrer">🔍 View full size</a>
        </div>
      </div>
    </section>
  );
}

/* ---------- Page wrapper ---------- */
function renderV2Page({ active, body, tickerCopy, hideFooter = false }) {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "motion": true,
    "fx": true,
    "fxIntensity": 1
  }/*EDITMODE-END*/;

  function App() {
    const [menuOpen, setMenuOpen] = useStateV2(false);
    const [t, setT] = window.useTweaks(TWEAK_DEFAULTS);

    // keyboard shortcut M opens menu
    useEffectV2(() => {
      const onKey = (e) => {
        if ((e.key === "m" || e.key === "M") && !e.metaKey && !e.ctrlKey && !e.altKey) {
          const tag = document.activeElement && document.activeElement.tagName;
          if (tag === "INPUT" || tag === "TEXTAREA") return;
          setMenuOpen(o => !o);
        }
      };
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, []);

    return (
      <>
        <TopStrip menuOpen={menuOpen} onOpen={() => setMenuOpen(true)} tickerCopy={tickerCopy} />
        <CascadeMenu open={menuOpen} onClose={() => setMenuOpen(false)} current={active} />
        <SideRail motion={t.motion} />

        <main>
          {body({ motion: t.motion })}
          {!hideFooter && <FooterColophon />}
        </main>

        <window.FxLayer enabled={t.motion && t.fx} intensity={t.fxIntensity} />

        <window.TweaksPanel title="Tweaks">
          <window.TweakSection label="Animations" />
          <window.TweakToggle
            label="Page motion (hand, sparkles)"
            value={t.motion}
            onChange={(v) => setT({ motion: v })}
          />
          <window.TweakToggle
            label="Confetti + cursor trail"
            value={t.fx}
            onChange={(v) => setT({ fx: v })}
          />
          <window.TweakSlider
            label="FX intensity"
            value={t.fxIntensity}
            min={0.4} max={2.5} step={0.1}
            onChange={(v) => setT({ fxIntensity: v })}
          />
          <window.TweakSection label="Navigate" />
          <window.TweakButton label="Home"          onClick={() => location.href = "index.html"} />
          {V2_SECTIONS.map(s => (
            <window.TweakButton key={s.id} label={s.title} onClick={() => location.href = s.href} />
          ))}
        </window.TweaksPanel>
      </>
    );
  }

  const root = ReactDOM.createRoot(document.getElementById("root"));
  root.render(<App />);
}

window.V2 = { CascadeMenu, TopStrip, SideRail, ContestPoster, FooterColophon, useContestCountdown, renderV2Page };
window.renderV2Page = renderV2Page;
