/* global React, window */
// ============================================================
// RISOGRAPH pages + STUDIO + CONTACT + case-study modal
// ============================================================

function ProjectCard({ p, lang, t, openCase, small }) {
  const d = p[lang] || p.en;
  if (p.placeholder) {
    return (
      <div className="proj-card placeholder">
        <div className="proj-thumb"><div className="ph" style={{ position: "absolute", inset: 0 }}><span>{d.disc}</span></div></div>
        <div className="proj-meta">
          <div className="disc">{lang === "ar" ? "شاغر" : "open slot"}</div>
          <h3>{d.title}</h3>
        </div>
      </div>
    );
  }
  return (
    <div className="proj-card" onClick={() => openCase(p)} role="button" tabIndex={0}
      onKeyDown={(e) => e.key === "Enter" && openCase(p)}>
      <div className="proj-thumb">
        {p.comingSoon && <span className="soon-ribbon">{lang === "ar" ? "قريباً" : "coming soon"}</span>}
        {p.img && <img className="proj-img" src={p.img} alt={d.title} loading="lazy" />}
        <div className="tagline">{d.tagline}</div>
      </div>
      <div className="proj-meta">
        <div className="disc">{d.disc}</div>
        <h3>{d.title}</h3>
      </div>
    </div>
  );
}

function PgRisoIntro({ t, lang, openCase }) {
  const { PROJECTS, PixelTuxedoCat } = window;
  const feat = PROJECTS.filter(p => ["weddingjo", "potatohead"].includes(p.id));
  return (
    <div className="riso riso-grain" style={{ height: "100%", display: "flex", flexDirection: "column", position: "relative" }}>
      <p className="eyebrow">02 · {lang === "ar" ? "الريزوغراف" : "Risograph"}</p>
      <h1 className="riso-title" style={{ margin: "0 0 6px" }}>{t.projectsTitle}</h1>
      <p style={{ fontFamily: "var(--grotesk)", fontSize: 12.5, lineHeight: 1.55, opacity: .85, margin: "0 0 12px", maxWidth: "42ch" }}>{t.projectsLede}</p>
      <div className="proj-grid" style={{ gridTemplateColumns: "1fr 1fr" }}>
        {feat.map(p => <ProjectCard key={p.id} p={p} lang={lang} t={t} openCase={openCase} />)}
      </div>
      <div style={{ position: "absolute", insetInlineEnd: 6, bottom: 22, pointerEvents: "none" }}>
        <PixelTuxedoCat size={92} blink={false} />
      </div>
      <span className="folio" style={{ color: "var(--realm-accent)" }}>vii</span>
    </div>
  );
}

function PgProjects({ t, lang, openCase }) {
  const { PROJECTS } = window;
  const rest = PROJECTS.filter(p => ["election", "loveseed", "nabtaty", "cloudette"].includes(p.id));
  return (
    <div className="riso riso-grain" style={{ height: "100%", display: "flex", flexDirection: "column" }}>
      <p className="eyebrow">{lang === "ar" ? "مطبوع في غرفة الريزو" : "Printed in the riso room"}</p>
      <div className="proj-grid" style={{ flex: 1 }}>
        {rest.map(p => <ProjectCard key={p.id} p={p} lang={lang} t={t} openCase={openCase} />)}
      </div>
      <span className="folio" style={{ color: "var(--realm-accent)" }}>viii</span>
    </div>
  );
}

// ---------- STUDIO ----------
function PgStudio({ t, lang }) {
  const { REALMS, PixelTuxedoCat } = window;
  const glyph = (i) => i % 3 === 0
    ? <circle cx="50" cy="50" r="22" />
    : i % 3 === 1
      ? <rect x="30" y="30" width="40" height="40" rx="4" />
      : <path d="M50 26 L72 62 L28 62 Z" />;
  return (
    <div className="analog studio" style={{ height: "100%" }}>
      <p className="eyebrow">{t.studioTitle}</p>
      <h2 style={{ fontSize: "clamp(22px,4vh,34px)", margin: "0 0 4px", lineHeight: 1 }}>{t.studioTitle}</h2>
      <p style={{ fontSize: 12.5, lineHeight: 1.55, opacity: .82, margin: "0 0 10px", maxWidth: "40ch" }}>{t.studioLede}</p>
      <div className="shelf">
        {REALMS.map((r, i) => (
          <div className="relic" key={r.key}>
            <div className="obj" style={{ background: "color-mix(in oklch, " + r.sw + " 26%, var(--realm-paper))" }}>
              <svg viewBox="0 0 100 100" width="46" height="46" fill={r.sw} opacity=".9">{glyph(i)}</svg>
            </div>
            <small>{lang === "ar" ? r.ar : r.en}</small>
          </div>
        ))}
        <div className="relic" style={{ display: "grid", placeItems: "center" }}>
          <PixelTuxedoCat size={96} variant="nap" />
        </div>
      </div>
      <Motes n={10} />
      <span className="folio">ix</span>
    </div>
  );
}

// ---------- CONTACT ----------
function PgContact({ t, lang, onLang }) {
  const [v, setV] = React.useState({ name: "", email: "", type: t.types[0], msg: "", lang: t.langs[0], hp: "" });
  const [err, setErr] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const set = (k) => (e) => setV(s => ({ ...s, [k]: e.target.value }));

  const submit = (e) => {
    e.preventDefault();
    if (v.hp) return; // honeypot
    const er = {};
    if (!v.name.trim()) er.name = t.req;
    if (!v.email.trim()) er.email = t.req;
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.email)) er.email = t.bademail;
    if (!v.msg.trim()) er.msg = t.req;
    setErr(er);
    if (Object.keys(er).length === 0) setSent(true);
  };

  return (
    <div className="analog" style={{ height: "100%", display: "flex", flexDirection: "column", position: "relative" }}>
      <p className="eyebrow">{t.contactTitle}</p>
      <h2 style={{ fontSize: "clamp(22px,4vh,34px)", margin: "0 0 2px", lineHeight: 1 }}>{t.contactTitle}</h2>
      <p style={{ fontStyle: "italic", fontSize: 13, opacity: .82, margin: "0 0 8px" }}>{t.contactLede}</p>
      <form className="form-paper" onSubmit={submit} noValidate>
        <div className="row2">
          <div className={"field" + (err.name ? " err" : "")}>
            <label>{t.f_name}</label>
            <input value={v.name} onChange={set("name")} autoComplete="off" />
            <div className="msg">{err.name}</div>
          </div>
          <div className={"field" + (err.email ? " err" : "")}>
            <label>{t.f_email}</label>
            <input value={v.email} onChange={set("email")} autoComplete="off" />
            <div className="msg">{err.email}</div>
          </div>
        </div>
        <div className="row2">
          <div className="field">
            <label>{t.f_type}</label>
            <select value={v.type} onChange={set("type")}>{t.types.map(o => <option key={o}>{o}</option>)}</select>
            <div className="msg" />
          </div>
          <div className="field">
            <label>{t.f_lang}</label>
            <select value={v.lang} onChange={set("lang")}>{t.langs.map(o => <option key={o}>{o}</option>)}</select>
            <div className="msg" />
          </div>
        </div>
        <div className={"field" + (err.msg ? " err" : "")}>
          <label>{t.f_msg}</label>
          <textarea value={v.msg} onChange={set("msg")} />
          <div className="msg">{err.msg}</div>
        </div>
        <input className="honeypot" tabIndex={-1} autoComplete="off" value={v.hp} onChange={set("hp")} aria-hidden="true" />
        <button type="submit" className="submit-stamp">{t.send}</button>
      </form>
      {sent && (
        <div className="sent-stamp"><div className="ink">{t.sent}</div></div>
      )}
      <span className="folio">x</span>
    </div>
  );
}

// ---------- Case study modal ----------
function CaseStudy({ p, lang, t, onClose }) {
  const d = p[lang] || p.en;
  React.useEffect(() => {
    const k = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, []);
  return (
    <div className="cs-overlay" onClick={onClose}>
      <div className={"cs-modal realm-" + p.realm} onClick={(e) => e.stopPropagation()}>
        <div className="cs-hero">
          <button className="cs-close" onClick={onClose} aria-label="close">×</button>
          {p.img
            ? <img src={p.img} alt={d.title} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
            : <div className="ph" style={{ position: "absolute", inset: 0, border: "none" }}><span>800 × 600 — {d.title}</span></div>}
        </div>
        <div className="cs-body">
          <div className="disc">{d.disc}</div>
          <h2>{d.title}</h2>
          <div className="stack">{t.builtWith}: {d.stack}</div>
          <p>{d.desc}</p>
          <p style={{ fontStyle: "italic", opacity: .8 }}>{t.role_label}: {d.role}</p>
          {p.metrics && (
            <div className="cs-metrics">
              {p.metrics.map((m, i) => (
                <div className="cs-metric" key={i}><b>{m.n}</b><span>{m.l[lang] || m.l.en}</span></div>
              ))}
            </div>
          )}
          {p.links && (
            <div className="cs-links">
              {p.links.map((l, i) => {
                const real = l.href && l.href !== "#";
                return <a key={i} href={l.href} target={real ? "_blank" : undefined} rel={real ? "noopener noreferrer" : undefined}
                  onClick={(e) => { if (!real) e.preventDefault(); }}>{l[lang] || l.en} ↗</a>;
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------- COLOPHON (closing page) ----------
function PgColophon({ t, lang }) {
  const { PixelTuxedoCat } = window;
  return (
    <div className="analog" style={{ height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center", gap: 10 }}>
      <p className="eyebrow">{lang === "ar" ? "تمّت" : "fin"}</p>
      <PixelTuxedoCat size={120} variant="nap" />
      <h2 style={{ fontFamily: "var(--serif-display)", fontSize: "clamp(24px,4vh,38px)", margin: "4px 0 0", lineHeight: 1 }}>
        {lang === "ar" ? "شكراً للقراءة" : "Thank you for reading"}
      </h2>
      <p style={{ fontStyle: "italic", fontSize: 13.5, opacity: .82, maxWidth: "32ch", lineHeight: 1.6 }}>
        {lang === "ar"
          ? "أُغلق الكتاب الآن. إن أعجبك ما رأيت، فلنصنع شيئاً معاً."
          : "The book closes here. If you liked what you saw, let's make something together."}
      </p>
      <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".06em", opacity: .7, marginTop: 6, lineHeight: 1.9 }}>
        <div>{t.name} · {t.place}</div>
        <div>ruhufatefruhuf@gmail.com</div>
      </div>
      <span className="folio">xii</span>
    </div>
  );
}

window.RisoPages = { ProjectCard, PgRisoIntro, PgProjects, PgStudio, PgContact, PgColophon, CaseStudy };
