/* Sara Akef, THE STANDARD. Themeable Marquee (light/dark) plus interactive layer */
const { useState, useEffect, useRef, useCallback } = React;
const t = window.SA_T, A = window.SA_A, N = window.SA_N, L = window.SA_L, P = window.SA_P;
/* a hero line is either a plain string or [before, accent, after] */
function heroLine(line) {
  if (!Array.isArray(line)) return line;
  return <React.Fragment>{line[0]}<span className="amp">{line[1]}</span>{line[2]}</React.Fragment>;
}

/* isolate a curly apostrophe so display type can kern around its ball terminal */
function apos(str) {
  if (typeof str !== "string" || str.indexOf("’") < 0) return str;
  return str.split("’").reduce((out, part, i) =>
    i === 0 ? [part] : out.concat(<span key={i} className="apos">’</span>, part), []);
}

const LANG = window.SA_LANG, LANGS = window.SA_LANGS;
const langHref = (c) => (window.SA_BASE || "") + (c === "en" ? "index.html" : c + "/index.html");

function SunIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
      <circle cx="12" cy="12" r="4.2" /><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.5 1.5M17.5 17.5L19 19M19 5l-1.5 1.5M6.5 17.5L5 19" />
    </svg>
  );
}
function MoonIcon() {
  return (<svg viewBox="0 0 24 24" fill="currentColor"><path d="M20 14.5A8 8 0 0 1 9.5 4 6.5 6.5 0 1 0 20 14.5z" /></svg>);
}

/* the marquee ticker, duplicated run so the loop is seamless */
function Ticker() {
  const Run = () => (
    <div className="run">
      {t("ticker").map((w, i) => (
        <React.Fragment key={i}><span className={i % 2 ? "o" : ""}>{w}</span><i className="s"></i></React.Fragment>
      ))}
    </div>
  );
  // eight identical runs, shifted by exactly four, so the seam never shows
  return (
    <div className="ticker" aria-hidden="true">
      <div className="track">{[0,1,2,3,4,5,6,7].map((n) => <Run key={n} />)}</div>
    </div>
  );
}

function SaraSite() {
  const getInitial = () => {
    try {
      const saved = localStorage.getItem("sa-theme");
      if (saved === "light" || saved === "dark") return saved;
    } catch (e) {}
    const hr = new Date().getHours();
    const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
    return (prefersDark || hr >= 19 || hr < 7) ? "dark" : "light";
  };

  const [theme, setTheme] = useState(getInitial);
  const [loaded, setLoaded] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [hoverRow, setHoverRow] = useState(null);
  const [openWorkId, setOpenWorkId] = useState(null);
  const [enquiry, setEnquiry] = useState(null);
  const [cvOpen, setCvOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const cvRef = useRef(null);
  const [filter, setFilter] = useState("All");
  const heroRef = useRef(null);
  const HV = window.SARA_HERO.heroVideos[window.SARA_HERO.hero];
  const vidRef = useRef(null);

  const profile = window.SARA_PROFILE || {};
  const disciplines = profile.disciplines || ["All"];
  const allCredits = (profile.credits || []).map(L);
  const discLabel = (d) => (t("disciplines") || {})[d] || d;
  const works = window.SA_WORKS || [];

  useEffect(() => { const t = setTimeout(() => setLoaded(true), 80); return () => clearTimeout(t); }, []);
  useEffect(() => { try { localStorage.setItem("sa-theme", theme); } catch (e) {} }, [theme]);

  useEffect(() => {
    if (!cvOpen) return;
    const onKey = (e) => { if (e.key === "Escape") setCvOpen(false); };
    const onDown = (e) => { if (cvRef.current && !cvRef.current.contains(e.target)) setCvOpen(false); };
    document.addEventListener("keydown", onKey);
    document.addEventListener("pointerdown", onDown);
    return () => { document.removeEventListener("keydown", onKey); document.removeEventListener("pointerdown", onDown); };
  }, [cvOpen]);

  useEffect(() => {
    const openEnq = () => setEnquiry({ type: null });
    window.addEventListener("sa-open-enquiry", openEnq);
    return () => window.removeEventListener("sa-open-enquiry", openEnq);
  }, []);

  // scroll: chrome state only
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > window.innerHeight * 0.7);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const toggle = () => setTheme((t) => (t === "dark" ? "light" : "dark"));

  const onHeroMove = useCallback((e) => {
    const el = heroRef.current; if (!el) return;
    const r = el.getBoundingClientRect();
    el.style.setProperty("--mx", ((e.clientX - r.left) / r.width) * 100 + "%");
    el.style.setProperty("--my", ((e.clientY - r.top) / r.height) * 100 + "%");
  }, []);

  useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === "Escape") setMenuOpen(false); };
    const onResize = () => { if (window.innerWidth > 760) setMenuOpen(false); };
    window.addEventListener("keydown", onKey);
    window.addEventListener("resize", onResize);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("resize", onResize);
      document.body.style.overflow = "";
    };
  }, [menuOpen]);

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    const m = document.querySelector('meta[name="theme-color"]');
    if (m) m.setAttribute("content", theme === "dark" ? "#14100D" : "#FBF6EC");
  }, [theme]);

  useEffect(() => {
    const v = vidRef.current; if (!v) return;
    const silence = () => { v.muted = true; v.defaultMuted = true; v.volume = 0; };
    silence();
    v.addEventListener("play", silence);
    v.addEventListener("volumechange", silence);
    return () => { v.removeEventListener("play", silence); v.removeEventListener("volumechange", silence); };
  }, []);

  const MotionSeq = window.MotionSeq;
  const WorkLightbox = window.WorkLightbox;
  const EnquiryForm = window.EnquiryForm;

  const enquire = (type) => setEnquiry({ type: type || null });

  const openOnKey = (fn) => (e) => {
    if (e.key === "Enter" || e.key === " ") { e.preventDefault(); fn(); }
  };

  const [noticeGone, setNoticeGone] = useState(() => {
    try { return localStorage.getItem("sa-notice-pl") === "1"; } catch (e) { return false; }
  });
  const dismissNotice = () => {
    setNoticeGone(true);
    try { localStorage.setItem("sa-notice-pl", "1"); } catch (e) {}
  };

  const shownWorks = works.filter((w) => filter === "All" || (w.tags || []).includes(filter));
  const restCredits = allCredits.filter((c) => !c.featured && (filter === "All" || (c.tags || []).includes(filter)));

  return (
    <div className={"site" + (loaded ? " loaded" : "") + (scrolled ? " scrolled" : "")} data-theme={theme} data-lang={LANG}>
      {LANG === "pl" && !noticeGone ? (
        <div className="notice">
          <p>{t("notice")}</p>
          <button type="button" aria-label={t("noticeClose")} onClick={dismissNotice}>✕</button>
        </div>
      ) : null}
      {/* HERO */}
      <header className="hero" ref={heroRef} onMouseMove={onHeroMove} style={{
        "--hv-pos": HV.position, "--hv-scale": HV.scale, "--hv-origin": HV.origin, "--hv-filter": HV.filter,
        "--hv-pos-sm": HV.positionSm, "--hv-scale-sm": HV.scaleSm, "--hv-origin-sm": HV.originSm,
      }}>
        <div className="hero-bg">
          <video ref={vidRef} className="hero-vid" src={A(HV.src)} autoPlay muted loop playsInline preload="auto"
                 disablePictureInPicture controls={false} aria-hidden="true"></video>
          <div className="hero-vignette"></div>
        </div>
        <div className="spot"></div>
        <div className="topbar">
          <span className="mark">{t("wordmark")}</span>
          <nav>
            <a href="#work">{t("navWork")}</a>
            <a href="#credits">{t("navCredits")}</a>
            <a href="#teaching">{t("navTeaching")}</a>
            <a href="#contact">{t("navContact")}</a>
          </nav>
          <div className="nav-tools">
            <span className="langpick">
              {LANGS.map((l) => l.code === LANG
                ? <span key={l.code} className="on" aria-current="true">{l.short}</span>
                : l.ready
                  ? <a key={l.code} href={langHref(l.code)} lang={l.code}>{l.short}</a>
                  : <span key={l.code} className="off" title={l.label + ", " + t("langSoon")}>{l.short}</span>)}
            </span>
            <button className="theme-toggle" onClick={toggle} aria-label={t("themeAria")}
                    title={theme === "dark" ? t("themeUp") : t("themeDown")}>
              {theme === "dark" ? <SunIcon /> : <MoonIcon />}
            </button>
            <button className="nav-cta" onClick={() => enquire()}>{t("navEnquire")}</button>
          </div>
          <button className="nav-toggle" aria-label={t("menuOpen")} aria-expanded={menuOpen} onClick={() => setMenuOpen(true)}>
            <span></span><span></span>
          </button>
        </div>
        {menuOpen ? (
          <div className="navsheet" onClick={() => setMenuOpen(false)}>
            <div className="navsheet-in" onClick={(e) => e.stopPropagation()}>
              <button className="navsheet-x" aria-label={t("menuClose")} onClick={() => setMenuOpen(false)}>✕</button>
              <nav>
                <a href="#work" onClick={() => setMenuOpen(false)}>{t("navWork")}</a>
                <a href="#credits" onClick={() => setMenuOpen(false)}>{t("navCredits")}</a>
                <a href="#teaching" onClick={() => setMenuOpen(false)}>{t("navTeaching")}</a>
                <a href="#contact" onClick={() => setMenuOpen(false)}>{t("navContact")}</a>
              </nav>
              <div className="navsheet-act">
                <button className="foot-enq" onClick={() => { setMenuOpen(false); enquire(); }}>{t("footSend")}</button>
                <span className="navsheet-k">{t("footCv")}</span>
                <div className="navsheet-cv">
                  <a href={A("Sara Akef CV.html")} target="_blank" rel="noopener">English</a>
                  <a href={A("Sara Akef CV FA.html")} target="_blank" rel="noopener" className="rtl">فارسی</a>
                  <a href={A("Sara Akef CV PL.html")} target="_blank" rel="noopener">Polski</a>
                </div>
                <span className="navsheet-k">{t("themeLabel")}</span>
                <div className="navsheet-cv">
                  <button className="navsheet-theme" onClick={toggle}>
                    {theme === "dark" ? <SunIcon /> : <MoonIcon />}
                    {theme === "dark" ? t("themeUp") : t("themeDown")}
                  </button>
                </div>
                <span className="navsheet-k">{t("langLabel")}</span>
                <div className="navsheet-cv">
                  {LANGS.map((l) => l.code === LANG
                    ? <span key={l.code} className="on">{l.label}</span>
                    : l.ready
                      ? <a key={l.code} href={langHref(l.code)} lang={l.code}>{l.label}</a>
                      : <span key={l.code} className="off">{l.label}</span>)}
                </div>
              </div>
              <a className="navsheet-em" href={"mailto:" + (profile.email || "")}>{profile.email}</a>
            </div>
          </div>
        ) : null}
        <div className="hero-type">
          <div className="eyebrow">{t("heroEyebrow")}</div>
          <h1 className="disp">
            <span className="clip"><span>{heroLine(t("heroName")[0])}</span></span>
            <span className="l2"><span className="clip"><span>{heroLine(t("heroName")[1])}</span></span></span>
          </h1>
        </div>
      </header>

      <Ticker />

      {/* ABOUT */}
      <section className="about" id="about">
        <h2 className="sec-k">{t("aboutHead")}</h2>
        <p className="big disp">{t("introBig")[0]}<em>{t("introBig")[1]}</em>{t("introBig")[2]}</p>
        <div className="about-in">
          <p className="about-bio">{P("bioShort", profile.bioShort)}</p>
          <dl className="about-facts">
            {(P("aboutFacts", null) || ["Based", "Languages"]
              .map((k) => (profile.vitals || []).find((v) => v.k === k))
              .filter(Boolean)
            ).map((x) => (<div key={x.k}><dt>{x.k}</dt><dd>{x.v}</dd></div>))}
            <div><dt>{t("workRightsK")}</dt><dd>{P("workRights", profile.workRights)}</dd></div>
          </dl>
        </div>
      </section>

      {/* WORK */}
      <section className="work" id="work">
        <div className="work-head">
          <h2 className="disp">{t("workHead")}</h2>
          <div className="filter">
            {disciplines.map((d) => (
              <button key={d} className={filter === d ? "on" : ""} onClick={() => setFilter(d)}>{discLabel(d)}</button>
            ))}
          </div>
        </div>
        {shownWorks.map((w) => (
          <article key={w.id} className={"row" + (w.alt ? " alt" : "")}
                   role="button" tabIndex={0} aria-label={w.title}
                   onMouseEnter={() => setHoverRow(w.id)} onMouseLeave={() => setHoverRow(null)}
                   onFocus={() => setHoverRow(w.id)} onBlur={() => setHoverRow(null)}
                   onKeyDown={openOnKey(() => setOpenWorkId(w.id))}
                   onClick={() => setOpenWorkId(w.id)}>
            <span className="idx disp">{N(String(works.indexOf(w) + 1).padStart(2, "0"))}</span>
            <span className="ttl disp">
              <span className="ttl-en">{w.title}</span>
              {w.fa ? <span className="ttl-fa fa">{w.fa}</span> : null}
            </span>
            <span className="disc">{w.disc}</span>
            <div className={"ph" + (hoverRow === w.id ? " playing" : "") + (w.posterOnly ? " ph-poster" : "")}
                 style={w.focus ? { "--focus": w.focus } : undefined}>
              {MotionSeq
                ? <MotionSeq frames={w.frames} warm={w.warm} playing={hoverRow === w.id} fps={1.8} alt={w.title + t("listSep") + w.disc} />
                : <img src={w.frames[0]} alt={w.title + t("listSep") + w.disc} />}
              {w.galleryFrames.length > 1 ? (
                <span className={"shot-badge" + (hoverRow === w.id ? " live" : "")}
                      style={hoverRow === w.id ? { background: "var(--terra-fill)", color: "#fff", borderColor: "var(--terra-fill)" } : undefined}>
                  {hoverRow === w.id
                    ? <React.Fragment><i className="dot"></i>{t("photos")(w.galleryFrames.length)}</React.Fragment>
                    : <React.Fragment>
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="7" y="3" width="14" height="12" rx="2"/><path d="M17 19H5a2 2 0 0 1-2-2V7"/></svg>
                        {N(w.galleryFrames.length)}
                      </React.Fragment>}
                </span>
              ) : null}
              {w.video ? (
                <span className="shot-badge vid" title={t("lbWatch")}>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m10 8 6 4-6 4V8z"/><rect x="2" y="4" width="20" height="16" rx="3"/></svg>
                  {t("badgeVideo")}
                </span>
              ) : null}
            </div>
          </article>
        ))}
        {shownWorks.length === 0 ? <p className="work-empty">{t("workEmpty")}</p> : null}
      </section>

      {/* FULL CREDITS */}
      <section className="credits" id="credits">
        <div className="credits-head">
          <h2 className="disp">{t("creditsHead")}</h2>
          <span className="count">{t("creditsCount")(restCredits.length)}</span>
        </div>
        <ol className="credits-list">
          {restCredits.map((c) => (
            <li key={c.id} className={"credit" + ((c.galleryFrames && c.galleryFrames.length) ? " has-shots" : "")}
                {...((c.galleryFrames && c.galleryFrames.length) ? { role: "button", tabIndex: 0, "aria-label": c.title,
                     onKeyDown: openOnKey(() => setOpenWorkId(c.id)) } : {})}
                onClick={() => { if (c.galleryFrames && c.galleryFrames.length) setOpenWorkId(c.id); }}>
              <span className="c-year">{c.year}</span>
              <span className="c-title disp">
                <span className="c-en">{c.title}
                  {(c.galleryFrames && c.galleryFrames.length) ? (
                    <span className="c-shots">
                      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="7" y="3" width="14" height="12" rx="2"/><path d="M17 19H5a2 2 0 0 1-2-2V7"/></svg>
                      {N(c.galleryFrames.length)}
                    </span>
                  ) : null}
                </span>
                {c.fa ? <span className="c-fa fa">{c.fa}</span> : null}
              </span>
              <span className="c-role">{c.role}</span>
              <span className="c-kind">{c.kind}</span>
              <span className="c-venue">{c.venue ? c.venue + (c.nights ? t("listSep") + c.nights : "") : (c.credits_crew || "")}</span>
            </li>
          ))}
        </ol>
        {restCredits.length === 0 ? <p className="work-empty">{t("creditsEmpty")}</p> : null}
        <p className="credits-note">{t("creditsNote")}</p>
      </section>

      {/* TEACHING */}
      <section className="teach" id="teaching">
        <h2 className="sec-k">{t("teachHead")}</h2>
        <div className="teach-in">
          <div>
            <p className="teach-lead">{P("teachIntro", (profile.teaching || {}).intro)}</p>
            <p className="teach-for"><b>{t("teachFor")}</b> {P("teachForWho", (profile.teaching || {}).forWho)}</p>
            <button className="teach-cta" onClick={() => enquire("teaching")}>{t("teachCta")}</button>
          </div>
          <dl className="teach-list">
            {(P("teachFormats", (profile.teaching || {}).formats) || []).map((f) => (
              <div key={f.k}><dt>{f.k}</dt><dd>{f.v}</dd></div>
            ))}
          </dl>
        </div>
      </section>

      {/* FOOTER */}
      <footer className="foot" id="contact">
        <div className="foot-top">
          <div className="foot-say">
            <div className="big disp">{apos(t("footBig")[0])}<br/><em>{apos(t("footBig")[1])}</em></div>
            <p className="foot-avail"><i className="dot"></i>{t("footAvail")}</p>
          </div>
          <div className="foot-act">
            <span className="foot-k">{t("footEnquiries")}</span>
            <a className="em disp" href={"mailto:" + (profile.email || "")}>{profile.email}</a>
            <div className="foot-tel">
              <a className="tel" href={"tel:" + (profile.phoneIntl || "")}>{profile.phone}</a>
              <span className="tel-apps">
                <a href={"https://wa.me/" + String(profile.phoneIntl || "").replace("+","")} target="_blank" rel="noopener">WhatsApp</a>
                <a href={"https://t.me/" + (profile.phoneIntl || "")} target="_blank" rel="noopener">Telegram</a>
              </span>
            </div>
            <div className="foot-btns">
              <button className="foot-enq" onClick={() => enquire()}>{t("footSend")}</button>
              <div className="cv-pick" ref={cvRef}>
                <button className="foot-cv" onClick={() => setCvOpen((v) => !v)} aria-expanded={cvOpen}>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v12"></path><path d="m7 11 5 5 5-5"></path><path d="M4 20h16"></path></svg>
                  {t("footCv")}
                </button>
                {cvOpen ? (
                  <div className="cv-menu">
                    <span className="cv-lbl">{t("footCvPick")}</span>
                    <a href={A("Sara Akef CV.html")} target="_blank" rel="noopener" onClick={() => setCvOpen(false)}>English</a>
                    <a href={A("Sara Akef CV FA.html")} target="_blank" rel="noopener" onClick={() => setCvOpen(false)} className="rtl">فارسی</a>
                    <a href={A("Sara Akef CV PL.html")} target="_blank" rel="noopener" onClick={() => setCvOpen(false)}>Polski</a>
                  </div>
                ) : null}
              </div>
            </div>
            <span className="foot-k foot-k2">{t("footElsewhere")}</span>
            <div className="foot-social">
              <a href={profile.instagram} target="_blank" rel="noopener">Instagram</a>
              <a href={profile.linkedin} target="_blank" rel="noopener">LinkedIn</a>
              <a href={profile.tiwall} target="_blank" rel="noopener">Tiwall</a>
            </div>
          </div>
        </div>
        <div className="foot-base">
          <span>{t("footRights")(new Date().getFullYear())}</span>
        </div>
      </footer>

      {EnquiryForm ? <EnquiryForm open={!!enquiry} onClose={() => setEnquiry(null)} preset={enquiry ? enquiry.type : null} /> : null}
      {WorkLightbox ? (() => {
        const c = allCredits.find((x) => x.id === openWorkId);
        return <WorkLightbox credit={c ? Object.assign({}, c, { frames: c.galleryFrames }) : null} onClose={() => setOpenWorkId(null)} />;
      })() : null}
    </div>
  );
}
window.SaraSite = SaraSite;
