/* global React, ReactDOM, Swiper, supabase, confetti */
const { useState, useEffect, useMemo, useRef } = React;

const T = window.TRANSLATIONS;
const WEDDING_DATE = new Date("2026-12-26T19:00:00+05:30");
const VENUE_NAME = "Bel-la Mondè Hotel";
const VENUE_ADDRESS = "Chhattarpur, New Delhi";
const VENUE_MAPS_URL = "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent("Bel-la Mondè Hotel Chhattarpur New Delhi");
const VENUE_INSTAGRAM = "https://www.instagram.com/bellamondeblu/";
const STORAGE_KEY = "wedding_rsvps_v1";
const SHARE_URL = typeof window !== "undefined" ? window.location.origin + window.location.pathname : "";

/* Supabase client — null until config.js is filled in with a real project,
   in which case the RSVP form falls back to localStorage. */
const SUPABASE_READY =
  typeof window !== "undefined" &&
  typeof supabase !== "undefined" &&
  window.SUPABASE_URL &&
  window.SUPABASE_ANON_KEY &&
  !/YOUR-PROJECT-REF/.test(window.SUPABASE_URL);
const sb = SUPABASE_READY ? supabase.createClient(window.SUPABASE_URL, window.SUPABASE_ANON_KEY) : null;

/* ============ Hooks ============ */
function useLang() {
  const [lang, setLang] = useState(() => {
    try { return localStorage.getItem("wedding_lang") || "en"; } catch { return "en"; }
  });
  useEffect(() => {
    document.body.dataset.lang = lang;
    document.documentElement.lang = lang;
    try { localStorage.setItem("wedding_lang", lang); } catch {}
  }, [lang]);
  const t = (key) => {
    const v = T[lang] && T[lang][key];
    if (v !== undefined && v !== null) return v;
    const e = T.en[key];
    return e !== undefined && e !== null ? e : key;
  };
  return [lang, setLang, t];
}

function useCountdown(target) {
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, target.getTime() - now);
  return {
    days: Math.floor(diff / 86400000),
    hours: Math.floor((diff % 86400000) / 3600000),
    minutes: Math.floor((diff % 3600000) / 60000),
    seconds: Math.floor((diff % 60000) / 1000),
  };
}

function useRsvps() {
  const [rsvps, setRsvps] = useState(() => {
    try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]"); } catch { return []; }
  });
  const persist = (next) => {
    setRsvps(next);
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } catch {}
  };
  return {
    rsvps,
    addRsvp: (r) => persist([...rsvps, { ...r, ts: Date.now() }]),
    clearAll: () => persist([]),
  };
}

/* ============ Twinkling stars + shooting stars ============ */
function Stars({ count = 40 }) {
  const stars = useMemo(() => {
    const colors = ["#ffffff", "#fff6da", "#fbe9b0", "#e8c97a"];
    return Array.from({ length: count }, () => ({
      left: Math.random() * 100,
      top: Math.random() * 100,
      delay: Math.random() * 6,
      dur: 2.2 + Math.random() * 3.4,
      size: 8 + Math.random() * 16,
      color: colors[Math.floor(Math.random() * colors.length)],
    }));
  }, [count]);
  // a few occasional shooting stars sweeping across the hero
  const shots = useMemo(() => ([
    { top: 14, dur: 7.5, delay: 1.5, angle: 16, len: 180 },
    { top: 33, dur: 9.5, delay: 5.5, angle: 24, len: 220 },
    { top: 7,  dur: 8.5, delay: 10,  angle: 12, len: 150 },
  ]), []);
  return (
    <div className="petals" aria-hidden="true">
      {stars.map((s, i) => (
        <svg
          key={i}
          className="star"
          style={{
            left: s.left + "%",
            top: s.top + "%",
            width: s.size + "px",
            height: s.size + "px",
            animationDuration: s.dur + "s",
            animationDelay: -s.delay + "s",
            color: s.color,
          }}
          viewBox="0 0 48 48"
          fill="currentColor"
        >
          {/* long thin 4-point spikes */}
          <path d="M24 0 C24.4 18.5 29.5 23.6 48 24 C29.5 24.4 24.4 29.5 24 48 C23.6 29.5 18.5 24.4 0 24 C18.5 23.6 23.6 18.5 24 0 Z" />
          {/* shorter diagonal spikes */}
          <path d="M24 9 C24.2 21 27 23.8 39 24 C27 24.2 24.2 27 24 39 C23.8 27 21 24.2 9 24 C21 23.8 23.8 21 24 9 Z" transform="rotate(45 24 24)" opacity="0.6" />
          {/* bright core */}
          <circle cx="24" cy="24" r="2.1" fill="#ffffff" />
        </svg>
      ))}
      {shots.map((s, i) => (
        <span
          key={"sh" + i}
          className="shooting-star"
          style={{
            top: s.top + "%",
            width: s.len + "px",
            animationDuration: s.dur + "s",
            animationDelay: s.delay + "s",
            "--angle": s.angle + "deg",
          }}
        >
          <i className="tail" />
          <i className="head" />
        </span>
      ))}
    </div>
  );
}

/* ============ Couple photo carousel (Swiper) ============ */
function CoupleCarousel() {
  // Explicit list of the photos that exist on disk (update if you add/remove files).
  const slides = [
    { src: "couple.jpg", alt: "Ashutosh and Mariko" },
    { src: "couple-3.jpg", alt: "Ashutosh and Mariko with their dog" },
    ...[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 16, 17].map((n) => ({
      src: "gallery-" + String(n).padStart(2, "0") + ".jpg",
      alt: "Ashutosh and Mariko",
    })),
  ];
  const el = useRef(null);
  const sw = useRef(null);
  const [hint, setHint] = useState(true);

  useEffect(() => {
    if (!el.current || typeof Swiper === "undefined") return;
    const hide = () => setHint(false);
    sw.current = new Swiper(el.current, {
      loop: true,
      speed: 2500,
      grabCursor: true,
      keyboard: { enabled: true },
      autoplay: { delay: 500, disableOnInteraction: false },
      pagination: { el: el.current.querySelector(".swiper-pagination"), clickable: true, dynamicBullets: true },
    });
    sw.current.on("slideChange", hide);
    const id = setTimeout(hide, 4500);
    return () => { clearTimeout(id); if (sw.current) sw.current.destroy(true, true); };
  }, []);

  return (
    <div className="couple-photo has-image" aria-label="Ashutosh and Mariko photos">
      <span className="ph-corner c1" />
      <span className="ph-corner c2" />
      <span className="ph-corner c3" />
      <span className="ph-corner c4" />
      <div className="swiper couple-swiper" ref={el}>
        <div className="swiper-wrapper">
          {slides.map((s, k) => (
            <div className="swiper-slide" key={k}>
              <img src={s.src} alt={s.alt} draggable="false" loading={k === 0 ? "eager" : "lazy"} />
            </div>
          ))}
        </div>
        <div className="swiper-pagination" />
      </div>
      {hint && (
        <div className="swipe-hint" aria-hidden="true">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l-6 6 6 6M15 6l6 6-6 6" /></svg>
          swipe
        </div>
      )}
    </div>
  );
}

/* ============ Background music toggle ============ */
function MusicToggle({ t }) {
  const audioRef = useRef(null);
  const [on, setOn] = useState(false);

  useEffect(() => {
    const a = audioRef.current;
    if (!a) return;
    a.volume = 0.45;
    let done = false;
    const remove = () => {
      if (done) return;
      done = true;
      window.removeEventListener("pointerdown", onFirst);
      window.removeEventListener("keydown", onFirst);
    };
    // Start on the first interaction anywhere — unless it's the toggle itself
    // (the button's own onClick handles that, so we don't fight it).
    const onFirst = (e) => {
      if (e && e.target && e.target.closest && e.target.closest(".music-toggle")) { remove(); return; }
      a.play().then(() => setOn(true)).catch(() => {});
      remove();
    };
    window.addEventListener("pointerdown", onFirst);
    window.addEventListener("keydown", onFirst);
    return remove;
  }, []);

  const toggle = () => {
    const a = audioRef.current;
    if (!a) return;
    if (on) { a.pause(); setOn(false); }
    else { a.play().then(() => setOn(true)).catch(() => {}); }
  };

  return (
    <button
      type="button"
      className={"music-toggle" + (on ? " on" : "")}
      onClick={toggle}
      aria-pressed={on}
      aria-label={on ? t("music_mute") : t("music_play")}
      title={on ? t("music_mute") : t("music_play")}
    >
      {on ? (
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M11 5 6 9H2v6h4l5 4z" />
          <path d="M15.5 8.5a5 5 0 0 1 0 7" />
          <path d="M19 4.5a9 9 0 0 1 0 15" />
        </svg>
      ) : (
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M11 5 6 9H2v6h4l5 4z" />
          <line x1="22" y1="9" x2="16" y2="15" />
          <line x1="16" y1="9" x2="22" y2="15" />
        </svg>
      )}
      <audio ref={audioRef} src="music.mp3" loop preload="none" />
    </button>
  );
}

/* ============ Top bar ============ */
function TopBar({ lang, setLang, t }) {
  return (
    <div className="topbar">
      <MusicToggle t={t} />
      <div className="controls">
        <div className="lang-toggle">
          <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>{t("nav_en")}</button>
          <button className={lang === "ja" ? "active" : ""} onClick={() => setLang("ja")}>{t("nav_ja")}</button>
        </div>
      </div>
    </div>
  );
}

/* ============ Hero ============ */
function Hero({ t }) {
  const cd = useCountdown(WEDDING_DATE);
  return (
    <header className="hero" data-screen-label="01 Hero">
      <div className="hero-bg" aria-hidden="true" />
      <Stars count={40} />
      <div className="eyebrow">{t("hero_eyebrow")}</div>
      <h1>
        Ashutosh <span className="amp">&amp;</span> Mariko
      </h1>
      <div className="invite-line">{t("hero_invite")}</div>
      <div className="meta">
        <span>{t("hero_date")}</span>
        <span className="dot" />
        <span>{t("hero_place")}</span>
      </div>
      <div className="hero-cta">
        <a href="#rsvp">
          {t("hero_cta")}
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 5v14M5 12l7 7 7-7" />
          </svg>
        </a>
      </div>
      <div className="countdown" aria-label="Countdown">
        <div className="cd-cell"><div className="cd-num">{String(cd.days).padStart(2, "0")}</div><div className="cd-lab">{t("cd_days")}</div></div>
        <div className="cd-cell"><div className="cd-num">{String(cd.hours).padStart(2, "0")}</div><div className="cd-lab">{t("cd_hours")}</div></div>
        <div className="cd-cell"><div className="cd-num">{String(cd.minutes).padStart(2, "0")}</div><div className="cd-lab">{t("cd_minutes")}</div></div>
        <div className="cd-cell"><div className="cd-num">{String(cd.seconds).padStart(2, "0")}</div><div className="cd-lab">{t("cd_seconds")}</div></div>
      </div>
      <CoupleCarousel />
    </header>
  );
}

/* ============ Welcome ============ */
function Welcome({ t }) {
  return (
    <section id="welcome" className="welcome" data-screen-label="02 Welcome">
      <div className="container center">
        <div className="eyebrow">{t("welcome_eyebrow")}</div>
        <h2 className="section-title"><em>{t("welcome_title")}</em></h2>
        <div className="welcome-divider" />
        <p>{t("welcome_body_1")}</p>
        <p>{t("welcome_body_2")}</p>
        <div className="signature">— {t("welcome_signature")}</div>
      </div>
    </section>
  );
}

/* ============ Introductions (the couple) ============ */
function Introductions({ t }) {
  return (
    <section id="couple" className="couple-intro" data-screen-label="03 The Couple">
      <div className="container">
        <div className="center">
          <div className="eyebrow">{t("intro_eyebrow")}</div>
          <h2 className="section-title"><em>{t("intro_title")}</em></h2>
          <p className="section-sub">{t("intro_sub")}</p>
        </div>
        <div className="couple-cards">
          <div className="person-card">
            <div className="person-kicker">{t("intro_groom_kicker")}</div>
            <div className="person-name">{t("intro_groom_name")}</div>
            <div className="person-lineage">
              <div className="line">{t("intro_groom_l1_pre")}<span className="who">{t("intro_groom_l1_name")}</span>{t("intro_groom_l1_suf")}</div>
              <div className="line">{t("intro_groom_l2_pre")}<span className="who">{t("intro_groom_l2_name")}</span>{t("intro_groom_l2_suf")}</div>
            </div>
            <p className="person-bio">{t("intro_groom_bio")}</p>
          </div>
          <div className="union-motif" aria-hidden="true">
            <span className="u-line top" />
            <div className="u-core">
              <span className="u-diamond" />
              <span className="u-date">26 · 12 · 2026</span>
            </div>
            <span className="u-line bottom" />
          </div>
          <div className="person-card">
            <div className="person-kicker">{t("intro_bride_kicker")}</div>
            <div className="person-name">{t("intro_bride_name")}</div>
            <div className="person-lineage">
              <div className="line">{t("intro_bride_l1_pre")}<span className="who">{t("intro_bride_l1_name")}</span>{t("intro_bride_l1_suf")}</div>
            </div>
            <p className="person-bio">{t("intro_bride_bio")}</p>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ Details ============ */
function Details({ t }) {
  const handleAddCalendar = () => {
    const start = "20261226T133000Z"; // 7:00 PM IST = 13:30 UTC
    const end = "20261226T233000Z";   // 5:00 AM IST next day (27 Dec) = 23:30 UTC
    const url = "https://www.google.com/calendar/render?action=TEMPLATE"
      + "&text=" + encodeURIComponent("Ashutosh & Mariko's Wedding Reception")
      + "&dates=" + start + "/" + end
      + "&details=" + encodeURIComponent("We can't wait to celebrate with you!")
      + "&location=" + encodeURIComponent(VENUE_NAME + ", " + VENUE_ADDRESS);
    window.open(url, "_blank");
  };
  return (
    <section id="details" className="details" data-screen-label="04 Details">
      <div className="container">
        <div className="center">
          <div className="eyebrow">{t("details_eyebrow")}</div>
          <h2 className="section-title">Where <span className="amp">&amp;</span> when</h2>
          <p className="section-sub">{t("details_sub")}</p>
        </div>
        <div className="details-grid">
          <div className="detail-cell">
            <div className="lab">{t("detail_when_lab")}</div>
            <div className="val">{t("detail_when_val")}</div>
            <div className="sub">{t("detail_when_sub")}</div>
          </div>
          <div className="detail-cell">
            <div className="lab">{t("detail_where_lab")}</div>
            <div className="val">{t("detail_where_val")}</div>
            <div className="sub">{t("detail_where_sub")}</div>
          </div>
          <div className="detail-cell">
            <div className="lab">{t("detail_dress_lab")}</div>
            <div className="val">{t("detail_dress_val")}</div>
            <div className="sub">{t("detail_dress_sub")}</div>
          </div>
          <div className="detail-cell">
            <div className="lab">{t("detail_lang_lab")}</div>
            <div className="val">{t("detail_lang_val")}</div>
            <div className="sub">{t("detail_lang_sub")}</div>
          </div>
        </div>
        <div className="map-frame">
          <iframe
            title="Venue map"
            src={"https://www.google.com/maps?q=" + encodeURIComponent("Bel-la Mondè Hotel Chhattarpur New Delhi") + "&output=embed"}
            loading="lazy"
            referrerPolicy="no-referrer-when-downgrade"
          />
        </div>
        <div className="actions-row">
          <button className="btn primary" onClick={handleAddCalendar}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2" /><line x1="3" y1="10" x2="21" y2="10" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="16" y1="2" x2="16" y2="6" /></svg>
            {t("add_calendar")}
          </button>
          <a className="btn" href={VENUE_MAPS_URL} target="_blank" rel="noreferrer">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 1118 0z" /><circle cx="12" cy="10" r="3" /></svg>
            {t("open_maps")}
          </a>
          <a className="btn ghost" href={VENUE_INSTAGRAM} target="_blank" rel="noreferrer">
            {t("view_venue")}
          </a>
        </div>
      </div>
    </section>
  );
}

/* ============ Confetti (via @hiseb/confetti — confettijs.org) ============ */
function fireConfetti() {
  if (typeof confetti !== "function") return;
  confetti({ count: 150, velocity: 280, size: 1.1, fade: true });
}

/* ============ Share buttons ============ */
function ShareButtons({ t }) {
  const [copied, setCopied] = useState(false);
  const onCopy = async () => {
    try {
      await navigator.clipboard.writeText(SHARE_URL);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {}
  };
  return (
    <div className="share-row">
      <button className="share-btn" onClick={onCopy}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="9" y="9" width="13" height="13" rx="2" /><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" /></svg>
        {copied ? t("share_copied") : t("share_copy")}
      </button>
    </div>
  );
}

/* ============ RSVP ============ */
function RsvpForm({ t, onSubmitted }) {
  const [name, setName] = useState("");
  const [attending, setAttending] = useState("");
  const [hasPlus, setHasPlus] = useState(false);
  const [plusName, setPlusName] = useState("");
  const [song, setSong] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const { addRsvp } = useRsvps();

  const canSubmit = name.trim() && attending && !submitting;

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!canSubmit) return;
    setSubmitting(true);
    const entry = {
      name: name.trim(),
      attending,
      plus_one: hasPlus && plusName.trim() ? plusName.trim() : null,
      song: song.trim() || null,
    };
    let saved = false;
    if (sb) {
      const { error } = await sb.from("rsvps").insert(entry);
      if (error) console.error("Supabase RSVP insert failed:", error.message);
      else saved = true;
    }
    if (!saved) {
      // No Supabase configured yet (or a network error) — keep the reply locally so it's not lost.
      addRsvp({ name: entry.name, attending: entry.attending, plusOne: entry.plus_one || "", song: entry.song || "" });
    }
    if (entry.attending === "yes") fireConfetti();
    onSubmitted({ name: entry.name, attending: entry.attending });
    setSubmitting(false);
  };

  return (
    <form className="rsvp-card" onSubmit={onSubmit}>
      <div className="field">
        <label>{t("f_name")}</label>
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} required />
      </div>
      <div className="field">
        <label>{t("f_attend")}</label>
        <div className="attend-options">
          <label data-val="yes" className={attending === "yes" ? "selected" : ""}>
            <input type="radio" name="attending" value="yes" checked={attending === "yes"} onChange={() => setAttending("yes")} />
            <span className="icon-wrap">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
            </span>
            <span className="lbl">{t("f_yes")}</span>
            <span className="sub">{t("f_yes_sub")}</span>
          </label>
          <label data-val="no" className={attending === "no" ? "selected" : ""}>
            <input type="radio" name="attending" value="no" checked={attending === "no"} onChange={() => setAttending("no")} />
            <span className="icon-wrap">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 12h8"/></svg>
            </span>
            <span className="lbl">{t("f_no")}</span>
            <span className="sub">{t("f_no_sub")}</span>
          </label>
        </div>
      </div>
      {attending === "yes" && (
        <div className="field">
          <label className="plus-one-toggle">
            <input type="checkbox" checked={hasPlus} onChange={(e) => setHasPlus(e.target.checked)} />
            <span>{t("f_plus_one_toggle")}</span>
          </label>
          <div className={"plus-one-wrap" + (hasPlus ? " open" : "")}>
            <input
              type="text"
              value={plusName}
              onChange={(e) => setPlusName(e.target.value)}
              placeholder={t("f_plus_one_name")}
              style={{ width: "100%", padding: "12px 0", border: 0, borderBottom: "1px solid var(--line)", background: "transparent", fontFamily: "var(--serif)", fontSize: "20px", outline: "none" }}
            />
          </div>
        </div>
      )}
      {attending === "yes" && (
        <div className="field">
          <label>{t("f_song")}</label>
          <input type="text" value={song} onChange={(e) => setSong(e.target.value)} placeholder={t("f_song_ph")} />
        </div>
      )}
      <div className="submit-row">
        <button type="submit" className="btn-submit" disabled={!canSubmit}>
          {submitting ? t("rsvp_sending") : t("rsvp_submit")}
        </button>
      </div>
    </form>
  );
}

function Rsvp({ t }) {
  const [done, setDone] = useState(null);
  return (
    <section id="rsvp" className="rsvp" data-screen-label="05 RSVP">
      <div className="container center">
        <div className="eyebrow">{t("rsvp_eyebrow")}</div>
        <h2 className="section-title">{t("rsvp_title")}</h2>
        {done ? (
          <div className="rsvp-card">
            <div className="rsvp-success">
              <div className="seal">{done.attending === "no" ? "🥺" : "🥰"}</div>
              <h3>{t("rsvp_success_title")}</h3>
              <p>{t(done.attending === "no" ? "rsvp_success_body_no" : "rsvp_success_body")}</p>
              <ShareButtons t={t} />
            </div>
          </div>
        ) : (
          <RsvpForm t={t} onSubmitted={setDone} />
        )}
      </div>
    </section>
  );
}

/* ============ Footer ============ */
function Footer({ t }) {
  return (
    <footer data-screen-label="06 Footer">
      <div className="tag">{t("footer_tag")}</div>
      <ShareButtons t={t} />
      <div className="fineprint">{t("fineprint")}</div>
    </footer>
  );
}

/* ============ App ============ */
function App() {
  const [lang, setLang, t] = useLang();
  return (
    <>
      <TopBar lang={lang} setLang={setLang} t={t} />
      <Hero t={t} />
      <Welcome t={t} />
      <Introductions t={t} />
      <Details t={t} />
      <Rsvp t={t} />
      <Footer t={t} />
    </>
  );
}

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