// =============================================================
// SHARED CHROME — Westenstar hi-fi multi-page site
// Header (real nav links + active state), Footer, Request modal,
// reusable inner-page hero banner, language hook, hfT helper.
// Loaded on every page BEFORE the page-specific component.
// =============================================================

const hfT = (lang, key) => window.T(lang, key);

// =============================================================
// FORM SUBMISSION — Web3Forms (https://web3forms.com)
// Paste your access key below. Requests are emailed to the
// address the key was issued for.
// =============================================================
const WS_WEB3FORMS_KEY = "76953a24-1ee2-4b10-ad36-01b136ad79f2";

async function wsSubmitForm(formEl, subject, extra) {
  const data = Object.fromEntries(new FormData(formEl).entries());
  Object.assign(data, extra || {});
  data.access_key = WS_WEB3FORMS_KEY;
  data.subject = subject;
  data.from_name = "Westenstar Website";
  const res = await fetch("https://api.web3forms.com/submit", {
    method: "POST",
    headers: { "Content-Type": "application/json", "Accept": "application/json" },
    body: JSON.stringify(data),
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok || !json.success) throw new Error(json.message || "Submit failed");
}

// Site-wide navigation — links point at real pages.
const HF_NAV = [
  { key: "hi_nav_models",  href: "tractors.html", id: "tractors" },
  { key: "hi_nav_parts",   href: "parts.html",    id: "parts" },
  { key: "hi_nav_service", href: "service.html",  id: "service" },
  { key: "hi_nav_regions", href: "regions.html",  id: "regions" },
  { key: "hi_nav_contact", href: "contact.html",  id: "contact" },
];

// Persisted EN/TR language, shared across page navigations.
function useLang() {
  const [lang, setLangState] = React.useState(() => {
    try { return localStorage.getItem("ws_lang") || "en"; } catch (e) { return "en"; }
  });
  const setLang = React.useCallback((v) => {
    try { localStorage.setItem("ws_lang", v); } catch (e) {}
    setLangState(v);
    document.documentElement.setAttribute("lang", v);
  }, []);
  React.useEffect(() => { document.documentElement.setAttribute("lang", lang); }, [lang]);
  return [lang, setLang];
}

// =============================================================
// REQUEST-DETAILS MODAL (shared by model cards & CTAs)
// =============================================================
function HfRequestButton({ lang, model, className = "hf-btn primary", label }) {
  const [open, setOpen] = React.useState(false);
  return (
    <React.Fragment>
      <button className={className} onClick={() => setOpen(true)}>
        {label || hfT(lang, "req_cta")} <span className="arrow"></span>
      </button>
      {open && <HfRequestModal lang={lang} model={model} onClose={() => setOpen(false)} />}
    </React.Fragment>
  );
}

const HfModalField = ({ lang, k, name, full, area }) =>
  <label className="hf-field" style={full ? { gridColumn: "1 / -1" } : null}>
    <span>{hfT(lang, k)}</span>
    {area ? <textarea name={name} rows={3}></textarea> : <input type="text" name={name} />}
  </label>;

function HfRequestModal({ lang, model, onClose }) {
  const [status, setStatus] = React.useState("idle"); // idle | sending | error | sent
  const sent = status === "sent";
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, []);

  const onSubmit = (e) => {
    e.preventDefault();
    const formEl = e.target;
    setStatus("sending");
    wsSubmitForm(formEl, "Request details — " + (model || "General"))
      .then(() => setStatus("sent"))
      .catch(() => setStatus("error"));
  };

  return ReactDOM.createPortal(
    <div className="hf-modal-overlay" onClick={onClose}>
      <div className="hf hf-typeC hf-modal" role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()}>
        <button className="hf-modal-x" onClick={onClose} aria-label="Close">✕</button>
        {sent ?
          <div className="hf-modal-sent">
            <div className="hf-eyebrow hf-eyebrow-red">{hfT(lang, "req_sent_title")}</div>
            <h3 className="hf-h3">{hfT(lang, "req_sent_title")}</h3>
            <p className="hf-body">{hfT(lang, "req_sent")}</p>
            <button className="hf-btn primary" onClick={onClose}>OK</button>
          </div> :
          <React.Fragment>
            <div className="hf-eyebrow hf-eyebrow-red">{hfT(lang, "req_title")}</div>
            <h3 className="hf-h3" style={{ marginTop: 6 }}>{model || hfT(lang, "req_title")}</h3>
            <p className="hf-body hf-modal-sub">{hfT(lang, "req_sub")}</p>
            <form onSubmit={onSubmit}>
              {model &&
                <label className="hf-field" style={{ marginBottom: 14, display: "block" }}>
                  <span>{hfT(lang, "req_model")}</span>
                  <input type="text" name="model" value={model} readOnly />
                </label>}
              <div className="hf-modal-grid">
                <HfModalField lang={lang} k="req_name" name="name" /><HfModalField lang={lang} k="req_company" name="company" />
                <HfModalField lang={lang} k="req_email" name="email" /><HfModalField lang={lang} k="req_phone" name="phone" />
                <HfModalField lang={lang} k="req_country" name="country" />
                <HfModalField lang={lang} k="req_message" name="message" full area />
              </div>
              {status === "error" &&
                <p className="hf-small" style={{ color: "var(--hf-red)", marginTop: 12 }}>{hfT(lang, "pg_form_error")}</p>}
              <div className="hf-modal-actions">
                <button type="button" className="hf-btn" onClick={onClose}>{hfT(lang, "req_cancel")}</button>
                <button type="submit" className="hf-btn primary" disabled={status === "sending"}>
                  {status === "sending" ? hfT(lang, "pg_form_sending") : hfT(lang, "req_submit")} <span className="arrow"></span>
                </button>
              </div>
            </form>
          </React.Fragment>}
      </div>
    </div>,
    document.body);
}

// =============================================================
// HEADER
// =============================================================
function HfHeader({ lang, setLang, active }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);
  return (
    <header className="hf-header">
      <a className="hf-logo" href="index.html">
        <span className="hf-logo-mark"></span>
        <span>WESTENSTAR</span>
      </a>
      <nav className="hf-nav">
        {HF_NAV.map((n) =>
          <a key={n.id} href={n.href} className={active === n.id ? "active" : ""}>{hfT(lang, n.key)}</a>
        )}
      </nav>
      <div className="hf-header-right">
        <a className="hf-btn primary sm" href="contact.html" style={{ minWidth: 140 }}>
          {hfT(lang, "hi_cta_quote")} <span className="arrow"></span>
        </a>
        <div className="hf-lang">
          <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
          <button className={lang === "tr" ? "on" : ""} onClick={() => setLang("tr")}>TR</button>
        </div>
        <button className={"hf-burger" + (menuOpen ? " open" : "")} aria-label="Menu"
          aria-expanded={menuOpen} onClick={() => setMenuOpen((v) => !v)}>
          <span></span><span></span><span></span>
        </button>
      </div>
      {menuOpen &&
        <div className="hf-mobile-menu">
          {HF_NAV.map((n) =>
            <a key={n.id} href={n.href} className={"hf-mm-link" + (active === n.id ? " active" : "")}>{hfT(lang, n.key)}</a>
          )}
          <a className="hf-btn primary" href="contact.html">{hfT(lang, "hi_cta_quote")} <span className="arrow"></span></a>
        </div>}
    </header>);
}

// =============================================================
// INNER-PAGE HERO BANNER (shared across all sub-pages)
// =============================================================
function HfPageHero({ lang, crumbKey, eyebrowKey, titleKey, subKey, counter, photoId, placeholder }) {
  return (
    <section className="hf-pagehero">
      {photoId &&
        <div className="hf-pagehero-photo">
          <image-slot id={photoId} shape="rect" placeholder={placeholder}
            style={{ width: "100%", height: "100%", display: "block" }}></image-slot>
        </div>}
      <div className="hf-pagehero-inner">
        <div className="hf-pagehero-top">
          <span className="hf-eyebrow on-dark hf-mono">
            <a href="index.html" style={{ color: "inherit", textDecoration: "none" }}>{hfT(lang, "nav_home")}</a>
            <span style={{ opacity: 0.4, margin: "0 8px" }}>/</span>
            <span style={{ color: "#fff" }}>{hfT(lang, crumbKey)}</span>
          </span>
          {counter && <span className="hf-eyebrow on-dark hf-mono">{counter}</span>}
        </div>
        <div className="hf-pagehero-bottom">
          <div className="hf-eyebrow hf-eyebrow-red">{hfT(lang, eyebrowKey)}</div>
          <h1 className="hf-h1 hf-pagehero-title">{hfT(lang, titleKey)}</h1>
          {subKey && <p className="hf-pagehero-sub">{hfT(lang, subKey)}</p>}
        </div>
      </div>
    </section>);
}

// =============================================================
// CTA BAND (shared — closes most pages)
// =============================================================
function HfCtaBand({ lang }) {
  return (
    <section className="hf-cta-band">
      <div className="left">
        <div className="hf-eyebrow" style={{ color: "rgba(255,255,255,0.85)" }}>{hfT(lang, "hi_cta_band_kicker")}</div>
        <h2 className="hf-h2 hf-display">{hfT(lang, "hi_cta_band_title")}</h2>
        <p className="hf-body" style={{ color: "rgba(255,255,255,0.95)", fontSize: 18, maxWidth: 540 }}>
          {hfT(lang, "hi_cta_band_sub")}
        </p>
      </div>
      <div className="right">
        <a className="hf-btn primary lg" href="contact.html">{hfT(lang, "hi_cta_band_primary")} <span className="arrow"></span></a>
        <a className="hf-btn lg" href="contact.html">{hfT(lang, "hi_cta_band_secondary")}</a>
        <div className="hf-mono" style={{ fontSize: 13, marginTop: 12, color: "rgba(255,255,255,0.85)" }}>
          <a href={"tel:" + hfT(lang, "hi_cta_call").replace(/[^+\d]/g, "")} style={{ color: "inherit", textDecoration: "none" }}>{hfT(lang, "hi_cta_call")}</a>
        </div>
      </div>
    </section>);
}

// =============================================================
// FOOTER
// =============================================================
function HfFooter({ lang }) {
  return (
    <footer className="hf-footer">
      <div className="hf-footer-grid">
        <div className="brand">
          <a className="hf-logo" href="index.html">
            <span className="hf-logo-mark"></span>
            <span>WESTENSTAR</span>
          </a>
          <p style={{ fontSize: 14, maxWidth: 360, margin: 0 }}>{hfT(lang, "hi_foot_tag")}</p>
        </div>
        <div>
          <h4>{hfT(lang, "hi_foot_col_explore")}</h4>
          <ul>
            <li><a href="tractors.html">{hfT(lang, "hi_nav_models")}</a></li>
            <li><a href="parts.html">{hfT(lang, "hi_nav_parts")}</a></li>
            <li><a href="service.html">{hfT(lang, "hi_nav_service")}</a></li>
            <li><a href="regions.html">{hfT(lang, "hi_nav_regions")}</a></li>
          </ul>
        </div>
        <div>
          <h4>{hfT(lang, "hi_foot_col_company")}</h4>
          <ul>
            <li><a href="contact.html">{hfT(lang, "hi_nav_contact")}</a></li>
          </ul>
        </div>
        <div>
          <h4>{hfT(lang, "hi_foot_col_contact")}</h4>
          <ul style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 13 }}>
            <li><a style={{ font: "inherit" }} href="mailto:info@westenstar-zirai.com.tr">info@westenstar-zirai.com.tr</a></li>
            <li><a style={{ font: "inherit" }} href="mailto:parts@westenstar-zirai.com.tr">parts@westenstar-zirai.com.tr</a></li>
            <li><a style={{ font: "inherit" }} href="mailto:logistics@westenstar-zirai.com.tr">logistics@westenstar-zirai.com.tr</a></li>
            <li style={{ marginTop: 8 }}><a style={{ font: "inherit" }} href={"tel:" + hfT(lang, "hi_cta_call").replace(/[^+\d]/g, "")}>{hfT(lang, "hi_cta_call")}</a></li>
            <li style={{ marginTop: 8 }}>{hfT(lang, "hi_foot_addr1")}</li>
          </ul>
        </div>
      </div>
      <div className="hf-footer-bottom">
        <span>{hfT(lang, "hi_foot_legal")}</span>
      </div>
    </footer>);
}

// Page shell — locks the whole site to font variant C (Oswald + IBM Plex Sans).
function HfPage({ children }) {
  return <div className="hf hf-typeC">{children}</div>;
}

Object.assign(window, {
  hfT, HF_NAV, useLang, wsSubmitForm,
  HfHeader, HfFooter, HfCtaBand, HfPageHero, HfPage,
  HfRequestButton, HfRequestModal,
});
