/* components.jsx — shared visual system + sections for the Yigal Ben Dor site */

const { useState, useEffect, useRef } = React;

/* ---------- i18n helper ----------
   L(value, lang) → if value is a {en,he} dictionary, return the localized
   string; otherwise return the value unchanged. Lets data.js stay a single
   source of truth with both languages co-located per item. */
function L(v, lang) {
  if (v && typeof v === "object" && !Array.isArray(v) && ("en" in v || "he" in v)) {
    return v[lang] != null ? v[lang] : (v.en != null ? v.en : v.he);
  }
  return v;
}

/* ---------- themes & accents ---------- */
const THEMES = {
  light: {
    paper:"#F2EDE4", paper2:"#EAE2D4", paper3:"#E2D8C6",
    ink:"#211C16", inkSoft:"#5E564B", inkFaint:"#8C8275",
    line:"rgba(33,28,22,0.14)", line2:"rgba(33,28,22,0.07)", accentInk:"#FBF8F1",
  },
  dark: {
    paper:"#15120E", paper2:"#1D1914", paper3:"#262019",
    ink:"#ECE4D6", inkSoft:"#A99E8C", inkFaint:"#76705F",
    line:"rgba(236,228,214,0.15)", line2:"rgba(236,228,214,0.06)", accentInk:"#15120E",
  },
};
const ACCENTS = {
  bronze: "#9A7B45",
  stone:  "#6E7378",
  clay:   "#A75D4A",
  ink:    "#3A332A",
};
const MATERIAL_COLOR = { wood:"#B07B43", bronze:"#93702F", polymer:"#A75D4A", stone:"#6E7378" };

/* ---------- material surface (refined placeholder fill) ---------- */
function materialSurface(key, dark) {
  switch (key) {
    case "bronze":
      return {
        background:
          "radial-gradient(120% 90% at 32% 26%, #E7C879 0%, #B98C3E 26%, #7C5A26 58%, #4A3415 100%)",
      };
    case "polymer":
      return {
        background:
          "radial-gradient(130% 100% at 28% 22%, #E7B8A6 0%, #C07A63 34%, #8C4636 70%, #5E2C20 100%)",
      };
    case "stone":
      return {
        background:
          "radial-gradient(120% 95% at 35% 28%, #D8D2C6 0%, #ABA79C 38%, #7E8085 72%, #565A5E 100%)",
      };
    case "wood":
    default:
      return {
        background:
          "radial-gradient(120% 95% at 35% 25%, #E4BE85 0%, #C2904F 40%, #8E5E2C 74%, #5C3A18 100%)",
      };
  }
}

/* minimal bust glyph used only as a placeholder marker */
function BustGlyph({ size = 70, color = "rgba(255,255,255,0.5)" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" fill="none" aria-hidden="true">
      <path d="M50 12c-9 0-15 7-15 17 0 6 2 10 5 14-7 3-13 9-16 18-1 3-2 7-2 11h56c0-4-1-8-2-11-3-9-9-15-16-18 3-4 5-8 5-14 0-10-6-17-15-17z"
        stroke={color} strokeWidth="2" fill="none" strokeLinejoin="round" />
    </svg>
  );
}

function MaterialSurface({ pieceKey, dark, children, style }) {
  return (
    <div className="grain" style={{ position:"absolute", inset:0, ...materialSurface(pieceKey, dark), ...style }}>
      <div style={{ position:"absolute", inset:0,
        background:"linear-gradient(145deg, rgba(255,255,255,0.12), rgba(255,255,255,0) 40%, rgba(0,0,0,0.28))" }} />
      {children}
    </div>
  );
}

/* ---------- reveal-on-scroll hook ---------- */
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    el.querySelectorAll(".reveal").forEach((n) => io.observe(el === n ? n : n));
    if (el.classList.contains("reveal")) io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

/* ---------- piece card ---------- */
function PieceCard({ piece, mkey, dark, index, onOpen, lang }) {
  const [hover, setHover] = useState(false);
  const mColor = MATERIAL_COLOR[mkey];
  const ui = window.SITE.ui.piece;
  return (
    <button
      className="reveal"
      onClick={() => onOpen(piece)}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        all:"unset", cursor:"pointer", display:"block", width:"100%",
        transitionDelay: `${(index % 3) * 90}ms`,
      }}
    >
      <div style={{
        position:"relative", width:"100%", aspectRatio:"3 / 4", overflow:"hidden",
        background:"var(--paper-3)",
        boxShadow: hover ? "0 26px 50px -24px rgba(0,0,0,0.5)" : "0 12px 30px -22px rgba(0,0,0,0.45)",
        transition:"box-shadow .6s var(--ease)",
      }}>
        {piece.img ? (
          <img src={piece.img} alt={L(piece.title, lang)}
            style={{ position:"absolute", inset:0, width:"100%", height:"100%", objectFit:"cover",
              transform: hover ? "scale(1.045)" : "scale(1)", transition:"transform 1.2s var(--ease)", filter:"saturate(1.02)" }} />
        ) : (
          <MaterialSurface pieceKey={mkey} dark={dark}>
            <div style={{ position:"absolute", inset:0, display:"flex", flexDirection:"column",
              alignItems:"center", justifyContent:"center", gap:14,
              transform: hover ? "scale(1.03)" : "scale(1)", transition:"transform 1.2s var(--ease)" }}>
              <BustGlyph />
            </div>
          </MaterialSurface>
        )}

        {/* placeholder tag */}
        {!piece.img && (
          <div style={{ position:"absolute", top:14, left:14, zIndex:2,
            fontFamily:"Hanken Grotesk", fontSize:9.5, letterSpacing:".18em", textTransform:"uppercase",
            color:"rgba(255,255,255,0.92)", background:"rgba(0,0,0,0.32)", backdropFilter:"blur(4px)",
            padding:"5px 9px", borderRadius:99 }}>
            {L(ui.photo, lang)}
          </div>
        )}

        {/* hover caption sweep */}
        <div style={{ position:"absolute", left:0, right:0, bottom:0, zIndex:2, padding:"34px 18px 16px",
          background:"linear-gradient(to top, rgba(0,0,0,0.62), rgba(0,0,0,0))",
          opacity: hover ? 1 : 0, transform: hover ? "translateY(0)" : "translateY(8px)",
          transition:"opacity .5s var(--ease), transform .5s var(--ease)", color:"#fff" }}>
          <div style={{ fontFamily:"Hanken Grotesk", fontSize:11, letterSpacing:".06em", opacity:.85 }}>
            {L(ui.view, lang)}
          </div>
        </div>
      </div>

      <div style={{ paddingTop:16, display:"flex", justifyContent:"space-between", alignItems:"baseline", gap:12 }}>
        <div>
          <h4 style={{ fontSize:21, color:"var(--ink)" }}>{L(piece.title, lang)}</h4>
          <div style={{ fontSize:13, color:"var(--ink-soft)", marginTop:3 }}>{L(piece.material, lang)}</div>
        </div>
        <div style={{ fontFamily:"Hanken Grotesk", fontSize:12.5, color:"var(--ink-faint)",
          borderBottom:`1.5px solid ${mColor}`, paddingBottom:2, whiteSpace:"nowrap" }}>{piece.year}</div>
      </div>
    </button>
  );
}

/* ---------- a material gallery section ---------- */
function MaterialSection({ material, idx, dark, onOpen, lang }) {
  const ref = useReveal();
  const mColor = MATERIAL_COLOR[material.key];
  const num = String(idx + 1).padStart(2, "0");
  return (
    <section ref={ref} id={material.key} data-screen-label={L(material.name, lang)}
      style={{ padding:"clamp(80px,11vh,150px) 0", borderTop:"1px solid var(--line-2)" }}>
      <div className="container">
        <div style={{ display:"grid", gridTemplateColumns:"minmax(0,1fr)", gap:0, marginBottom:54 }}>
          <div style={{ display:"flex", alignItems:"flex-end", gap:18, flexWrap:"wrap" }}>
            <span className="reveal" style={{ fontFamily:"Cormorant Garamond", fontStyle:"italic",
              fontSize:"clamp(34px,5vw,64px)", color:mColor, lineHeight:1, opacity:.9 }}>{num}</span>
            <h2 className="reveal" style={{ fontSize:"clamp(40px,7vw,86px)", color:"var(--ink)", flex:"0 1 auto" }}>
              {L(material.name, lang)}
            </h2>
          </div>
          <div className="reveal" style={{ marginTop:20, display:"grid",
            gridTemplateColumns:"minmax(0,1fr)", maxWidth:620 }}>
            <span className="eyebrow" style={{ color:mColor, marginBottom:10 }}>{L(material.subtitle, lang)}</span>
            <p style={{ fontSize:17, color:"var(--ink-soft)", lineHeight:1.7 }}>{L(material.blurb, lang)}</p>
          </div>
        </div>

        <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit, minmax(240px, 1fr))", gap:"clamp(22px,3vw,44px)" }}>
          {material.pieces.map((p, i) => (
            <PieceCard key={p.id} piece={p} mkey={material.key} dark={dark} index={i} onOpen={onOpen} lang={lang} />
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- piece detail overlay ---------- */
function PieceDetail({ piece, mkey, dark, onClose, lang }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, []);
  if (!piece) return null;
  const mColor = MATERIAL_COLOR[mkey];
  const ui = window.SITE.ui.piece;
  return (
    <div onClick={onClose} style={{ position:"fixed", inset:0, zIndex:120,
      background: dark ? "rgba(8,7,5,0.82)" : "rgba(30,26,20,0.62)", backdropFilter:"blur(8px)",
      display:"flex", alignItems:"center", justifyContent:"center", padding:"clamp(16px,4vw,56px)",
      animation:"fadeIn .4s var(--ease) .02s forwards" }}>
      <style>{`@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes riseIn{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:none}}@media(prefers-reduced-motion:reduce){[data-detail]{animation:none!important;}}`}</style>
      <div onClick={(e) => e.stopPropagation()} style={{
        width:"min(1040px, 100%)", maxHeight:"88vh", overflow:"auto", background:"var(--paper)",
        display:"grid", gridTemplateColumns:"minmax(0, 1.05fr) minmax(0, 0.95fr)",
        boxShadow:"0 40px 120px -30px rgba(0,0,0,0.7)", animation:"riseIn .5s var(--ease) .02s forwards" }}>
        <div style={{ position:"relative", minHeight:360, background:"var(--paper-3)" }}>
          {piece.img ? (
            <img src={piece.img} alt={L(piece.title, lang)} style={{ width:"100%", height:"100%", objectFit:"cover", minHeight:360 }} />
          ) : (
            <MaterialSurface pieceKey={mkey} dark={dark}>
              <div style={{ position:"absolute", inset:0, display:"flex", alignItems:"center", justifyContent:"center" }}>
                <BustGlyph size={110} />
              </div>
            </MaterialSurface>
          )}
        </div>
        <div style={{ padding:"clamp(28px,4vw,52px)", display:"flex", flexDirection:"column" }}>
          <button onClick={onClose} aria-label="Close" style={{ all:"unset", cursor:"pointer",
            alignSelf:"flex-end", fontFamily:"Hanken Grotesk", fontSize:12, letterSpacing:".18em",
            textTransform:"uppercase", color:"var(--ink-faint)" }}>{L(ui.close, lang)}</button>
          <span className="eyebrow" style={{ color:mColor, marginTop:18 }}>{L(piece.subtitle, lang)}</span>
          <h2 style={{ fontSize:"clamp(36px,4vw,52px)", color:"var(--ink)", marginTop:12 }}>{L(piece.title, lang)}</h2>
          {piece.note && <p style={{ fontFamily:"Cormorant Garamond", fontStyle:"italic", fontSize:22,
            color:"var(--ink-soft)", marginTop:18, lineHeight:1.45 }}>{L(piece.note, lang)}</p>}

          <dl style={{ margin:"30px 0 0", display:"grid", gridTemplateColumns:"auto 1fr", rowGap:14, columnGap:24,
            borderTop:"1px solid var(--line)", paddingTop:24 }}>
            {[[L(ui.material, lang), L(piece.material, lang)], [L(ui.year, lang), piece.year], [L(ui.dimensions, lang), L(piece.size, lang)]].map(([k,v]) => v && (
              <React.Fragment key={k}>
                <dt className="eyebrow" style={{ alignSelf:"center" }}>{k}</dt>
                <dd style={{ margin:0, fontSize:16, color:"var(--ink)" }}>{v}</dd>
              </React.Fragment>
            ))}
          </dl>

          <div style={{ marginTop:"auto", paddingTop:34, display:"flex", gap:14, alignItems:"center", flexWrap:"wrap" }}>
            <a href="#contact" onClick={onClose} style={{
              fontFamily:"Hanken Grotesk", fontWeight:600, fontSize:13.5, letterSpacing:".04em",
              background:"var(--accent)", color:"var(--accent-ink)", padding:"14px 26px" }}>
              {L(ui.inquire, lang)}
            </a>
            <span style={{ fontSize:13.5, color:"var(--ink-faint)" }}>{L(ui.priceOnRequest, lang)}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  L,
  THEMES, ACCENTS, MATERIAL_COLOR, materialSurface,
  BustGlyph, MaterialSurface, useReveal,
  PieceCard, MaterialSection, PieceDetail,
});
