/* Innmade site — React components */
const { useState, useEffect, useRef, useMemo } = React;

/* ---------- TWEAK DEFAULTS ---------- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#E8FF5C",
  "type": "editorial",
  "density": "default",
  "grain": true,
  "cursor": false
}/*EDITMODE-END*/;

const ACCENTS = [
  { hex: "#E8FF5C", name: "Lime" },
  { hex: "#FF5A1F", name: "Ember" },
  { hex: "#4F8CFF", name: "Ion" },
  { hex: "#B388FF", name: "Heather" },
  { hex: "#1A7F4F", name: "Kelp" },
  { hex: "#F2F1EC", name: "Bone" },
];

/* ---------- EMAIL LINK (click-to-reveal, JS-composed) ---------- */
function EmailLink({ className, style, children }) {
  const [addr, setAddr] = useState("");
  const [revealed, setRevealed] = useState(false);
  useEffect(() => {
    // Defer composition until after mount so static DOM contains no email
    const u = ["h","e","l","l","o"].join("");
    const d = "innmade" + "." + "com";
    setAddr(u + String.fromCharCode(64) + d);
  }, []);

  if (!addr) return <span className={className} style={style}>{children || "…"}</span>;

  if (!revealed) {
    const btnStyle = { background: "none", border: "none", padding: 0, margin: 0, cursor: "pointer", color: "inherit", textAlign: "inherit", font: "inherit", letterSpacing: "inherit", lineHeight: "inherit", ...(style || {}) };
    return (
      <button type="button"
              className={className}
              style={btnStyle}
              onClick={() => setRevealed(true)}
              aria-label="Reveal email address">
        {children || "show email →"}
      </button>
    );
  }

  return <a className={className} style={style} href={"mailto:" + addr} rel="nofollow">{addr}</a>;
}

/* ---------- BRAND ---------- */
function Brand() {
  return (
    <a href="#top" className="brand">
      <div className="brand-mark">i</div>
      <div className="brand-name">innmade<em>.</em></div>
    </a>
  );
}

/* ---------- NAV ---------- */
function Nav({ t, lang, setLang }) {
  return (
    <nav className="nav" id="top">
      <Brand />
      <div className="nav-links">
        <a href="#work" className="nav-link" data-idx="01">{t.nav.work}</a>
        <a href="#services" className="nav-link" data-idx="02">{t.nav.services}</a>
        <a href="#about" className="nav-link" data-idx="03">{t.nav.about}</a>
        <a href="#contact" className="nav-link" data-idx="04">{t.nav.contact}</a>
      </div>
      <div className="nav-right">
        <div className="lang-toggle">
          <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
          <span>/</span>
          <button className={lang === "tr" ? "active" : ""} onClick={() => setLang("tr")}>TR</button>
        </div>
        <a href="#contact" className="cta-btn"><span className="dot" />{t.nav.cta}</a>
      </div>
    </nav>
  );
}

/* ---------- HERO ---------- */
function Hero({ t }) {
  const words = t.hero.rotating;
  const [i, setI] = useState(0);
  const [out, setOut] = useState(false);

  // Dynamic booking slot — always "booking next quarter", slots decrease as current quarter progresses
  const booking = useMemo(() => {
    const now = new Date();
    const y = now.getFullYear();
    const curQ = Math.floor(now.getMonth() / 3) + 1;     // 1..4
    const nextQ = curQ === 4 ? 1 : curQ + 1;
    const nextQY = curQ === 4 ? y + 1 : y;
    const qStart = new Date(y, (curQ - 1) * 3, 1).getTime();
    const qEnd   = new Date(y, curQ * 3, 1).getTime();
    const progress = Math.min(1, Math.max(0, (now.getTime() - qStart) / (qEnd - qStart)));
    const slots = Math.max(2, Math.round(9 - progress * 6));   // 9 → 3 across the quarter
    return { q: nextQ, y: nextQY, slots };
  }, []);

  useEffect(() => {
    const id = setInterval(() => {
      setOut(true);
      setTimeout(() => {
        setI((prev) => (prev + 1) % words.length);
        setOut(false);
      }, 400);
    }, 2800);
    return () => clearInterval(id);
  }, [words.length]);

  return (
    <section className="hero">
      <div>
        <div className="hero-eyebrow mono">
          <span className="pulse" />
          <span>{t.hero.eyebrow}</span>
        </div>
        <h1 className="hero-title display">
          <span className="row">{t.hero.titleStart}</span>
          <span className="row">
            <span className="rotator">
              <span className={"rotator-inner " + (out ? "out" : "")} key={i}>
                {words[i]}
              </span>
            </span>
          </span>
        </h1>
      </div>

      <div className="hero-bottom">
        <p className="hero-sub">{t.hero.sub}</p>
        <div className="hero-meta">
          <div><strong>41.00°N</strong> · 28.97°E</div>
          <div>İstanbul · London</div>
          <div>UTC +03:00</div>
        </div>
        <div className="hero-meta">
          <div><strong>Now booking</strong></div>
          <div>Q{booking.q} {booking.y} engagements</div>
          <div>{booking.slots} of 10 slots open</div>
        </div>
      </div>

      <div className="hero-scroll">
        <span>{t.hero.scroll}</span><span className="arrow" />
      </div>
    </section>
  );
}

/* ---------- MARQUEE ---------- */
function Marquee({ items }) {
  const row = (key) => (
    <div className="marquee-track" key={key} aria-hidden={key > 0 ? "true" : undefined}>
      {items.map((it, i) => <span className="marquee-item" key={i}>{it}</span>)}
    </div>
  );
  return <div className="marquee">{row(0)}{row(1)}</div>;
}

/* ---------- SECTION HEAD ---------- */
function SectionHead({ kicker, title, body }) {
  return (
    <div className="section-head">
      <div className="section-kicker">{kicker}</div>
      <div>
        <h2 className="section-title">{title}</h2>
        {body && <p className="section-body">{body}</p>}
      </div>
    </div>
  );
}

/* ---------- SERVICES ---------- */
function Services({ t }) {
  return (
    <section className="section" id="services">
      <SectionHead kicker={t.services.kicker} title={t.services.title} body={t.services.body} />
      <div className="services-grid">
        {t.services.items.map((s, i) => (
          <article className={"service" + (s.featured ? " featured" : "")} key={i}>
            {s.featured ? (
              <>
                <div className="feat-left">
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                    <span className="service-n">{s.n}</span>
                    <span className="feat-badge">{s.tag}</span>
                  </div>
                  <h3 className="service-name">{s.name}</h3>
                  <p className="service-desc">{s.desc}</p>
                </div>
                <div className="feat-right">
                  <div />
                  <ul className="service-deliverables">
                    {s.deliverables.map((d, j) => <li key={j}>{d}</li>)}
                  </ul>
                </div>
              </>
            ) : (
              <>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                  <span className="service-n">{s.n}</span>
                  <span className="service-tag">{s.tag}</span>
                </div>
                <h3 className="service-name">{s.name}</h3>
                <p className="service-desc">{s.desc}</p>
                <ul className="service-deliverables">
                  {s.deliverables.map((d, j) => <li key={j}>{d}</li>)}
                </ul>
              </>
            )}
          </article>
        ))}
      </div>
    </section>
  );
}

/* ---------- WORK ---------- */
function Work({ t }) {
  return (
    <section className="section" id="work">
      <SectionHead kicker={t.work.kicker} title={t.work.title} body={t.work.body} />
      <div className="work-list">
        {t.work.items.map((w, i) => (
          <a className={"work-row" + (w.featured ? " featured" : "")} key={i} href="#contact">
            {w.featured && <span className="work-star" />}
            <div className="work-year">{String(i + 1).padStart(2, "0")}</div>
            <div className="work-client">{w.client}</div>
            <div className="work-project">{w.project}</div>
            <div className="work-tag">{w.tag}</div>
            <div className="work-arrow">→</div>
          </a>
        ))}
      </div>
      <div style={{ marginTop: 32, display: "flex", justifyContent: "flex-end" }}>
        <a href="#contact" className="mono" style={{ color: "var(--accent)" }}>{t.work.viewAll} ↗</a>
      </div>
    </section>
  );
}

/* ---------- PROCESS + ABOUT ---------- */
function Process({ t }) {
  return (
    <section className="section">
      <SectionHead kicker={t.process.kicker} title={t.process.title} />
      <div className="process-grid">
        {t.process.steps.map((s, i) => (
          <div className="step" key={i}>
            <div className="step-n">{s.n}<sup>step</sup></div>
            <div>
              <div className="step-name">{s.name}</div>
              <p className="step-body">{s.body}</p>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function About({ t }) {
  return (
    <section className="section" id="about">
      <SectionHead kicker={t.about.kicker} title={t.about.title} />
      <div className="about-wrap">
        <div className="about-body">
          <p>{t.about.body}</p>
          <p>— Founders previously at Allianz, Trendyol, Stripe, and Anthropic partners. Recognized by FWA, Awwwards, and Brand New.</p>
        </div>
        <div className="stats">
          {t.about.stats.map((s, i) => (
            <div className="stat" key={i}>
              <div className="stat-k">{s.k}</div>
              <div className="stat-v">{s.v}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- CONTACT ---------- */
function Contact({ t }) {
  const [state, setState] = useState("idle"); // idle | sending | sent | error
  const [ts] = useState(() => String(Date.now())); // time-trap stamp

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (state === "sending" || state === "sent") return;
    const form = e.currentTarget;
    const data = new FormData(form);
    setState("sending");
    try {
      const res = await fetch("/submit.php", { method: "POST", body: data });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.ok) throw new Error(json.error || "send_failed");
      setState("sent");
      form.reset();
    } catch (err) {
      setState("error");
    }
  };

  const sending = state === "sending";
  const sent = state === "sent";

  return (
    <section className="section" id="contact">
      <SectionHead kicker={t.contact.kicker} title={t.contact.title} body={t.contact.body} />
      <div className="contact-wrap">
        <form className="contact-form" onSubmit={handleSubmit} noValidate={false}>
          <div className="field">
            <label>{t.contact.fields.name}</label>
            <input required name="name" placeholder="Ayşe Demir" />
          </div>
          <div className="field">
            <label>{t.contact.fields.company}</label>
            <input required name="company" placeholder="Acme Corp." />
          </div>
          <div className="field">
            <label>{t.contact.fields.email}</label>
            <input required type="email" name="email" placeholder="ayse@acme.com" />
          </div>
          <div className="field">
            <label>{t.contact.fields.budget}</label>
            <select name="budget" defaultValue="">
              <option value="" disabled>—</option>
              {t.contact.budgets.map((b, i) => <option key={i}>{b}</option>)}
            </select>
          </div>
          <div className="field">
            <label>{t.contact.fields.message}</label>
            <textarea required name="message" rows={3} placeholder="…" />
          </div>
          {/* honeypot — humans never fill this */}
          <div aria-hidden="true" style={{ position: "absolute", left: "-9999px", top: "auto", width: 1, height: 1, overflow: "hidden" }}>
            <label>Leave this field empty<input type="text" name="_gotcha" tabIndex="-1" autoComplete="off" /></label>
          </div>
          {/* time-trap: rendered-at timestamp */}
          <input type="hidden" name="_ts" value={ts} />
          <div className="submit-row">
            <button className="big-btn" type="submit" disabled={sending || sent}>
              {sent ? "✓ " + (t.contact.sent.replace(/^✓\s*/, "").split(" — ")[0]) : sending ? t.contact.sending : t.contact.submit}
              <span className="arrow-ico">→</span>
            </button>
            <span className="mono" style={{ color: "var(--fg-mute)" }}>avg. reply · 42h</span>
          </div>
          {state === "sent" && <p className="mono" style={{ color: "var(--accent)", fontSize: 12, marginTop: 12 }}>{t.contact.sent}</p>}
          {state === "error" && <p className="mono" style={{ color: "#ff6b6b", fontSize: 12, marginTop: 12 }}>{t.contact.error}</p>}
        </form>
        <aside className="contact-aside">
          <div className="mono" style={{ marginBottom: 16 }}>{t.contact.direct}</div>
          <EmailLink className="huge-mail display italic">{t.contact.reveal}</EmailLink>
          <div className="contact-info">
            <div><strong>{t.contact.london}</strong><br/>{t.contact.londonAddr.split("\n").map((l, i) => <span key={i}>{l}<br/></span>)}</div>
            <div style={{ marginTop: 20 }}><strong>{t.contact.kayseri}</strong><br/>{t.contact.kayseriAddr.split("\n").map((l, i) => <span key={i}>{l}<br/></span>)}</div>
            <div style={{ marginTop: 20 }}>
              <strong>{t.contact.phones}</strong><br/>
              <span style={{ userSelect: "all" }}>+90 507 278 02 58</span><br/>
              <span style={{ userSelect: "all" }}>+44 7848 500 672</span>
            </div>
          </div>
        </aside>
      </div>
    </section>
  );
}

/* ---------- FOOTER ---------- */
function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="footer-top">
        <div className="footer-tag">{t.footer.tag}</div>
        {[t.footer.col1, t.footer.col2, t.footer.col3].map((c, i) => (
          <div className="footer-col" key={i}>
            <h5>{c.h}</h5>
            <ul>{c.items.map((it, j) => (
              <li key={j}>{it === "__EMAIL__" ? <EmailLink>{t.contact.reveal}</EmailLink> : it}</li>
            ))}</ul>
          </div>
        ))}
      </div>
      <div className="footer-big">Innmade<span className="italic" style={{ color: "var(--accent)" }}>.</span></div>
      <div className="footer-bottom">
        <span>{t.footer.legal}</span>
        <span>MADE IN LONDON WITH <span style={{ color: "var(--accent)" }}>♥</span> · 51.51°N 0.13°W</span>
      </div>
    </footer>
  );
}

/* ---------- TWEAKS PANEL ---------- */
function TweaksPanel({ t, tweaks, setTweaks, open, onClose }) {
  const setKey = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*'); } catch(e){}
  };
  return (
    <div className={"tweaks-panel " + (open ? "open" : "")}>
      <div className="tweaks-head">
        <h4>{t.tweaks.title}</h4>
        <button onClick={onClose} style={{ color: "var(--fg-dim)" }}>✕</button>
      </div>

      <div className="tweak-row">
        <label>{t.tweaks.accent}</label>
        <div className="swatches">
          {ACCENTS.map(a => (
            <div key={a.hex}
                 className={"swatch " + (tweaks.accent === a.hex ? "active" : "")}
                 style={{ background: a.hex }}
                 title={a.name}
                 onClick={() => setKey("accent", a.hex)} />
          ))}
        </div>
      </div>

      <div className="tweak-row">
        <label>{t.tweaks.type}</label>
        <div className="seg">
          {[["editorial","Editorial"],["neo","Neo"],["grotesk","Grotesk"]].map(([v, l]) => (
            <button key={v} className={tweaks.type === v ? "active" : ""} onClick={() => setKey("type", v)}>{l}</button>
          ))}
        </div>
      </div>

      <div className="tweak-row">
        <label>{t.tweaks.density}</label>
        <div className="seg">
          {[["tight","Tight"],["default","Default"],["comfortable","Roomy"]].map(([v, l]) => (
            <button key={v} className={tweaks.density === v ? "active" : ""} onClick={() => setKey("density", v)}>{l}</button>
          ))}
        </div>
      </div>

      <div className="tweak-row">
        <div className={"toggle " + (tweaks.grain ? "on" : "")} onClick={() => setKey("grain", !tweaks.grain)}>
          <label style={{ margin: 0 }}>{t.tweaks.grain}</label>
          <div className="sw" />
        </div>
      </div>

      <div className="tweak-row" style={{ marginBottom: 0 }}>
        <div className={"toggle " + (tweaks.cursor ? "on" : "")} onClick={() => setKey("cursor", !tweaks.cursor)}>
          <label style={{ margin: 0 }}>{t.tweaks.cursor}</label>
          <div className="sw" />
        </div>
      </div>
    </div>
  );
}

/* ---------- CUSTOM CURSOR ---------- */
function CustomCursor({ on }) {
  const dotRef = useRef(null);
  useEffect(() => {
    if (!on) return;
    const dot = dotRef.current;
    const move = (e) => { if (dot) { dot.style.left = e.clientX + "px"; dot.style.top = e.clientY + "px"; } };
    const over = (e) => { if (dot && e.target.closest("a,button,.swatch,.service,.work-row,.field")) dot.classList.add("hover"); };
    const out = (e) => { if (dot && !e.target.closest("a,button,.swatch,.service,.work-row,.field")) dot.classList.remove("hover"); };
    window.addEventListener("mousemove", move);
    document.addEventListener("mouseover", over);
    document.addEventListener("mouseout", out);
    return () => {
      window.removeEventListener("mousemove", move);
      document.removeEventListener("mouseover", over);
      document.removeEventListener("mouseout", out);
    };
  }, [on]);
  if (!on) return null;
  return <div className="cur-dot" ref={dotRef} />;
}

/* ---------- APP ---------- */
function App() {
  const [lang, setLang] = useState(() => localStorage.getItem("innmade-lang") || "en");
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const t = window.INNMADE_I18N[lang];

  useEffect(() => { localStorage.setItem("innmade-lang", lang); document.documentElement.lang = lang; }, [lang]);

  // tweak wiring
  useEffect(() => {
    document.documentElement.style.setProperty("--accent", tweaks.accent);
    document.documentElement.setAttribute("data-type", tweaks.type);
    document.documentElement.setAttribute("data-density", tweaks.density);
    document.body.classList.toggle("grain", !!tweaks.grain);
    document.body.classList.toggle("cur-on", !!tweaks.cursor);
  }, [tweaks]);

  // edit-mode host protocol
  useEffect(() => {
    const handler = (e) => {
      if (!e.data) return;
      if (e.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", handler);
    try { window.parent.postMessage({ type: "__edit_mode_available" }, "*"); } catch(e){}
    return () => window.removeEventListener("message", handler);
  }, []);

  return (
    <>
      <Nav t={t} lang={lang} setLang={setLang} />
      <Hero t={t} />
      <Marquee items={t.marquee} />
      <Work t={t} />
      <Services t={t} />
      <Process t={t} />
      <About t={t} />
      <Contact t={t} />
      <Footer t={t} />
      <TweaksPanel t={t} tweaks={tweaks} setTweaks={setTweaks} open={tweaksOpen} onClose={() => setTweaksOpen(false)} />
      <CustomCursor on={tweaks.cursor} />
    </>
  );
}

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