/* global React */
const { useState, useEffect, useContext, createContext } = React;

// Language context
const LangContext = createContext('EN');
const useLang = () => useContext(LangContext);
const useT = (section) => {
  const lang = useLang();
  const t = window.NH_TRANSLATIONS[lang] || window.NH_TRANSLATIONS['EN'];
  return section ? t[section] : t;
};
Object.assign(window, { LangContext, useLang, useT });

const Icon = ({ name, size = 18 }) => {
  const c = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
  const p = {
    leaf: <><path d="M20 4C12 4 4 8 4 18c0 1 0 2 1 2 8 0 15-7 15-15 0-1 0-1 0-1Z"/><path d="M4 20c4-6 9-9 16-12"/></>,
    compass: <><circle cx="12" cy="12" r="9"/><path d="m9 15 2-6 6-2-2 6-6 2Z"/></>,
    bolt: <path d="m13 2-9 12h7l-1 8 9-12h-7l1-8Z"/>,
    ruler: <><path d="M3 17 17 3l4 4L7 21l-4-4Z"/><path d="m7 13 2 2M11 9l2 2M15 5l2 2"/></>,
    shield: <><path d="M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6l-8-3Z"/><path d="m9 12 2 2 4-4"/></>,
    tag: <><path d="M3 12V3h9l9 9-9 9-9-9Z"/><circle cx="8" cy="8" r="1.5"/></>,
    arrow: <path d="M5 12h14M13 6l6 6-6 6"/>,
    crown: <path d="M3 18h18M5 7l3 5 4-7 4 7 3-5v11H5V7Z"/>,
    check: <path d="m4 12 5 5 11-11"/>,
    close: <path d="M6 6l12 12M18 6 6 18"/>,
    area: <><rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 9h16M9 4v16"/></>,
    levels: <><path d="M3 12h6V6h6v6h6"/><path d="M3 18h18"/></>,
    rooms: <><path d="M4 21V8l8-5 8 5v13"/><path d="M9 21v-7h6v7"/></>,
    menu: <><path d="M4 7h16M4 12h16M4 17h16"/></>,
    fb: <path d="M14 8h3V4h-3a4 4 0 0 0-4 4v2H7v4h3v8h4v-8h3l1-4h-4V8Z"/>,
    ig: <><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r=".5"/></>,
    li: <><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M8 10v8M8 7v.01M12 18v-5a3 3 0 0 1 6 0v5"/></>,
    phone: <><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.89.7 2.78a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.3-1.27a2 2 0 0 1 2.11-.45c.89.33 1.82.57 2.78.7A2 2 0 0 1 22 16.92Z"/></>,
    mail: <><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></>,
    mapPin: <><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0Z"/><circle cx="12" cy="10" r="3"/></>,
    cert: <><circle cx="12" cy="9" r="6"/><path d="M9 14.5V21l3-2 3 2v-6.5"/></>,
    cog: <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3h0a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8v0a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/></>,
    pen: <><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></>,
    truck: <><rect x="1" y="6" width="14" height="11"/><path d="M15 8h4l3 4v5h-7"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="18" r="2"/></>,
    package: <><path d="M3 7v10l9 5 9-5V7l-9-5Z"/><path d="m3 7 9 5 9-5M12 12v10"/></>,
    saw: <><path d="M3 17h12l3-3-3-3H3v6Z"/><path d="M5 11V7M9 11V7M13 11V7M21 17v4"/></>,
    house: <><path d="M4 12 12 4l8 8v8H4v-8Z"/><path d="M9 20v-5h6v5"/></>,
    yt: <><path d="M22 7s-.3-2-1.2-2.8c-1.1-1.2-2.4-1.2-3-1.3C15.6 2.8 12 2.8 12 2.8s-3.6 0-5.8.1c-.6.1-1.9.1-3 1.3C2.3 5 2 7 2 7S1.7 9.3 1.7 11.5v2.1c0 2.2.3 4.4.3 4.4s.3 2 1.2 2.8c1.1 1.2 2.6 1.1 3.3 1.2C8.5 22.2 12 22.2 12 22.2s3.6 0 5.8-.2c.6-.1 1.9-.1 3-1.3.9-.8 1.2-2.8 1.2-2.8s.3-2.2.3-4.4v-2.1C22.3 9.3 22 7 22 7Z"/><path d="m10 15 5-3-5-3v6Z" fill="currentColor" stroke="none"/></>,
  };
  return <svg {...c}>{p[name] || null}</svg>;
};

const Crown = () => <span className="crown"><Icon name="crown" size={14}/></span>;

const Logo = ({ variant = "dark" }) => (
  <a href="Norge House.html" className={"logo logo--" + variant} aria-label="Norge House">
    <img src={(window.__resources && window.__resources.logoSvg) || "logo.svg"} alt="Norge House" className="logo__img"/>
  </a>
);

const Nav = ({ current = "home", lang, setLang }) => {
  const t = window.NH_TRANSLATIONS[lang] || window.NH_TRANSLATIONS['EN'];
  const n = t.nav;
  const links = [
    { id: "home", href: "Norge House.html", label: n.home },
    { id: "about", href: "About Us.html", label: n.about },
    { id: "production", href: "Production.html", label: n.production },
    { id: "projects", href: "Projects.html", label: n.projects },
    { id: "gallery", href: "Gallery.html", label: n.gallery || "Gallery" },
    { id: "b2b", href: "B2B.html", label: n.b2b },
    { id: "contacts", href: "Contacts.html", label: n.contacts },
  ];
  return (
    <header className="nav" id="top">
      <div className="container nav__inner">
        <Logo/>
        <nav className="nav__links">
          {links.map(l => <a key={l.id} href={l.href} className={l.id === current ? "is-active" : ""}>{l.label}</a>)}
        </nav>
        <div className="nav__right">
          <div className="lang">
            {["EN", "LV"].map(l => (
              <button key={l} className={l === lang ? "is-active" : ""} onClick={() => setLang(l)}>{l}</button>
            ))}
          </div>
          <button className="nav__menu-btn"><Icon name="menu" size={16}/> Menu</button>
        </div>
      </div>
    </header>
  );
};

const Footer = ({ lang = "EN" }) => {
  const t = (window.NH_TRANSLATIONS[lang] || window.NH_TRANSLATIONS['EN']).footer;
  return (
  <footer className="footer">
    <div className="footer__bg">
      <img src={(window.__resources && window.__resources.footerHouse) || "img/footer-house.png"} alt="" aria-hidden="true" className="footer__bg-img"/>
      <div className="footer__bg-fade"/>
    </div>
    <div className="footer__glass">
      <div className="container">
        <div className="footer__grid">
          <div className="footer__brand">
            <Logo variant="light"/>
            <p>{t.brand}</p>
            <div className="footer__socials">
              <a href="https://www.instagram.com/norge.house?fbclid=IwY2xjawRpTSJleHRuA2FlbQIxMABicmlkETF6TXBQTHU1MjMyR3BFYTZIc3J0YwZhcHBfaWQQMjIyMDM5MTc4ODIwMDg5MgABHrSuBWdk2dKJuhttdGMhSkLW6usEO1Ir_JO5USPeXI8dVeWFwCcxM2aNerth_aem_qDM-MDsmRB63ZoxaOiy-Pg" aria-label="Instagram" target="_blank" rel="noopener noreferrer"><Icon name="ig" size={16}/></a>
              <a href="https://www.linkedin.com/company/norge-house/posts/?feedView=videos" aria-label="LinkedIn" target="_blank" rel="noopener noreferrer"><Icon name="li" size={16}/></a>
              <a href="https://www.facebook.com/norgehouse/" aria-label="Facebook" target="_blank" rel="noopener noreferrer"><Icon name="fb" size={16}/></a>
              <a href="https://www.youtube.com/channel/UC7KjU6LshV6B0VH5SDqev9g" aria-label="YouTube" target="_blank" rel="noopener noreferrer"><Icon name="yt" size={16}/></a>
            </div>
          </div>
          <div>
            <h4>{t.quickLinks}</h4>
            <ul>
              <li><a href="Norge House.html">{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.home}</a></li>
              <li><a href="About Us.html">{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.about}</a></li>
              <li><a href="Production.html">{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.production}</a></li>
              <li><a href="Projects.html">{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.projects}</a></li>
              <li><a href="Gallery.html">{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.gallery || 'Gallery'}</a></li>
              <li><a href="B2B.html">{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.b2b}</a></li>
              <li><a href="Contacts.html">{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.contacts}</a></li>
            </ul>
          </div>
          <div>
            <h4>{t.contactInfo}</h4>
            <ul>
              <li>Vītoli, Limbažu pagasts</li>
              <li>Limbažu novads, Latvija</li>
              <li><a href="tel:+37125774431">+371 25774431</a></li>
              <li><a href="tel:+4407926691478">+44 07926691478</a></li>
              <li><a href="tel:+31628286862">+31 628286862</a></li>
              <li><a href="mailto:info@norgehouse.com">info@norgehouse.com</a></li>
            </ul>
          </div>
          <div>
            <h4>{t.legal}</h4>
            <ul>
              <li><a href="#">{t.privacy}</a></li>
              <li><a href="#">{t.terms}</a></li>
              <li><a href="#">{t.cookies}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer__bottom">
          <div>{t.copyright}</div>
          <div className="footer__bottom__legal">
            <a href="#">EN</a><a href="#">LV</a>
          </div>
        </div>
      </div>
    </div>
  </footer>
  );
};

const PageHero = ({ eyebrow, title, lead, image, imageAlt, tilted }) => (
  <section className={"pagehero" + (tilted ? " pagehero--tilted" : "")}>
    <div className="container pagehero__inner">
      <div className="pagehero__text">
        {eyebrow && <span className="eyebrow"><Crown/> {eyebrow}</span>}
        <h1>{title}</h1>
        {lead && <p className="pagehero__lead">{lead}</p>}
      </div>
      {image && (
        <div className="pagehero__media">
          <img src={image} alt={imageAlt || ""}/>
        </div>
      )}
    </div>
  </section>
);

const formatPrice = (n) => "€" + n.toLocaleString("en-US");

const ContactForm = ({ projects = [], fields = {}, lang = "EN" }) => {
  const f = fields;
  const tc = ((window.NH_TRANSLATIONS && window.NH_TRANSLATIONS[lang]) || (window.NH_TRANSLATIONS && window.NH_TRANSLATIONS.EN) || {}).common || {};
  const [form, setForm] = useState({ name: "", email: "", phone: "", project: projects[0] || tc.customProject || "Custom project", message: "" });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [sendError, setSendError] = useState("");
  const update = (k, v) => setForm(prev => ({ ...prev, [k]: v }));
  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = tc.errName || "Please enter your name.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) errs.email = tc.errEmail || "Enter a valid email address.";
    if (!form.message.trim() || form.message.trim().length < 10) errs.message = tc.errMessage || "Tell us a little about your project (10+ characters).";
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;
    setSending(true); setSendError("");
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...form, formType: "contact", lang, page: location.pathname }),
      });
      const out = await res.json().catch(() => ({}));
      if (!res.ok || !out.ok) throw new Error(out.error || "Send failed");
      setSent(true);
    } catch (err) {
      const mail = "mailto:info@norgehouse.com?subject=" + encodeURIComponent("Website enquiry — " + form.name) +
        "&body=" + encodeURIComponent(`Name: ${form.name}\nEmail: ${form.email}\nPhone: ${form.phone}\nProject: ${form.project}\n\n${form.message}`);
      setSendError((tc.errSend || "Couldn't send right now.") + " ");
      window.location.href = mail;
    } finally {
      setSending(false);
    }
  };
  if (sent) {
    const successTitle = (tc.formSuccessTitle || "Thank you, {name}.").replace("{name}", form.name.split(" ")[0]);
    return (
      <div className="cta__success">
        <Icon name="check" size={20}/>
        <div>
          <strong style={{ display: "block", marginBottom: 4 }}>{successTitle}</strong>
          {tc.formSuccessBody || "We've received your enquiry and will reply within one business day."}
        </div>
      </div>
    );
  }
  return (
    <form className="cta__form" onSubmit={submit} noValidate>
      <div className="cta__row">
        <div>
          <label>{f.name || "Name"}</label>
          <input type="text" value={form.name} onChange={e => update("name", e.target.value)} placeholder="Anna Lindgren"/>
          {errors.name && <div className="field-error">{errors.name}</div>}
        </div>
        <div>
          <label>{f.email || "Email"}</label>
          <input type="email" value={form.email} onChange={e => update("email", e.target.value)} placeholder="anna@example.com"/>
          {errors.email && <div className="field-error">{errors.email}</div>}
        </div>
      </div>
      <div className="cta__row">
        <div>
          <label>{f.phone || "Phone"}</label>
          <input type="tel" value={form.phone} onChange={e => update("phone", e.target.value)} placeholder="+371 ..."/>
        </div>
        <div>
          <label>{f.project || "Project of interest"}</label>
          <select value={form.project} onChange={e => update("project", e.target.value)}>
            {projects.map(p => <option key={p}>{p}</option>)}
            <option>{tc.customProject || "Custom project"}</option>
          </select>
        </div>
      </div>
      <div>
        <label>{f.message || "Message"}</label>
        <textarea value={form.message} onChange={e => update("message", e.target.value)} placeholder="Plot location, timeline, target floor area…"/>
        {errors.message && <div className="field-error">{errors.message}</div>}
      </div>
      {sendError && <div className="field-error" style={{ marginTop: 4 }}>{sendError}<a href="mailto:info@norgehouse.com" style={{ textDecoration: "underline" }}>info@norgehouse.com</a></div>}
      <button className="btn" type="submit" disabled={sending}>{sending ? (tc.sending || "Sending…") : (f.send || "Get in Touch")} <span className="arrow"><Icon name="arrow" size={14}/></span></button>
    </form>
  );
};

const Divider = ({ children, ctaText = "Get in Touch", ctaHref = "Contacts.html" }) => (
  <section className="divider">
    <div className="container">
      <div className="divider__text">{children || <>Build <em>Your</em> Vision <em>With</em> Us</>}</div>
      <a href={ctaHref} className="btn btn--lg">{ctaText} <span className="arrow"><Icon name="arrow" size={14}/></span></a>
    </div>
  </section>
);

// PageShell — wraps any page with lang state, provides Nav + Footer
const PageShell = ({ current, children }) => {
  const [lang, setLang] = React.useState(() => localStorage.getItem('nh_lang') || 'EN');
  const saveLang = (l) => { localStorage.setItem('nh_lang', l); setLang(l); };
  return (
    <LangContext.Provider value={lang}>
      <Nav current={current} lang={lang} setLang={saveLang}/>
      <main>{typeof children === 'function' ? children(lang) : children}</main>
      <Footer lang={lang}/>
    </LangContext.Provider>
  );
};

Object.assign(window, { Icon, Crown, Logo, Nav, Footer, PageHero, ContactForm, formatPrice, Divider, PageShell, LangContext, useLang, useT });
