/* 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", lang }) => {
  const l = lang || (typeof window !== "undefined" ? localeFromPath() : "EN");
  return (
    <a href={hrefFor("home", l)} 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 [menuOpen, setMenuOpen] = useState(false);
  const links = [
    { id: "home", href: hrefFor("home", lang), label: n.home },
    { id: "about", href: hrefFor("about", lang), label: n.about },
    { id: "production", href: hrefFor("production", lang), label: n.production },
    { id: "projects", href: hrefFor("projects", lang), label: n.projects },
    { id: "gallery", href: hrefFor("gallery", lang), label: n.gallery || "Gallery" },
    { id: "b2b", href: hrefFor("b2b", lang), label: n.b2b },
    { id: "contacts", href: hrefFor("contacts", lang), label: n.contacts },
  ];
  useEffect(() => {
    if (!menuOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => e.key === "Escape" && setMenuOpen(false);
    document.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = prev; document.removeEventListener("keydown", onKey); };
  }, [menuOpen]);
  return (
    <>
      <header className="nav" id="top">
        <div className="container nav__inner">
          <Logo lang={lang}/>
          <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" onClick={() => setMenuOpen(true)} aria-label="Open menu" aria-expanded={menuOpen}><Icon name="menu" size={16}/> Menu</button>
          </div>
        </div>
      </header>
      {menuOpen && (
        <div className="nav__mobile" role="dialog" aria-modal="true" aria-label="Site navigation">
          <div className="nav__mobile__head">
            <Logo lang={lang}/>
            <button className="nav__mobile__close" onClick={() => setMenuOpen(false)} aria-label="Close menu">
              <Icon name="close" size={20}/>
            </button>
          </div>
          <nav className="nav__mobile__links">
            {links.map(l => (
              <a key={l.id} href={l.href} className={l.id === current ? "is-active" : ""} onClick={() => setMenuOpen(false)}>{l.label}</a>
            ))}
          </nav>
          <div className="nav__mobile__lang">
            {["EN", "LV"].map(l => (
              <button key={l} className={l === lang ? "is-active" : ""} onClick={() => { setLang(l); setMenuOpen(false); }}>{l}</button>
            ))}
          </div>
        </div>
      )}
    </>
  );
};

const Footer = ({ lang = "EN", setLang }) => {
  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" lang={lang}/>
            <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={hrefFor("home", lang)}>{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.home}</a></li>
              <li><a href={hrefFor("about", lang)}>{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.about}</a></li>
              <li><a href={hrefFor("production", lang)}>{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.production}</a></li>
              <li><a href={hrefFor("projects", lang)}>{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.projects}</a></li>
              <li><a href={hrefFor("gallery", lang)}>{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.gallery || 'Gallery'}</a></li>
              <li><a href={hrefFor("b2b", lang)}>{(window.NH_TRANSLATIONS[lang]||window.NH_TRANSLATIONS['EN']).nav.b2b}</a></li>
              <li><a href={hrefFor("contacts", lang)}>{(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={hrefFor("privacy", lang)}>{t.privacy}</a></li>
              <li><a href={hrefFor("terms", lang)}>{t.terms}</a></li>
              <li><a href={hrefFor("cookies", lang)}>{t.cookies}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer__bottom">
          <div>{t.copyright}</div>
          <div className="footer__bottom__legal">
            {["EN", "LV"].map(l => (
              <button
                key={l}
                type="button"
                className={"footer__lang-btn" + (l === lang ? " is-active" : "")}
                onClick={() => setLang && setLang(l)}
              >
                {l}
              </button>
            ))}
          </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 Lightbox = ({ project, onClose }) => {
  const [imgIdx, setImgIdx] = useState(0);
  const thumbsRef = React.useRef(null);
  useEffect(() => { setImgIdx(0); }, [project && project.id]);
  useEffect(() => {
    const gallery = project ? (project.gallery && project.gallery.length ? project.gallery : [project.img]) : [];
    const onKey = e => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") setImgIdx(i => Math.max(0, i - 1));
      if (e.key === "ArrowRight") setImgIdx(i => Math.min(gallery.length - 1, i + 1));
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = project ? "hidden" : "";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [project, onClose]);
  // Auto-scroll the active thumbnail into view inside the thumb strip when imgIdx changes.
  useEffect(() => {
    const strip = thumbsRef.current;
    if (!strip) return;
    const active = strip.querySelector('.lightbox__thumb.is-active');
    if (!active) return;
    const stripRect = strip.getBoundingClientRect();
    const activeRect = active.getBoundingClientRect();
    const padding = 12;
    if (activeRect.left < stripRect.left + padding) {
      strip.scrollBy({ left: activeRect.left - stripRect.left - padding, behavior: "smooth" });
    } else if (activeRect.right > stripRect.right - padding) {
      strip.scrollBy({ left: activeRect.right - stripRect.right + padding, behavior: "smooth" });
    }
  }, [imgIdx, project && project.id]);

  const lang = useLang();
  const t = (window.NH_TRANSLATIONS && window.NH_TRANSLATIONS[lang]) || (window.NH_TRANSLATIONS && window.NH_TRANSLATIONS.EN) || {};
  const tp = t.projectsPage || {};

  if (!project) return null;
  const gallery = project.gallery && project.gallery.length ? project.gallery : [project.img];
  const currentImg = gallery[imgIdx];

  return (
    <div className="lightbox is-open" onClick={onClose}>
      <div className="lightbox__inner" onClick={e => e.stopPropagation()}>
        <button className="lightbox__close" onClick={onClose} aria-label="Close"><Icon name="close" size={16}/></button>
        <div className="lightbox__gallery">
          <div className="lightbox__gallery-main">
            {(() => {
              const isPng = currentImg && currentImg.toLowerCase().endsWith('.png');
              const imgStyle = isPng ? { objectFit: 'contain', padding: '16px', boxSizing: 'border-box', background: '#fff' } : {};
              return <img src={currentImg} alt={project.name} key={currentImg} style={imgStyle}/>;
            })()}
            {imgIdx > 0 && (
              <button className="lightbox__nav lightbox__nav--prev" onClick={() => setImgIdx(i => i - 1)} aria-label="Previous image">
                <span className="lb-arrow-flip"><Icon name="arrow" size={17}/></span>
              </button>
            )}
            {imgIdx < gallery.length - 1 && (
              <button className="lightbox__nav lightbox__nav--next" onClick={() => setImgIdx(i => i + 1)} aria-label="Next image">
                <Icon name="arrow" size={17}/>
              </button>
            )}
            {gallery.length > 1 && (
              <div className="lightbox__dots">
                {gallery.map((_, i) => (
                  <button key={i} className={"lightbox__dot" + (i === imgIdx ? " is-active" : "")} onClick={() => setImgIdx(i)} aria-label={"Image " + (i + 1)}></button>
                ))}
              </div>
            )}
          </div>
          {gallery.length > 1 && (
            <div className="lightbox__gallery-controls">
              <button className={"lightbox__gallery-arrow" + (imgIdx === 0 ? " is-disabled" : "")} onClick={() => setImgIdx(i => Math.max(0, i - 1))} aria-label="Previous image">
                <span className="lb-arrow-flip"><Icon name="arrow" size={16}/></span>
              </button>
              <span className="lightbox__gallery-counter">{imgIdx + 1} / {gallery.length}</span>
              <button className={"lightbox__gallery-arrow" + (imgIdx === gallery.length - 1 ? " is-disabled" : "")} onClick={() => setImgIdx(i => Math.min(gallery.length - 1, i + 1))} aria-label="Next image">
                <Icon name="arrow" size={16}/>
              </button>
            </div>
          )}
          {gallery.length > 1 && (
            <div className="lightbox__thumbs" ref={thumbsRef}>
              {gallery.map((img, i) => (
                <button key={i} className={"lightbox__thumb" + (i === imgIdx ? " is-active" : "")} onClick={() => setImgIdx(i)}>
                  <img src={img} alt={"View " + (i + 1)}/>
                </button>
              ))}
            </div>
          )}
        </div>
        <div className="lightbox__body">
          <div className="lightbox__body-top">
            <span className="eyebrow"><Crown/> {(tp.tagLabels && tp.tagLabels[project.tag]) || project.tag}</span>
            <h2 className="lightbox__title">{project.name}</h2>
            {project.description && (<p className="lightbox__desc">{project.description}</p>)}
          </div>
          <div className="lightbox__specs">
            <div className="lightbox__specs-heading">{tp.buildingParams || "Building parameters"}</div>
            {project.specs && project.specs.livingArea && (
              <div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.livingArea || "Living area"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.specs.livingArea}</span></div>
            )}
            <div className="lightbox__spec-row"><span className="lightbox__spec-label">{project.specs && project.specs.livingArea ? (tp.totalArea || "Total area") : (tp.floorArea || "Floor area")}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.area} m²</span></div>
            {project.specs && project.specs.garage && (<div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.garage || "Garage"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.specs.garage}</span></div>)}
            <div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.levels || "Levels"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.levels}</span></div>
            {project.rooms && (<div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.rooms || "Rooms"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.rooms}</span></div>)}
            {project.specs && project.specs.cubicCapacity && (<div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.cubicCapacity || "Cubic capacity"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.specs.cubicCapacity}</span></div>)}
            {project.specs && project.specs.height && (<div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.heightLabel || "Height"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.specs.height}</span></div>)}
            {project.specs && project.specs.roofSlope && (<div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.roofSlope || "Roof slope"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.specs.roofSlope}</span></div>)}
            {project.specs && project.specs.roofArea && (<div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.roofArea || "Roof area"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.specs.roofArea}</span></div>)}
            {project.specs && project.specs.plotSize && (<div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.plotSize || "Min. plot size"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.specs.plotSize}</span></div>)}
            {project.specs && project.specs.uValue && (<div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.uValue || "Wall U-value"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.specs.uValue}</span></div>)}
            {project.specs && project.specs.windows && (<div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.windowsLabel || "Windows"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.specs.windows}</span></div>)}
            {project.specs && project.specs.assembly && (<div className="lightbox__spec-row"><span className="lightbox__spec-label">{tp.assemblyLabel || "Assembly time"}</span><span className="lightbox__spec-dots"></span><span className="lightbox__spec-value">{project.specs.assembly}</span></div>)}
          </div>
          {project.included && project.included.length > 0 && (
            <div className="lightbox__included">
              <div className="lightbox__included-title">{tp.kitIncludes || "Kit includes"}</div>
              <ul className="lightbox__included-list">
                {project.included.map((item, i) => (
                  <li key={i}><Icon name="check" size={12}/><span>{item}</span></li>
                ))}
              </ul>
            </div>
          )}
          <div className="lightbox__footer">
            <a href={hrefFor("contacts", lang)} className="btn btn--lg lightbox__cta" onClick={onClose}>
              {tp.requestQuote || "Request a quote"} <span className="arrow"><Icon name="arrow" size={14}/></span>
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};

const TURNSTILE_SITE_KEY = "0x4AAAAAADN1gyCbitfMBS3f";

const TurnstileWidget = ({ onToken, theme = "light" }) => {
  const ref = React.useRef(null);
  const widgetIdRef = React.useRef(null);
  React.useEffect(() => {
    let cancelled = false;
    let interval = null;
    const render = () => {
      if (cancelled || !ref.current || !window.turnstile) return;
      try {
        widgetIdRef.current = window.turnstile.render(ref.current, {
          sitekey: TURNSTILE_SITE_KEY,
          theme,
          size: "flexible",
          callback: (t) => !cancelled && onToken && onToken(t),
          "expired-callback": () => !cancelled && onToken && onToken(""),
          "error-callback": () => !cancelled && onToken && onToken(""),
        });
      } catch (e) { /* ignore double-render */ }
    };
    if (window.turnstile) { render(); }
    else {
      interval = setInterval(() => {
        if (cancelled) { clearInterval(interval); return; }
        if (window.turnstile) { clearInterval(interval); render(); }
      }, 80);
      setTimeout(() => clearInterval(interval), 15000);
    }
    return () => {
      cancelled = true;
      if (interval) clearInterval(interval);
      if (widgetIdRef.current && window.turnstile) {
        try { window.turnstile.remove(widgetIdRef.current); } catch (e) { /* noop */ }
      }
    };
  }, []);
  return <div ref={ref} className="cta__turnstile"/>;
};

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 [turnstileToken, setTurnstileToken] = 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;
    if (!turnstileToken) {
      setSendError(tc.errCaptcha || "Please complete the verification below.");
      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, turnstileToken }),
      });
      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>}
      <div className="cta__submit-row">
        <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>
        <TurnstileWidget onToken={setTurnstileToken}/>
      </div>
    </form>
  );
};

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

// URL routing — maps each page id to its EN and LV canonical URLs.
// Used by Nav, Footer, language switcher, and all internal CTAs so links stay
// in the visitor's current locale.
const NH_ROUTES = [
  { id: "home",       en: "/",            lv: "/lv/" },
  { id: "about",      en: "/about-us",    lv: "/lv/par-mums" },
  { id: "production", en: "/production",  lv: "/lv/razosana" },
  { id: "projects",   en: "/projects",    lv: "/lv/projekti" },
  { id: "gallery",    en: "/gallery",     lv: "/lv/galerijas" },
  { id: "b2b",        en: "/b2b",         lv: "/lv/partneriem" },
  { id: "news",       en: "/news",        lv: "/lv/jaunumi" },
  { id: "contacts",   en: "/contacts",    lv: "/lv/kontakti" },
  { id: "privacy",    en: "/privacy",     lv: "/lv/privatuma-politika" },
  { id: "terms",      en: "/terms",       lv: "/lv/lietosanas-noteikumi" },
  { id: "cookies",    en: "/cookies",     lv: "/lv/sikdatnes" },
];

// Detect locale from current URL pathname. /lv/* → LV, everything else → EN.
const localeFromPath = () => {
  const p = (typeof window !== "undefined" && window.location && window.location.pathname) || "/";
  return p === "/lv" || p === "/lv/" || p.startsWith("/lv/") ? "LV" : "EN";
};

// Resolve the URL for a page id in a given language.
const hrefFor = (id, lang) => {
  const r = NH_ROUTES.find(x => x.id === id) || NH_ROUTES[0];
  return lang === "LV" ? r.lv : r.en;
};

// Detect which page we're currently on, by URL pathname.
const currentPageId = () => {
  const p = (typeof window !== "undefined" && window.location && window.location.pathname) || "/";
  const decoded = decodeURIComponent(p).replace(/\/$/, "") || "/";
  for (const r of NH_ROUTES) {
    const enNorm = r.en.replace(/\/$/, "") || "/";
    const lvNorm = r.lv.replace(/\/$/, "") || "/";
    if (decoded === enNorm || decoded === lvNorm) return r.id;
  }
  return null;
};

// PageShell — wraps any page with lang state (from URL), provides Nav + Footer
const PageShell = ({ current, children }) => {
  const initialLang = localeFromPath();
  const [lang, setLang] = React.useState(initialLang);
  // saveLang: navigate to the equivalent URL in the new language (preserves SEO).
  const saveLang = (l) => {
    try { localStorage.setItem('nh_lang', l); } catch (e) { /* private mode */ }
    if (l === lang) return;
    const id = current || currentPageId() || "home";
    const target = hrefFor(id, l);
    if (target && target !== window.location.pathname) {
      window.location.href = target;
    } else {
      setLang(l);
    }
  };
  // Keep <html lang="..."> in sync with the active locale (helps screen readers + SEO)
  React.useEffect(() => {
    try { document.documentElement.lang = lang === "LV" ? "lv" : "en"; } catch (e) { /* noop */ }
  }, [lang]);
  // Inject hreflang + canonical tags so search engines know about the EN/LV pair
  React.useEffect(() => {
    try {
      const origin = "https://norgehouse.com";
      const id = current || currentPageId() || "home";
      const en = origin + encodeURI(hrefFor(id, "EN")).replace(/%2F/g, "/");
      const lv = origin + encodeURI(hrefFor(id, "LV")).replace(/%2F/g, "/");
      const canonical = lang === "LV" ? lv : en;
      // Remove any previously-injected tags
      Array.from(document.querySelectorAll('link[data-nh="hreflang"], link[data-nh="canonical"]')).forEach(el => el.remove());
      const make = (rel, href, hreflang) => {
        const l = document.createElement("link");
        l.rel = rel;
        l.href = href;
        if (hreflang) l.hreflang = hreflang;
        l.setAttribute("data-nh", rel === "canonical" ? "canonical" : "hreflang");
        document.head.appendChild(l);
      };
      make("canonical", canonical);
      make("alternate", en, "en");
      make("alternate", lv, "lv");
      make("alternate", en, "x-default");
    } catch (e) { /* noop */ }
  }, [lang, current]);
  return (
    <LangContext.Provider value={lang}>
      <Nav current={current} lang={lang} setLang={saveLang}/>
      <main>{typeof children === 'function' ? children(lang) : children}</main>
      <Footer lang={lang} setLang={saveLang}/>
    </LangContext.Provider>
  );
};

Object.assign(window, { Icon, Crown, Logo, Nav, Footer, PageHero, ContactForm, formatPrice, Divider, PageShell, LangContext, useLang, useT, TurnstileWidget, Lightbox, NH_ROUTES, hrefFor, localeFromPath, currentPageId });
