/* global React, useLang, LanguageSwitcher */
const { useState, useRef, useEffect } = React;

/* ============================================================
   useBP — viewport breakpoint hook
     sm: ≤ 720   md: 721–1024   lg: > 1024
   Mirrors the breakpoints baked into the page-level CSS vars.
   ============================================================ */
const useBP = () => {
  const get = () => (typeof window !== "undefined" ? window.innerWidth : 1280);
  const [w, setW] = useState(get());
  useEffect(() => {
    const on = () => setW(window.innerWidth);
    window.addEventListener("resize", on);
    return () => window.removeEventListener("resize", on);
  }, []);
  return {
    w,
    sm: w <= 720,
    md: w > 720 && w <= 1024,
    lg: w > 1024,
    notLg: w <= 1024,
  };
};

/* ============================================================
   Primitives — text-level atoms reused throughout the kit
   ============================================================ */

const Kicker = ({ children, color = "bronze" }) => (
  <div
    style={{
      fontFamily: "var(--font-latin-sans)",
      fontSize: 11,
      letterSpacing: "0.22em",
      textTransform: "uppercase",
      color: color === "bronze" ? "var(--foiga-bronze)" : "var(--ink-3)",
    }}
  >
    {children}
  </div>
);

const Folio = ({ children, light }) => (
  <div
    style={{
      fontFamily: "var(--font-latin-sans)",
      fontSize: 10,
      letterSpacing: "0.22em",
      textTransform: "uppercase",
      color: light ? "rgba(251,247,238,0.85)" : "var(--ink-3)",
    }}
  >
    {children}
  </div>
);

const Tag = ({ children, solid, muted }) => {
  const base = {
    fontFamily: "var(--font-latin-sans)",
    fontSize: 10,
    letterSpacing: "0.18em",
    textTransform: "uppercase",
    padding: "7px 14px",
    borderRadius: 999,
    border: "1px solid var(--foiga-bronze)",
    color: "var(--foiga-bronze)",
    background: "var(--paper-warm)",
    display: "inline-block",
  };
  if (solid) Object.assign(base, { background: "var(--foiga-bronze)", color: "var(--paper-warm)" });
  if (muted) Object.assign(base, { borderColor: "var(--rule)", color: "var(--ink-3)" });
  return <span style={base}>{children}</span>;
};

const Button = ({ children, variant = "primary", as = "button", ...rest }) => {
  const base = {
    fontFamily: "var(--font-latin-sans)",
    fontSize: 11,
    letterSpacing: "0.18em",
    textTransform: "uppercase",
    padding: "14px 22px",
    border: "1px solid transparent",
    background: "transparent",
    cursor: "pointer",
    lineHeight: 1,
    display: "inline-block",
    textDecoration: "none",
    transition: "background 140ms ease, color 140ms ease, border-color 140ms ease",
  };
  const variants = {
    primary: { background: "var(--ink-1)", color: "var(--paper-warm)" },
    bronze: { background: "var(--foiga-bronze)", color: "var(--paper-warm)" },
    outline: { borderColor: "var(--ink-1)", color: "var(--ink-1)" },
    ghost: { color: "var(--ink-1)", borderBottom: "1px solid var(--ink-1)", padding: "8px 0" },
  };
  const TagEl = as;
  return <TagEl style={{ ...base, ...variants[variant] }} {...rest}>{children}</TagEl>;
};

const Hairline = ({ width, ink, style }) => (
  <div
    style={{
      borderTop: `1px solid ${ink ? "var(--ink-1)" : "var(--hairline)"}`,
      width: width || "100%",
      ...style,
    }}
  />
);

/* ============================================================
   Top navigation — sticky hairline, brand + nav + language switch
   Sessions item opens a small dropdown of subsections.
   ============================================================ */

const navItems = [
  { key: "home",     href: "#top" },
  { key: "journal",  href: "#journal" },
  { key: "sessions", href: "#sessions", sub: [
    { key: "plans",   href: "#sessions-plans" },
    { key: "short",   href: "#sessions-short" },
    { key: "addons",  href: "#sessions-addons" },
    { key: "details", href: "#sessions-details" },
    { key: "album",   href: "#sessions-album" },
  ]},
  { key: "about",    href: "#about" },
];

const NavItem = ({ item }) => {
  const { t } = useLang();
  const [open, setOpen] = useState(false);
  const timer = useRef(null);
  const onEnter = () => { clearTimeout(timer.current); setOpen(true); };
  const onLeave = () => { timer.current = setTimeout(() => setOpen(false), 160); };

  if (!item.sub) {
    return (
      <a
        href={item.href}
        style={{
          fontFamily: "var(--font-sans)",
          fontSize: 12,
          letterSpacing: "0.18em",
          textTransform: "uppercase",
          color: "var(--ink-1)",
          border: 0,
          whiteSpace: "nowrap",
        }}
      >
        {t("nav." + item.key)}
      </a>
    );
  }

  return (
    <div style={{ position: "relative" }} onMouseEnter={onEnter} onMouseLeave={onLeave}>
      <a
        href={item.href}
        style={{
          fontFamily: "var(--font-sans)",
          fontSize: 12,
          letterSpacing: "0.18em",
          textTransform: "uppercase",
          color: open ? "var(--foiga-bronze)" : "var(--ink-1)",
          border: 0,
          whiteSpace: "nowrap",
          display: "inline-flex",
          alignItems: "center",
          gap: 6,
          transition: "color 140ms ease",
        }}
      >
        {t("nav." + item.key)}
        <span style={{ fontSize: 8, opacity: 0.7, transform: open ? "rotate(180deg)" : "none", transition: "transform 140ms ease" }}>▾</span>
      </a>
      <div
        style={{
          position: "absolute",
          top: "calc(100% + 14px)",
          left: -16,
          background: "var(--paper-warm)",
          border: "1px solid var(--hairline)",
          padding: "14px 0",
          minWidth: 240,
          opacity: open ? 1 : 0,
          visibility: open ? "visible" : "hidden",
          transform: open ? "translateY(0)" : "translateY(-4px)",
          transition: "opacity 180ms ease, transform 180ms ease, visibility 180ms",
          boxShadow: "var(--shadow-2)",
        }}
      >
        {item.sub.map((s, i) => (
          <a
            key={s.key}
            href={s.href}
            style={{
              display: "flex",
              alignItems: "baseline",
              gap: 12,
              padding: "10px 22px",
              fontFamily: "var(--font-serif)",
              fontSize: 15,
              color: "var(--ink-1)",
              border: 0,
              transition: "background 140ms ease, color 140ms ease",
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--paper-cream)"; e.currentTarget.style.color = "var(--foiga-bronze)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink-1)"; }}
          >
            <span style={{ fontFamily: "var(--font-latin-sans)", fontSize: 9, letterSpacing: "0.22em", color: "var(--ink-3)", minWidth: 18 }}>
              0{i + 1}
            </span>
            {t("sub." + s.key)}
          </a>
        ))}
      </div>
    </div>
  );
};

const TopNav = () => {
  const { t } = useLang();
  const { sm, notLg } = useBP();
  const [drawer, setDrawer] = useState(false);

  // Close drawer when viewport grows or when a link is clicked
  useEffect(() => { if (!notLg) setDrawer(false); }, [notLg]);
  useEffect(() => {
    document.body.style.overflow = drawer ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [drawer]);

  return (
    <header
      style={{
        position: "sticky",
        top: 0,
        zIndex: 50,
        display: "flex",
        alignItems: "center",
        padding: notLg ? "14px var(--page-pad)" : "16px var(--page-pad)",
        borderBottom: "1px solid var(--hairline)",
        background: "rgba(246,241,232,0.92)",
        backdropFilter: "blur(8px)",
        WebkitBackdropFilter: "blur(8px)",
      }}
    >
      <a href="#top" onClick={() => setDrawer(false)} style={{ display: "flex", alignItems: "center", gap: 12, border: 0 }}>
        <img src={window.__resources.logo256} alt="Foiga" style={{ width: 30, height: 30, display: "block" }} />
        <span style={{ fontFamily: "var(--font-display)", fontSize: 17, letterSpacing: "0.06em", color: "var(--ink-1)" }}>
          {sm ? "FOIGA" : t("nav.brand")}
        </span>
      </a>
      <div style={{ flex: 1 }} />

      {/* Desktop nav */}
      {!notLg && (
        <>
          <nav style={{ display: "flex", gap: 30, alignItems: "center" }}>
            {navItems.map((item) => <NavItem key={item.key} item={item} />)}
          </nav>
          <a
            href="#inquire"
            style={{
              marginLeft: 28,
              marginRight: 20,
              fontFamily: "var(--font-sans)",
              fontSize: 12,
              letterSpacing: "0.18em",
              textTransform: "uppercase",
              color: "var(--foiga-bronze)",
              border: 0,
              whiteSpace: "nowrap",
            }}
          >
            {t("nav.inquire")}
          </a>
          <LanguageSwitcher />
        </>
      )}

      {/* Mobile / tablet — hamburger */}
      {notLg && (
        <button
          aria-label="Menu"
          aria-expanded={drawer}
          onClick={() => setDrawer(v => !v)}
          style={{
            background: "transparent",
            border: 0,
            cursor: "pointer",
            padding: 8,
            margin: "-8px -8px -8px 0",
            display: "flex",
            flexDirection: "column",
            gap: 5,
            width: 36,
          }}
        >
          {[0,1,2].map(i => (
            <span key={i} style={{
              display: "block",
              height: 1,
              width: 22,
              background: "var(--ink-1)",
              transition: "transform 220ms ease, opacity 220ms ease",
              transform: drawer
                ? (i === 0 ? "translateY(6px) rotate(45deg)" : i === 2 ? "translateY(-6px) rotate(-45deg)" : "none")
                : "none",
              opacity: drawer && i === 1 ? 0 : 1,
            }}/>
          ))}
        </button>
      )}

      {/* Mobile drawer */}
      {notLg && (
        <div
          style={{
            position: "fixed",
            inset: 0,
            top: 60,
            background: "var(--paper)",
            zIndex: 49,
            opacity: drawer ? 1 : 0,
            visibility: drawer ? "visible" : "hidden",
            transition: "opacity 240ms ease, visibility 240ms",
            overflowY: "auto",
            display: "flex",
            flexDirection: "column",
            padding: "32px var(--page-pad) 48px",
          }}
        >
          <div style={{ display: "flex", flexDirection: "column" }}>
            {navItems.map((item) => (
              <div key={item.key} style={{ borderBottom: "1px solid var(--hairline)" }}>
                <a
                  href={item.href}
                  onClick={() => setDrawer(false)}
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "baseline",
                    padding: "22px 0",
                    fontFamily: "var(--font-display)",
                    fontSize: 26,
                    letterSpacing: "-0.005em",
                    color: "var(--ink-1)",
                    border: 0,
                  }}
                >
                  <span>{t("nav." + item.key)}</span>
                  <span style={{
                    fontFamily: "var(--font-latin-sans)",
                    fontSize: 10,
                    letterSpacing: "0.22em",
                    color: "var(--ink-3)",
                  }}>
                    0{navItems.indexOf(item) + 1}
                  </span>
                </a>
                {item.sub && (
                  <div style={{ paddingBottom: 18, paddingLeft: 4, display: "flex", flexDirection: "column", gap: 12 }}>
                    {item.sub.map((s) => (
                      <a key={s.key} href={s.href} onClick={() => setDrawer(false)}
                        style={{
                          fontFamily: "var(--font-serif)",
                          fontSize: 16,
                          color: "var(--ink-2)",
                          border: 0,
                        }}>
                        — {t("sub." + s.key)}
                      </a>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
          <div style={{ marginTop: 36, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24 }}>
            <a
              href="#inquire"
              onClick={() => setDrawer(false)}
              style={{
                fontFamily: "var(--font-sans)",
                fontSize: 12,
                letterSpacing: "0.18em",
                textTransform: "uppercase",
                color: "var(--foiga-bronze)",
                border: 0,
              }}
            >
              {t("nav.inquire")}
            </a>
            <LanguageSwitcher />
          </div>
        </div>
      )}
    </header>
  );
};

/* ============================================================
   Hero — paper layout, title left, current-issue artifact right
   ============================================================ */

const Hero = () => {
  const { t, lang } = useLang();
  const { sm, notLg } = useBP();
  // Hero uses a 3-line stacked headline — text per language
  const titleLines = {
    zh: ["用一勺光，", "記下", "每一天。"],
    en: ["A spoonful", "of light,", "a record of days."],
    ja: ["ひとさじの", "光で、", "日々を。"],
  }[lang];
  const subtitle = {
    zh: "日々を、ひとさじの光で。",
    en: "日々を、ひとさじの光で。",
    ja: "A spoonful of light, a record of days.",
  }[lang];
  return (
    <section
      id="top"
      style={{
        background: "var(--paper)",
        padding: sm ? "40px var(--page-pad) 56px" : "72px var(--page-pad) 96px",
        borderBottom: "1px solid var(--hairline)",
      }}
    >
      <div style={{ display: "flex", alignItems: "baseline", marginBottom: sm ? 32 : 56, gap: 16, flexWrap: "wrap" }}>
        <Folio>{t("hero.folio.issue")}</Folio>
        <div style={{ flex: 1 }} />
        <Folio>{t("hero.folio.city")}</Folio>
        <Folio>{t("hero.folio.date")}</Folio>
      </div>
      <div style={{
        display: "grid",
        gridTemplateColumns: notLg ? "1fr" : "1.05fr 1fr",
        gap: notLg ? 40 : 80,
        alignItems: "center",
      }}>
        <div>
          <Kicker>{t("hero.kicker")}</Kicker>
          <h1
            style={{
              fontFamily: "var(--font-display)",
              fontSize: lang === "zh" ? "clamp(44px, 9vw, 108px)" : "clamp(46px, 10vw, 120px)",
              lineHeight: 0.98,
              letterSpacing: "-0.015em",
              margin: "18px 0 14px",
              color: "var(--ink-1)",
            }}
          >
            {titleLines.map((l, i) => <span key={i} style={{ display: "block" }}>{l}</span>)}
          </h1>
          <div
            style={{
              fontFamily: "var(--font-serif)",
              fontSize: sm ? 18 : 22,
              color: "var(--ink-2)",
              lineHeight: 1.55,
            }}
          >
            {subtitle}
          </div>
          <Hairline ink width={80} style={{ margin: sm ? "28px 0 20px" : "36px 0 24px" }} />
          <p
            style={{
              fontFamily: "var(--font-serif)",
              fontSize: sm ? 16 : 17,
              lineHeight: 1.85,
              color: "var(--ink-2)",
              margin: 0,
              maxWidth: 500,
            }}
          >
            {t("hero.body")}
          </p>
          <div style={{ marginTop: sm ? 28 : 40, display: "flex", gap: 18, alignItems: "center", flexWrap: "wrap" }}>
            <Button variant="primary">{t("hero.cta.primary")}</Button>
            <Button variant="ghost">{t("hero.cta.ghost")}</Button>
          </div>
        </div>
        <figure style={{
          margin: 0,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          gap: 18,
          order: notLg ? -1 : 0, // photo above text on small screens
        }}>
          <div
            style={{
              width: notLg ? "100%" : "82%",
              maxWidth: notLg ? 440 : "none",
              aspectRatio: "3 / 4",
              background: `url(${window.__resources.p01}) center/cover no-repeat`,
              boxShadow: "var(--shadow-print)",
              border: "1px solid var(--washi)",
            }}
          />
          <figcaption style={{ textAlign: "center", display: "flex", flexDirection: "column", gap: 6 }}>
            <Kicker color="bronze">{t("hero.current")}</Kicker>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22, letterSpacing: "-0.005em", color: "var(--ink-1)" }}>
              {t("hero.current.title")}
            </div>
            <Folio>{t("hero.current.meta")}</Folio>
          </figcaption>
        </figure>
      </div>
    </section>
  );
};

/* ============================================================
   Section header — reusable across page sections
   ============================================================ */

const SectionHead = ({ kicker, title, subtitle, num }) => {
  const { sm } = useBP();
  return (
    <div style={{
      display: "flex",
      alignItems: "baseline",
      padding: "0 var(--page-pad)",
      marginBottom: sm ? 28 : 40,
      gap: 24,
      flexWrap: "wrap",
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <Kicker>● {kicker}</Kicker>
        <h2
          style={{
            fontFamily: "var(--font-display)",
            fontSize: "clamp(34px, 5.4vw, 56px)",
            lineHeight: 1.02,
            letterSpacing: "-0.01em",
            margin: "12px 0 8px",
            color: "var(--ink-1)",
          }}
        >
          {title}
        </h2>
        {subtitle && (
          <div style={{ fontFamily: "var(--font-serif)", fontSize: sm ? 17 : 20, color: "var(--ink-2)", fontStyle: "italic" }}>
            {subtitle}
          </div>
        )}
      </div>
      {num && <Folio>{num}</Folio>}
    </div>
  );
};

/* ============================================================
   Journal strip — editorial cards (seed + pipeline API)
   ============================================================ */

const CATEGORY_ZH = {
  wedding:"婚紗", portrait:"人像", landscape:"風景", season:"季節",
  event:"活動", travel:"旅拍", commercial:"商業", family:"家庭",
};

const JournalCard = ({ image, num, place, title, sub, meta }) => (
  <article style={{ display: "flex", flexDirection: "column", gap: 10 }}>
    <div
      style={{
        width: "100%",
        aspectRatio: "4 / 5",
        background: `url('${image}') center/cover no-repeat`,
        marginBottom: 6,
      }}
    />
    <Kicker>№ {num} · {place}</Kicker>
    <h3
      style={{
        fontFamily: "var(--font-display)",
        fontSize: 26,
        lineHeight: 1.12,
        letterSpacing: "-0.005em",
        color: "var(--ink-1)",
        margin: "2px 0",
      }}
    >
      {title}
    </h3>
    {sub && (
      <div style={{ fontFamily: "var(--font-serif)", fontSize: 15, color: "var(--ink-2)", fontStyle: "italic" }}>
        {sub}
      </div>
    )}
    <Hairline style={{ marginTop: 10 }} />
    <Folio>{meta}</Folio>
  </article>
);

const JournalStrip = () => {
  const { t, lang } = useLang();
  const { sm, md } = useBP();
  const [apiPosts, setApiPosts] = useState([]);

  useEffect(() => {
    fetch('https://foiga-api.foigafoto.workers.dev/api/posts?limit=6')
      .then(r => r.ok ? r.json() : { posts: [] })
      .then(({ posts = [] }) => setApiPosts(posts))
      .catch(() => {});
  }, []);

  const SEED_IMGS = [window.__resources.p07, window.__resources.p17, window.__resources.p18];
  const seed = ({
    zh: [
      { place: "奈良",   title: "與鹿並肩的早晨",          sub: "東大寺前的櫻花林。",             meta: "光影手帖 · 約 8 分鐘" },
      { place: "京都",   title: "緣側上的午後",            sub: "粉色袷、一只風鈴、無風。",        meta: "京都散步 · 約 12 分鐘" },
      { place: "町家",   title: "拍攝結束後，他們跳起來。",  sub: "在居酒屋的門口、雨後的下午。",   meta: "拍攝側記 · 約 6 分鐘" },
    ],
    en: [
      { place: "Nara",    title: "A morning beside the deer",    sub: "Cherry trees in front of Tōdaiji.",    meta: "Journal · 8 min read" },
      { place: "Kyoto",   title: "An afternoon on the engawa",   sub: "Pink awase, one wind chime, no wind.", meta: "A walk in Kyoto · 12 min" },
      { place: "Machiya", title: "After the shoot, they jumped", sub: "Outside an izakaya, after rain.",      meta: "Behind the camera · 6 min" },
    ],
    ja: [
      { place: "奈良",   title: "鹿のとなりの朝",           sub: "東大寺前の桜並木で。",               meta: "写真手帖 · 約 8 分" },
      { place: "京都",   title: "縁側のひととき",            sub: "ピンクの袷、風鈴ひとつ、風なし。",   meta: "京都散歩 · 約 12 分" },
      { place: "町家",   title: "撮影が終わって、跳ねた。",   sub: "居酒屋の前、雨上がりの午後。",       meta: "撮影の余白 · 約 6 分" },
    ],
  }[lang] || []).map((e, i) => ({ ...e, image: SEED_IMGS[i] }));

  const pipeline = apiPosts.map(p => ({
    image: p.thumb_url,
    place: p.exif_location || CATEGORY_ZH[p.ai_category] || "Foiga",
    title: p.title,
    sub: p.body ? p.body.slice(0, 52) + "…" : "",
    meta: `光影手帖 · ${CATEGORY_ZH[p.ai_category] || "攝影"}`,
  }));

  const all = [...pipeline, ...seed];

  return (
    <section id="journal" style={{ padding: sm ? "72px 0 64px" : "112px 0 96px", background: "var(--paper)" }}>
      <SectionHead
        kicker={t("journal.kicker")}
        title={t("journal.title")}
        subtitle={t("journal.subtitle")}
        num={`№ 01 / ${String(all.length).padStart(2, "0")}`}
      />
      <div style={{
        display: "grid",
        gridTemplateColumns: sm ? "1fr" : md ? "repeat(2, 1fr)" : "repeat(3, 1fr)",
        gap: sm ? 32 : 40,
        padding: "0 var(--page-pad)",
      }}>
        {all.map((e, i) => <JournalCard key={i} num={String(i + 1).padStart(2, "0")} {...e} />)}
      </div>
    </section>
  );
};

/* ============================================================
   Feature spread — magazine work commission
   ============================================================ */

const Feature = () => {
  const { t } = useLang();
  const { sm, notLg } = useBP();
  return (
    <section style={{
      background: "var(--paper-cream)",
      padding: sm ? "72px var(--page-pad)" : "112px var(--page-pad)",
    }}>
      <div style={{
        display: "grid",
        gridTemplateColumns: notLg ? "1fr" : "1.15fr 1fr",
        gap: notLg ? 40 : 80,
        alignItems: "center",
      }}>
        <div
          style={{
            aspectRatio: "3 / 4",
            maxWidth: notLg ? 520 : "none",
            width: "100%",
            margin: notLg ? "0 auto" : "0",
            background: `url(${window.__resources.p16}) center/cover no-repeat`,
            boxShadow: "var(--shadow-print)",
          }}
        />
        <div>
          <Kicker>{t("feature.kicker")}</Kicker>
          <h2
            style={{
              fontFamily: "var(--font-display)",
              fontSize: "clamp(38px, 6.4vw, 64px)",
              lineHeight: 1.0,
              letterSpacing: "-0.015em",
              color: "var(--ink-1)",
              margin: "14px 0 6px",
            }}
          >
            {t("feature.title")}
          </h2>
          <div style={{
            fontFamily: "var(--font-display)",
            fontSize: "clamp(26px, 3.8vw, 38px)",
            letterSpacing: "-0.01em",
            color: "var(--foiga-bronze)",
          }}>
            {t("feature.subtitle")}
          </div>
          <Hairline ink width={60} style={{ margin: "28px 0 22px" }} />
          <p style={{ fontFamily: "var(--font-serif)", fontSize: sm ? 15 : 16, lineHeight: 1.85, color: "var(--ink-2)", margin: "0 0 18px", maxWidth: 460 }}>
            {t("feature.body")}
          </p>
          <p style={{ fontFamily: "var(--font-serif)", fontSize: 13, lineHeight: 1.7, color: "var(--ink-3)", margin: "0 0 32px", maxWidth: 460, fontStyle: "italic" }}>
            {t("feature.credit")}
          </p>
          <div style={{ display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
            <Button variant="outline">{t("feature.cta")}</Button>
            <Tag muted>{t("feature.tag1")}</Tag>
            <Tag>{t("feature.tag2")}</Tag>
          </div>
        </div>
      </div>
    </section>
  );
};

/* ============================================================
   Portfolio grid — five-up thumbnail row
   ============================================================ */

const PortfolioGrid = () => {
  const { t, lang } = useLang();
  const { sm, md } = useBP();
  // 8-photo masonry-style grid — real Foiga work
  const items = [
    { img: window.__resources.p05,       zh: "屋簷上 · 京都", en: "On the rooftops · Kyoto",   ja: "屋根の上 · 京都",           span: "wide" },
    { img: window.__resources.p13,           zh: "鹿與笑聲 · 奈良", en: "Deer & laughter · Nara",  ja: "鹿と笑い · 奈良",            span: null },
    { img: window.__resources.p10, zh: "黑振袖 · 伏見稻荷", en: "Black furisode · Fushimi", ja: "黒振袖 · 伏見稲荷",       span: "wide" },
    { img: window.__resources.p14, zh: "和裝 · 神社午後", en: "Kimono · shrine afternoon", ja: "和装 · 神社の午後",         span: null },
    { img: window.__resources.p16,           zh: "櫻吹雪 · 京都", en: "Cherry blossoms · Kyoto",   ja: "桜吹雪 · 京都",             span: "tall" },
    { img: window.__resources.p02,   zh: "粉色和服 · 庭園", en: "Pink kimono · garden",     ja: "桜色の着物 · 庭園",         span: null },
    { img: window.__resources.p19,        zh: "二人參拜 · 神社", en: "A prayer · Inari shrine",  ja: "二人で参拝 · 神社",         span: null },
  ];
  const caption = (it) => ({ zh: it.zh, en: it.en, ja: it.ja }[lang]);
  return (
    <section id="about" style={{ padding: sm ? "72px var(--page-pad) 64px" : "112px var(--page-pad) 96px" }}>
      <SectionHead
        kicker={t("portfolio.kicker")}
        title={t("portfolio.title")}
        subtitle={t("portfolio.subtitle")}
        num="2024 — 2026"
      />
      <div
        style={{
          display: "grid",
          gridTemplateColumns: sm ? "repeat(2, 1fr)" : md ? "repeat(3, 1fr)" : "repeat(4, 1fr)",
          gridAutoRows: sm ? 180 : md ? 220 : 280,
          gap: sm ? 10 : 14,
        }}
      >
        {items.map((it, i) => {
          // On small screens, drop the column-span so layout doesn't break.
          const colSpan = sm ? 1 : (it.span === "wide" ? 2 : 1);
          const rowSpan = it.span === "tall" ? 2 : 1;
          return (
            <figure
              key={i}
              style={{
                margin: 0,
                gridRowEnd: `span ${rowSpan}`,
                gridColumnEnd: `span ${colSpan}`,
                display: "flex",
                flexDirection: "column",
                gap: 8,
              }}
            >
              <div
                style={{
                  width: "100%",
                  height: "100%",
                  background: `url('${it.img}') center/cover no-repeat`,
                  transition: "opacity 600ms cubic-bezier(.2,.6,.2,1)",
                  cursor: "pointer",
                }}
                onMouseEnter={(e) => (e.currentTarget.style.opacity = 0.88)}
                onMouseLeave={(e) => (e.currentTarget.style.opacity = 1)}
              />
              <figcaption style={{ fontFamily: "var(--font-sans)", fontSize: 12, color: "var(--ink-3)", lineHeight: 1.5 }}>
                {caption(it)}
              </figcaption>
            </figure>
          );
        })}
      </div>
    </section>
  );
};

/* ============================================================
   Inquiry — underline-only form + hanko mark
   ============================================================ */

const InquiryField = ({ label, placeholder, type = "text", textarea, name, value, onChange, required }) => (
  <label style={{ display: "flex", flexDirection: "column", flex: 1 }}>
    <span
      style={{
        fontFamily: "var(--font-sans)",
        fontSize: 11,
        letterSpacing: "0.18em",
        textTransform: "uppercase",
        color: "var(--ink-3)",
        marginBottom: 8,
      }}
    >
      {label}
    </span>
    {textarea ? (
      <textarea
        rows={3}
        name={name}
        value={value}
        onChange={onChange}
        required={required}
        placeholder={placeholder}
        style={{
          fontFamily: "var(--font-serif)", fontSize: 16, padding: "10px 0", border: 0,
          borderBottom: "1px solid var(--ink-1)", background: "transparent",
          color: "var(--ink-1)", outline: "none", resize: "vertical", fontStyle: "italic",
        }}
      />
    ) : (
      <input
        type={type}
        name={name}
        value={value}
        onChange={onChange}
        required={required}
        placeholder={placeholder}
        style={{
          fontFamily: "var(--font-serif)", fontSize: 16, padding: "10px 0", border: 0,
          borderBottom: "1px solid var(--ink-1)", background: "transparent",
          color: "var(--ink-1)", outline: "none",
        }}
      />
    )}
  </label>
);

const InquiryThanks = ({ submitted, onAgain }) => {
  const { t } = useLang();
  const { sm } = useBP();
  const rows = [
    ["inq.field.name",  submitted.name],
    ["inq.field.email", submitted.email],
    ["inq.field.date",  submitted.date],
    ["inq.field.where", submitted.where],
    ["inq.field.note",  submitted.note],
  ].filter(([, v]) => v && v.trim());
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: sm ? 28 : 36 }}>
      <div>
        <Kicker color="bronze">{t("inq.thanks.kicker")}</Kicker>
        <h3 style={{
          fontFamily: "var(--font-display)", fontSize: "clamp(28px, 3.6vw, 40px)",
          lineHeight: 1.1, letterSpacing: "-0.01em", margin: "10px 0 14px", color: "var(--ink-1)", fontWeight: 400,
        }}>{t("inq.thanks.title")}</h3>
        <div style={{ fontFamily: "var(--font-serif)", fontSize: sm ? 15 : 16, color: "var(--ink-2)", lineHeight: 1.7, maxWidth: 520 }}>
          {t("inq.thanks.body")}
        </div>
      </div>
      <dl style={{ margin: 0, padding: 0, borderTop: "1px solid var(--rule)" }}>
        {rows.map(([k, v]) => (
          <div key={k} style={{
            display: "grid",
            gridTemplateColumns: sm ? "1fr" : "160px 1fr",
            gap: sm ? 4 : 24,
            padding: "16px 0",
            borderBottom: "1px solid var(--rule)",
          }}>
            <dt className="foiga-meta" style={{ margin: 0 }}>{t(k)}</dt>
            <dd style={{
              margin: 0, fontFamily: "var(--font-serif)", fontSize: 16, lineHeight: 1.7,
              color: "var(--ink-1)", whiteSpace: "pre-wrap", wordBreak: "break-word",
            }}>{v}</dd>
          </div>
        ))}
      </dl>
      <div>
        <button onClick={onAgain} style={{
          background: "transparent", border: 0, padding: 0, cursor: "pointer",
          fontFamily: "var(--font-latin-sans)", fontSize: 11, letterSpacing: "0.22em",
          textTransform: "uppercase", color: "var(--foiga-bronze)",
          borderBottom: "1px solid var(--foiga-bronze-pale)", paddingBottom: 2,
        }}>{t("inq.thanks.again")}</button>
      </div>
    </div>
  );
};

const Inquiry = () => {
  const { t, lang } = useLang();
  const { sm, notLg } = useBP();
  const [form, setForm] = React.useState({ name: "", email: "", date: "", where: "", note: "" });
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = React.useState("");
  const [submitted, setSubmitted] = React.useState(null);

  const onChange = (e) => setForm((f) => ({ ...f, [e.target.name]: e.target.value }));

  const onSubmit = async (e) => {
    e.preventDefault();
    if (status === "sending") return;
    setStatus("sending");
    setErrorMsg("");
    try {
      const res = await fetch("/api/inquiry", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...form, lang }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) {
        throw new Error(data.error || `HTTP ${res.status}`);
      }
      setSubmitted(data.submitted || { ...form, lang });
      setStatus("sent");
    } catch (err) {
      setErrorMsg(t("inq.error"));
      setStatus("error");
    }
  };

  const reset = () => {
    setForm({ name: "", email: "", date: "", where: "", note: "" });
    setSubmitted(null);
    setStatus("idle");
    setErrorMsg("");
  };

  return (
    <section id="inquire" style={{
      background: "var(--paper-warm)",
      padding: sm ? "72px var(--page-pad)" : "120px var(--page-pad)",
    }}>
      <div style={{
        display: "grid",
        gridTemplateColumns: notLg ? "1fr" : "1fr 1.4fr",
        gap: notLg ? 48 : 80,
      }}>
        <div>
          <Kicker>{t("inq.kicker")}</Kicker>
          <h2
            style={{
              fontFamily: "var(--font-display)", fontSize: "clamp(36px, 5.4vw, 56px)", lineHeight: 1.02,
              letterSpacing: "-0.01em", margin: "12px 0 10px", color: "var(--ink-1)",
            }}
          >
            {t("inq.title")}
          </h2>
          <div style={{ fontFamily: "var(--font-serif)", fontSize: sm ? 16 : 18, color: "var(--ink-2)", fontStyle: "italic", maxWidth: 360 }}>
            {t("inq.subtitle")}
          </div>
          <div style={{ marginTop: sm ? 40 : 64, display: "flex", alignItems: "center", gap: 24 }}>
            <div
              style={{
                width: sm ? 64 : 86, height: sm ? 64 : 86, background: "var(--vermilion)", color: "var(--paper-warm)",
                fontFamily: "var(--font-display)", fontSize: sm ? 40 : 54, lineHeight: 1,
                display: "flex", alignItems: "center", justifyContent: "center",
                transform: "rotate(-4deg)", flexShrink: 0,
              }}
            >
              寫
            </div>
            <Folio>{t("inq.contact")}<br />{t("inq.location")}</Folio>
          </div>
        </div>

        {status === "sent" && submitted ? (
          <InquiryThanks submitted={submitted} onAgain={reset} />
        ) : (
          <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: sm ? 28 : 36 }}>
            <div style={{ display: "flex", gap: sm ? 20 : 36, flexDirection: sm ? "column" : "row" }}>
              <InquiryField label={t("inq.field.name")}  placeholder={t("inq.ph.name")}  name="name"  value={form.name}  onChange={onChange} required />
              <InquiryField label={t("inq.field.email")} placeholder={t("inq.ph.email")} name="email" value={form.email} onChange={onChange} type="email" required />
            </div>
            <div style={{ display: "flex", gap: sm ? 20 : 36, flexDirection: sm ? "column" : "row" }}>
              <InquiryField label={t("inq.field.date")}  placeholder={t("inq.ph.date")}  name="date"  value={form.date}  onChange={onChange} />
              <InquiryField label={t("inq.field.where")} placeholder={t("inq.ph.where")} name="where" value={form.where} onChange={onChange} />
            </div>
            <InquiryField label={t("inq.field.note")} placeholder={t("inq.ph.note")} name="note" value={form.note} onChange={onChange} textarea />
            {status === "error" && errorMsg && (
              <div style={{
                fontFamily: "var(--font-serif)", fontSize: 14, color: "var(--vermilion)",
                borderLeft: "2px solid var(--vermilion)", paddingLeft: 12, fontStyle: "italic", lineHeight: 1.6,
              }}>{errorMsg}</div>
            )}
            <div style={{ display: "flex", alignItems: "center", gap: 18, marginTop: 8, flexWrap: "wrap" }}>
              <Button variant="primary" type="submit" disabled={status === "sending"}>
                {status === "sending" ? t("inq.sending") : t("inq.cta")}
              </Button>
              <Folio>{t("inq.consent")}</Folio>
            </div>
          </form>
        )}
      </div>
    </section>
  );
};

/* ============================================================
   Footer
   ============================================================ */

const Footer = () => {
  const { t } = useLang();
  return (
    <footer
      style={{
        borderTop: "1px solid var(--hairline)",
        padding: "28px var(--page-pad)",
        display: "flex",
        alignItems: "center",
        gap: 24,
        rowGap: 12,
        flexWrap: "wrap",
        background: "var(--paper)",
      }}
    >
      <img src={window.__resources.logo256} alt="" style={{ width: 26, height: 26 }} />
      <Folio>{t("foot.brand")}</Folio>
      <Folio>{t("foot.issue")}</Folio>
      <div style={{ flex: 1, minWidth: 12 }} />
      <Folio>
        <a
          href="https://instagram.com/foigaphotography"
          target="_blank"
          rel="noopener noreferrer"
          aria-label="Foiga on Instagram"
          style={{ color: "inherit", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6 }}
        >
          <svg
            aria-hidden="true"
            width="12" height="12" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" strokeWidth="1.5"
            strokeLinecap="square" strokeLinejoin="miter"
            style={{ display: "block" }}
          >
            <rect x="2" y="2" width="20" height="20" rx="5" />
            <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" />
            <line x1="17.5" y1="6.5" x2="17.51" y2="6.5" />
          </svg>
          Instagram
        </a>
      </Folio>
      <Folio>Foiga.com</Folio>
      <Folio>© 2026</Folio>
    </footer>
  );
};

/* ============================================================
   Page composition — SessionsSection is loaded from sessions.jsx
   ============================================================ */

const HomePage = () => (
  <LangProvider>
    <div style={{ background: "var(--paper)" }}>
      <TopNav />
      <Hero />
      <JournalStrip />
      <Feature />
      <SessionsSection />
      <PortfolioGrid />
      <Inquiry />
      <Footer />
    </div>
  </LangProvider>
);

Object.assign(window, {
  HomePage, TopNav, Hero, JournalStrip, Feature, PortfolioGrid, Inquiry, Footer,
  Button, Tag, Kicker, Folio, Hairline, SectionHead, InquiryField,
  useBP,
});
