// EUROMOBILJE — Reusable components

const { useState, useEffect, useRef, useMemo } = React;

// Small icon set — line icons, simple shapes only
const Icon = ({ name, size = 16 }) => {
  const props = {
    width: size, height: size, viewBox: "0 0 24 24", fill: "none",
    stroke: "currentColor", strokeWidth: 1.4, strokeLinecap: "round", strokeLinejoin: "round",
  };
  switch (name) {
    case "arrow-right":
      return (<svg {...props}><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg>);
    case "arrow-up-right":
      return (<svg {...props}><path d="M7 17L17 7"/><path d="M8 7h9v9"/></svg>);
    case "menu":
      return (<svg {...props}><path d="M4 7h16"/><path d="M4 12h16"/><path d="M4 17h16"/></svg>);
    case "close":
      return (<svg {...props}><path d="M6 6l12 12"/><path d="M18 6l-12 12"/></svg>);
    case "phone":
      return (<svg {...props}><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-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>);
    case "mail":
      return (<svg {...props}><rect x="3" y="5" width="18" height="14" rx="1"/><path d="M3 7l9 6 9-6"/></svg>);
    case "pin":
      return (<svg {...props}><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"/></svg>);
    case "check":
      return (<svg {...props}><path d="M20 6L9 17l-5-5"/></svg>);
    case "hotel":
      return (<svg {...props}><path d="M3 21V8l9-5 9 5v13"/><path d="M9 21v-6h6v6"/><path d="M9 12h.01"/><path d="M15 12h.01"/></svg>);
    case "restaurant":
      return (<svg {...props}><path d="M3 3v8a3 3 0 0 0 6 0V3"/><path d="M6 11v10"/><path d="M16 3v18"/><path d="M16 9c0-3 1-6 4-6v18"/></svg>);
    case "mall":
      return (<svg {...props}><rect x="3" y="6" width="18" height="14"/><path d="M3 10h18"/><path d="M8 6V4"/><path d="M16 6V4"/></svg>);
    case "office":
      return (<svg {...props}><rect x="4" y="3" width="16" height="18"/><path d="M9 7h.01"/><path d="M15 7h.01"/><path d="M9 11h.01"/><path d="M15 11h.01"/><path d="M9 15h.01"/><path d="M15 15h.01"/></svg>);
    default: return null;
  }
};

// Curated Unsplash photo IDs per visual category. Multiple IDs per tag
// give variety across products that share the same tag. Each ID is the
// part after "photo-" in the CDN URL.
const TAG_PHOTOS = {
  workshop:   ["1426927308491-6380b6a9936f", "1497218770144-3fea6dbc33fe"],
  lounge:     ["1583847268964-b28dc8f51f92", "1631679706909-1844bbd07221"],
  dining:     ["1616486886892-ff366aa67ba4", "1604578762246-41134e37f9cc"],
  bedroom:    ["1615874959474-d609969a20ed", "1505693416388-ac5ce068fe85"],
  kitchen:    ["1556911220-bff31c812dba", "1565538810643-b5bdb714032a"],
  office:     ["1610374792793-f016b77ca51a", "1497366811353-6870744d04b2"],
  lobby:      ["1573052905904-34ad8c27f0cc", "1495365200479-c4ed1d35e1aa"],
  library:    ["1568667256531-7d5ac92eaa7a", "1532012197267-da84d127e765"],
  sofa:       ["1555041469-a586c61ea9bc", "1493663284031-b7e3aefcae8e"],
  armchair:   ["1580480055273-228ff5388ef8", "1586023492125-27b2c045efd7"],
  table:      ["1581428982868-e410dd047a90", "1542372147193-a7aca54189cd"],
  chair:      ["1506439773649-6e0eb8cfb237", "1598300042247-d088f8ab3a91"],
  bed:        ["1505693416388-ac5ce068fe85", "1522771739844-6a9f6d5f14af"],
  wardrobe:   ["1631048499455-4f9e26f23b9f", "1609709295948-17d77cb2a69b"],
  desk:       ["1499951360447-b19be8fe80f5", "1535957998253-26ae1ef29506"],
  bookcase:   ["1568842782152-db6cc2a2264e", "1615884241431-d07c87e30ab2"],
  console:    ["1609879938030-31acdeded104", "1560448076-957f79776e95"],
  bench:      ["1561724677-a93ece9f1e1f", "1588018759902-6a69207bb499"],
  daybed:     ["1583847268964-b28dc8f51f92"],
  sideboard:  ["1718049719548-723e863fbccf", "1593443746658-bfaece08b4f8"],
  buffet:     ["1743838244119-3d2be1fb8ac0", "1758977405163-f2595de08dfe"],
  credenza:   ["1718049719548-723e863fbccf", "1459801786602-b19123ae25a8"],
  dresser:    ["1591129841117-3adfd313e34f", "1579283111509-855c7eea1c49"],
  vanity:     ["1623922939942-38c39476cbff", "1712214741533-3dd5b8013ca7"],
  headboard:  ["1618941027499-790b098c04b3", "1572556806947-e468f74f8899"],
  nightstand: ["1649194271420-b2ff52418a62", "1637947148874-5549202425f3"],
  island:     ["1556911220-bff31c812dba", "1600489000022-c2086d79f9d4"],
  cabinet:    ["1602028915047-37269d1a73f7", "1601760561441-16420502c7e0"],
  pantry:     ["1591208824584-1de04f9b0664", "1601465788455-63a148629b68"],
  bar:        ["1707296415986-a2a3649350da", "1618236444940-e2100b2726e7"],
  hood:       ["1714358013380-b75b16127007", "1714624107079-9925651c396a"],
  reception:  ["1682579770385-4d725efef9c7", "1470290378698-263fa7ca60ab"],
};

// Some labels mention a noun that maps to one of the photo categories above.
// Order matters: most-specific terms first, so "lounge armchair" → "armchair"
// (not "lounge"), but "kitchen island" → "kitchen" (rooms beat single pieces).
const TAG_ORDER = [
  "headboard","sideboard","credenza","buffet","dresser","vanity",
  "wardrobe","bookcase","bookshelf","armchair","daybed","nightstand",
  "bedside","console","cabinetry",
  "bedroom","kitchen","dining","office","lounge","library","lobby",
  "sofa","bench","desk","cabinet","island","pantry","shelving",
  "table","chair","bed","shelf","reception","hood","bar",
  "hotel","restaurant","workshop","cabinetmaker","carpenter",
];
const ALIASES = {
  bookshelf:    "bookcase",
  shelf:        "bookcase",
  shelving:     "bookcase",
  bedside:      "nightstand",
  cabinetry:    "cabinet",
  hotel:        "lobby",
  restaurant:   "dining",
  cabinetmaker: "workshop",
  carpenter:    "workshop",
};
const tagFor = (label) => {
  const words = label.toLowerCase().split(/[^a-z]+/).filter(Boolean).map((w) => w.replace(/s$/, ""));
  const raw = TAG_ORDER.find((k) => words.includes(k)) || "lounge";
  return ALIASES[raw] || raw;
};
const hash = (s) => {
  let h = 0;
  for (let i = 0; i < s.length; i++) h = ((h << 5) - h + s.charCodeAt(i)) | 0;
  return Math.abs(h);
};

const Placeholder = ({ label, dark = false, ratio, src: overrideSrc }) => {
  const [failed, setFailed] = useState(false);
  const tag = tagFor(label);
  const seed = hash(label);
  const photos = TAG_PHOTOS[tag] || TAG_PHOTOS.lounge;
  const id = photos[seed % photos.length];
  const src = overrideSrc || `https://images.unsplash.com/photo-${id}?w=800&q=80&auto=format&fit=crop`;
  return (
    <div className={`placeholder${dark ? " placeholder--dark" : ""}`} style={ratio ? { aspectRatio: ratio } : undefined}>
      {!failed && (
        <img
          src={src}
          alt={label}
          className="placeholder__img"
          loading="lazy"
          onError={() => setFailed(true)}
        />
      )}
      {failed && <div className="placeholder__label">[ {label} ]</div>}
    </div>
  );
};

const LangToggle = ({ className = "" }) => {
  const lang = window.useLang();
  const set = (l) => () => window.setLang(l);
  return (
    <div className={`lang-toggle ${className}`} role="group" aria-label="Language">
      <button
        type="button"
        className={`lang-toggle__btn${lang === "en" ? " is-active" : ""}`}
        onClick={set("en")}
        aria-pressed={lang === "en"}
      >EN</button>
      <span className="lang-toggle__sep" aria-hidden="true">/</span>
      <button
        type="button"
        className={`lang-toggle__btn${lang === "al" ? " is-active" : ""}`}
        onClick={set("al")}
        aria-pressed={lang === "al"}
      >AL</button>
    </div>
  );
};

const Nav = ({ active, onNavigate, onOpenContact }) => {
  window.useLang();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [scrolled, setScrolled] = useState(
    typeof window !== "undefined" && window.scrollY > 8
  );
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    { id: "home", label: t("Home") },
    { id: "products", label: t("Products") },
    { id: "partnerships", label: t("Partnerships") },
    { id: "about", label: t("About") },
  ];

  const go = (id) => {
    setMobileOpen(false);
    onNavigate(id);
  };
  const hrefFor = (id) => {
    if (id === "home") return "/";
    if (id === "about") return "/about";
    if (id === "products") return "/products";
    if (id === "partnerships") return "/partnerships";
    if (id === "contact") return "/contact";
    return `#${id}`;
  };

  return (
    <>
      <header className={`nav${scrolled ? " nav--scrolled" : ""}`}>
        <div className="nav__inner">
          <a href="/" className="brand" onClick={(e)=>{ e.preventDefault(); go("home"); }}>
            <img src="assets/euromobilje-logo.png" alt="EUROMOBILJE" className="brand__logo" />
            <span className="brand__mark">EUROMOBILJE</span>
            <span className="brand__since">Shpk · est. 1998</span>
          </a>
          <nav>
            <ul className="nav__links">
              {links.map(l => {
                const isActive = active === l.id;
                return (
                  <li key={l.id}>
                    <a
                      href={hrefFor(l.id)}
                      className={isActive ? "active" : ""}
                      style={isActive ? {
                        color: "var(--walnut)",
                        textDecorationLine: "underline",
                        textDecorationColor: "var(--accent)",
                        textDecorationThickness: "2px",
                        textUnderlineOffset: "8px",
                      } : undefined}
                      onClick={(e)=>{ e.preventDefault(); go(l.id); }}
                    >{l.label}</a>
                  </li>
                );
              })}
            </ul>
          </nav>
          <div className="nav__cta">
            <LangToggle />
            <button className={`btn ${active === "contact" ? "btn--primary" : "btn--ghost"}`} onClick={onOpenContact}>
              {t("Contact Us")} <Icon name="arrow-right" size={14}/>
            </button>
            <button className="nav__burger" onClick={()=>setMobileOpen(true)} aria-label={t("Open menu")}>
              <Icon name="menu" size={18} />
            </button>
          </div>
        </div>
      </header>
      <div className={`mobile-menu${mobileOpen ? " open" : ""}`}>
        <button className="mobile-menu__close" onClick={()=>setMobileOpen(false)} aria-label={t("Close menu")}>
          <Icon name="close" size={18} />
        </button>
        <ul>
          {links.map(l => {
            const isActive = active === l.id;
            return (
              <li key={l.id}>
                <a
                  href={hrefFor(l.id)}
                  className={isActive ? "active" : ""}
                  style={isActive ? {
                    color: "var(--walnut)",
                    textDecorationLine: "underline",
                    textDecorationColor: "var(--accent)",
                    textDecorationThickness: "2px",
                    textUnderlineOffset: "8px",
                  } : undefined}
                  onClick={(e)=>{ e.preventDefault(); go(l.id); }}
                >{l.label}</a>
              </li>
            );
          })}
        </ul>
        <LangToggle className="lang-toggle--mobile" />
        <button className="btn btn--primary" style={{marginTop: 24, alignSelf: "flex-start"}} onClick={()=>{ setMobileOpen(false); onOpenContact(); }}>
          {t("Contact Us")} <Icon name="arrow-right" size={14}/>
        </button>
      </div>
    </>
  );
};

const Hero = ({ onOpenContact, onNavigate }) => (
  <section className="section hero" id="home">
    <div className="container">
      <div className="hero__grid">
        <div>
          <span className="eyebrow">{t("Furniture manufacturer · Tirana, Albania")}</span>
          <h1 className="hero__title" style={{marginTop: 20}}>
            {t("Furniture made ")}<em>{t("to last,")}</em>{t(" designed to fit.")}
          </h1>
          <p className="hero__lead">
            {t("For 28 years EUROMOBILJE has built bespoke furniture for homes, hotels, restaurants, retail spaces, and offices across Albania and the region. Workshop-direct prices. Architect-grade collaboration. One team from sketch to install.")}
          </p>
          <div className="hero__ctas">
            <button className="btn btn--primary" onClick={onOpenContact}>
              {t("Start a project")} <Icon name="arrow-right" size={14}/>
            </button>
            <button className="btn btn--ghost" onClick={()=>onNavigate("products")}>
              {t("Browse collections")}
            </button>
          </div>
          <div className="hero__meta">
            {window.EM_DATA.STATS.map(s => (
              <div className="hero__meta__item" key={s.lbl}>
                <span className="num">{s.num}</span>
                <span className="lbl">{t(s.lbl)}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="hero__visual">
          <Placeholder
            label="warm modern interior, sculptural seating, afternoon light"
            src="https://images.unsplash.com/photo-1618221195710-dd6b41faaea6?w=1600&q=85&auto=format&fit=crop"
          />
          <div className="hero__visual__caption">
            <span>{t("Tirana workshop")}</span>
            <span>04 / 2026</span>
          </div>
        </div>
      </div>
    </div>
  </section>
);

const Marquee = () => {
  const items = [
    "Custom Cabinetry", "Hospitality Fit-out", "Architect Partnership", "Solid Wood",
    "Veneers & Lacquer", "Upholstery", "Stone & Metal", "Workshop Direct",
  ];
  return (
    <div className="marquee">
      <div className="marquee__inner">
        {[...items, ...items].map((s, i) => (
          <span key={i}>{t(s)}</span>
        ))}
      </div>
    </div>
  );
};

const Values = () => (
  <section className="section section--paper" id="values">
    <div className="container">
      <div className="section-head">
        <h2>{t("What you get when you work with us, ")}<em>{t("every time.")}</em></h2>
        <p className="section-head__intro">
          {t("Four commitments that have held since 1998 — they are why architects keep specifying us, and why hotel groups bring us into every new property.")}
        </p>
      </div>
      <div className="values">
        {window.EM_DATA.VALUES.map(v => (
          <div className="value" key={v.num}>
            <div className="value__num">— {v.num}</div>
            <h3 className="value__title">{t(v.title)}</h3>
            <p className="value__body">{t(v.body)}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const Categories = ({ onNavigate }) => (
  <section className="section section--bone" id="categories">
    <div className="container">
      <div className="section-head">
        <h2>{t("Six categories. ")}<em>{t("One workshop.")}</em></h2>
        <p className="section-head__intro">
          {t("Whether you're outfitting a single dining room or a 120-key hotel, every category is made on the same workshop floor by the same team — which is how we keep finishes, hardware, and lead times consistent across a whole project.")}
        </p>
      </div>
      <div className="cats">
        {window.EM_DATA.CATEGORIES.map(c => (
          <button className="cat" key={c.num} onClick={()=>onNavigate("products")} aria-label={t(c.title)}>
            <Placeholder label={c.img} />
            <div className="cat__overlay">
              <h3 className="cat__title">{t(c.title)}</h3>
              <div className="cat__sub">{t(c.sub)}</div>
            </div>
          </button>
        ))}
      </div>
    </div>
  </section>
);

const About = () => (
  <section className="section section--paper" id="about">
    <div className="container">
      <div className="section-head">
        <span className="eyebrow" style={{gridColumn: "1 / -1"}}>{t("About — Since 1998")}</span>
        <h2>{t("A small workshop in Tirana that ")}<em>{t("kept getting asked back.")}</em></h2>
        <p className="section-head__intro">
          {t("We started with two cabinetmakers and a single bandsaw. The thing that grew the company was simple: when you do good work for a client, they bring you the next project, and the project after that.")}
        </p>
      </div>
      <div className="story__grid">
        <div className="story__col">
          <p>{t("EUROMOBILJE Shpk was founded in 1998 in Tirana by a family of cabinetmakers. For the first ten years we made residential furniture — kitchens, wardrobes, dining sets — building a reputation among architects and homeowners who wanted something better than imported flatpack.")}</p>
          <p>{t("In 2008 a boutique hotel asked if we could handle a full property. We could. From that contract grew our hospitality division, which now accounts for more than half of our work.")}</p>
          <p>{t("Today we operate from a 4,200 m² facility on the outskirts of Tirana, with CNC machining, dedicated finishing rooms, an upholstery line, and an installation team that travels across Albania, Kosovo, North Macedonia, Montenegro, and northern Greece.")}</p>
          <blockquote className="story__quote">
            {t("“We don't try to be the cheapest, and we don't try to be the loudest. We try to be the people you call back.”")}
            <span className="story__quote__by">{t("— Founder's note")}</span>
          </blockquote>

          <ul className="timeline">
            {window.EM_DATA.TIMELINE.map(item => (
              <li key={item.yr}>
                <span className="timeline__yr">{item.yr}</span>
                <span className="timeline__txt">{t(item.txt)}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="story__visual">
          <Placeholder label="workshop floor — cabinetmakers at work" />
        </div>
      </div>
    </div>
  </section>
);

const Products = () => {
  const [tab, setTab] = useState("living");
  const products = window.EM_DATA.PRODUCTS[tab];
  return (
    <section className="section section--bone" id="products">
      <div className="container">
        <div className="section-head">
          <h2>{t("Products & ")}<em>{t("customization.")}</em></h2>
          <p className="section-head__intro">
            {t("Every piece on this site is a starting point. Dimensions, woods, fabrics, finishes, and hardware can be specified to your project — most clients change at least one thing. Lead times typically 6–10 weeks for residential, 8–14 weeks for contract.")}
          </p>
        </div>
        <div className="tabs" role="tablist">
          {window.EM_DATA.PRODUCT_TABS.map(tb => (
            <button
              key={tb.id}
              className={`tab${tab === tb.id ? " active" : ""}`}
              onClick={()=>setTab(tb.id)}
              role="tab"
              aria-selected={tab === tb.id}
            >{t(tb.label)}</button>
          ))}
        </div>
        <div className="product-grid">
          {products.map(p => (
            <div className="product" key={p.name}>
              <div className="product__visual">
                <Placeholder label={p.img} />
              </div>
              <div>
                <div className="product__name">{p.name}</div>
                <div className="product__meta">
                  <span>{t(p.meta[0])}</span>
                  <span>{window.tPrice(p.meta[1])}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
        <div style={{marginTop: 32, textAlign: "center"}}>
          <a href="/products" className="btn btn--primary">
            {t("Browse the full catalog")} <Icon name="arrow-right" size={14}/>
          </a>
        </div>
      </div>
    </section>
  );
};

const Partnerships = ({ onOpenContact, onNavigate }) => (
  <section className="section section--walnut" id="partnerships">
    <div className="container">
      <div className="b2b__grid">
        <div className="b2b__visual">
          <Placeholder dark label="hospitality lobby — full fit-out" />
        </div>
        <div>
          <span className="eyebrow" style={{color: "rgba(255,255,255,0.65)"}}>{t("Partnerships")}</span>
          <h2 style={{
            fontSize: "clamp(32px, 4vw, 56px)",
            lineHeight: 1.05,
            marginTop: 16,
            color: "var(--cream)",
            fontWeight: 400,
          }}>
            {t("Built for projects, ")}<em style={{fontStyle: "italic", color: "var(--accent-soft)", fontWeight: 400}}>{t("not just pieces.")}</em>
          </h2>
          <p style={{
            fontSize: 17,
            color: "rgba(245,240,231,0.75)",
            lineHeight: 1.6,
            marginTop: 20,
            maxWidth: "52ch",
          }}>
            {t("We deliver complete furniture packages for commercial spaces — coordinated finishes across hundreds of pieces, phased delivery to match site programmes, and after-sales support for the life of the contract.")}
          </p>
          <div className="b2b__sectors">
            {window.EM_DATA.SECTORS.map(s => {
              const iconMap = { "Hotels & Resorts": "hotel", "Restaurants & Cafés": "restaurant", "Shopping Malls": "mall", "Corporate Offices": "office" };
              return (
                <div className="b2b__sector" key={s.title}>
                  <div className="b2b__sector__icon"><Icon name={iconMap[s.title]} size={18}/></div>
                  <div>
                    <div className="b2b__sector__title">{t(s.title)}</div>
                    <div className="b2b__sector__sub">{t(s.sub)}</div>
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{marginTop: 32, display: "flex", gap: 14, flexWrap: "wrap"}}>
            <a className="btn btn--light" href="/partnerships" onClick={(e)=>{ e.preventDefault(); onNavigate && onNavigate("partnerships"); }}>
              {t("See selected partnerships")} <Icon name="arrow-right" size={14}/>
            </a>
            <button className="btn btn--light" onClick={onOpenContact} style={{borderColor: "rgba(255,255,255,0.35)"}}>
              {t("Talk to our contract team")}
            </button>
          </div>
        </div>
      </div>
    </div>
  </section>
);

const Design = () => (
  <section className="section section--paper" id="design">
    <div className="container">
      <div className="section-head">
        <span className="eyebrow" style={{gridColumn: "1 / -1"}}>{t("Design & Consultation")}</span>
        <h2>{t("From a first sketch ")}<em>{t("to the final install.")}</em></h2>
        <p className="section-head__intro">
          {t("Most of our projects begin before any furniture has been specified. We work alongside architects and interior designers — or we lead the design ourselves when the client doesn't have a studio engaged. First consultation is free.")}
        </p>
      </div>
      <div className="process">
        {window.EM_DATA.PROCESS.map(p => (
          <div className="step" key={p.num}>
            <div className="step__num">{p.num}</div>
            <div className="step__title">{t(p.title)}</div>
            <div className="step__body">{t(p.body)}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const Testimonials = () => (
  <section className="section section--bone">
    <div className="container">
      <div className="section-head">
        <h2>{t("Clients who ")}<em>{t("came back.")}</em></h2>
        <p className="section-head__intro">
          {t("Roughly 70% of our contract work each year comes from repeat clients or direct referrals. A few notes from people we've built for.")}
        </p>
      </div>
      <div className="tst">
        {window.EM_DATA.TESTIMONIALS.map(item => (
          <div className="tst__card" key={item.name}>
            <div className="tst__quote">“{t(item.quote)}”</div>
            <div className="tst__by">
              <div className="tst__avatar">{item.initials}</div>
              <div>
                <div className="tst__name">{item.name}</div>
                <div className="tst__role">{t(item.role)}</div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// Standalone /contact page — Nav + editorial hero + form + info aside + Footer.
const ContactPage = () => {
  window.useLang();
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({
    name: "", company: "", email: "", phone: "",
    type: "Residential", scope: "", message: "",
  });
  const upd = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  const submit = (e) => {
    e.preventDefault();
    setSubmitted(true);
    setTimeout(() => setSubmitted(false), 4000);
    setForm({ name: "", company: "", email: "", phone: "", type: "Residential", scope: "", message: "" });
  };

  const navigate = (id) => {
    if (id === "contact") {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }
    if (id === "home") { window.location.href = "/"; return; }
    if (id === "about") { window.location.href = "/about"; return; }
    if (id === "products") { window.location.href = "/products"; return; }
    if (id === "partnerships") { window.location.href = "/partnerships"; return; }
    window.location.href = `/#${id}`;
  };
  const openContact = () => { window.scrollTo({ top: 0, behavior: "smooth" }); };

  return (
    <>
      <Nav active="contact" onNavigate={navigate} onOpenContact={openContact} />
      <main>
        <section className="section section--paper page-hero page-hero--compact">
          <div className="container">
            <span className="eyebrow">{t("Contact · Tirana, Albania")}</span>
            <h1 className="page-hero__title">
              {t("Start a ")}<em>{t("conversation.")}</em>
            </h1>
            <p className="page-hero__lead">
              {t("Tell us what you're working on. We'll respond within one business day with the right person — design, contract sales, or workshop — depending on the brief.")}
            </p>
            <div className="page-hero__rule" aria-hidden="true"></div>
          </div>
        </section>

        <section className="section">
          <div className="container">
            <div className="contact__grid">
              <form onSubmit={submit}>
                <div className="field--row">
                  <div className="field">
                    <label>{t("Full name")}</label>
                    <input type="text" required value={form.name} onChange={upd("name")} placeholder="Erjon Hoxha" />
                  </div>
                  <div className="field">
                    <label>{t("Company / Studio (optional)")}</label>
                    <input type="text" value={form.company} onChange={upd("company")} placeholder="LK Studio" />
                  </div>
                </div>
                <div className="field--row">
                  <div className="field">
                    <label>{t("Email")}</label>
                    <input type="email" required value={form.email} onChange={upd("email")} placeholder="you@studio.al" />
                  </div>
                  <div className="field">
                    <label>{t("Phone")}</label>
                    <input type="tel" value={form.phone} onChange={upd("phone")} placeholder="+355 ..." />
                  </div>
                </div>
                <div className="field--row">
                  <div className="field">
                    <label>{t("Project type")}</label>
                    <select value={form.type} onChange={upd("type")}>
                      <option value="Residential">{t("Residential")}</option>
                      <option value="Hotel / Resort">{t("Hotel / Resort")}</option>
                      <option value="Restaurant / Café">{t("Restaurant / Café")}</option>
                      <option value="Retail / Mall">{t("Retail / Mall")}</option>
                      <option value="Office">{t("Office")}</option>
                      <option value="Other commercial">{t("Other commercial")}</option>
                    </select>
                  </div>
                  <div className="field">
                    <label>{t("Scope (rough)")}</label>
                    <input type="text" value={form.scope} onChange={upd("scope")} placeholder={t("e.g. lobby + 40 rooms")} />
                  </div>
                </div>
                <div className="field">
                  <label>{t("Project notes")}</label>
                  <textarea required value={form.message} onChange={upd("message")} placeholder={t("Site, timeline, references, anything you'd like us to know.")} />
                </div>
                <button type="submit" className="btn btn--primary">
                  {t("Send enquiry")} <Icon name="arrow-right" size={14}/>
                </button>
                <div className={`toast${submitted ? " show" : ""}`}>
                  {t("✓ Thanks — we'll be in touch within one business day.")}
                </div>
              </form>
              <aside className="contact__info">
                <div className="contact__info__group">
                  <div className="contact__info__label">{t("Workshop & Showroom")}</div>
                  <div className="contact__info__val">
                    Rruga Dritan Hoxha, Nr. 142<br/>
                    {t("Tirana")} 1023, {window.__lang === "al" ? "Shqipëri" : "Albania"}
                  </div>
                </div>
                <div className="contact__info__group">
                  <div className="contact__info__label">{t("Phone")}</div>
                  <div className="contact__info__val">
                    <a href="tel:+35542000000">+355 4 200 00 00</a><br/>
                    <a href="tel:+35569000000">+355 69 200 00 00</a> &nbsp;<span style={{color: "var(--walnut-3)", fontSize: 12}}>(WhatsApp)</span>
                  </div>
                </div>
                <div className="contact__info__group">
                  <div className="contact__info__label">{t("Email")}</div>
                  <div className="contact__info__val">
                    <a href="mailto:projects@euromobilje.al">projects@euromobilje.al</a><br/>
                    <a href="mailto:contract@euromobilje.al">contract@euromobilje.al</a>
                  </div>
                </div>
                <div className="contact__info__group">
                  <div className="contact__info__label">{t("Hours")}</div>
                  <div className="contact__info__val">
                    {t("Mon–Fri · 08:00–18:00")}<br/>
                    {t("Sat · 09:00–14:00 (showroom)")}
                  </div>
                </div>
                <div className="contact__info__group">
                  <div className="contact__info__label">{t("Languages")}</div>
                  <div className="contact__info__val" style={{fontSize: 14, color: "var(--walnut-2)"}}>
                    Shqip · English · Italiano
                  </div>
                </div>
              </aside>
            </div>
          </div>
        </section>
      </main>
      <Footer onNavigate={navigate} />
    </>
  );
};

const Footer = ({ onNavigate }) => (
  <footer className="footer">
    <div className="container">
      <div className="footer__grid">
        <div className="footer__brand">
          <img src="assets/white-logo.png" alt="EUROMOBILJE" className="footer__brand__logo" />
          <div style={{
            fontFamily: "var(--serif)",
            fontSize: 24,
            color: "var(--cream)",
          }}>EUROMOBILJE Shpk</div>
          <p>{t("Furniture manufacturer based in Tirana, Albania. Residential, hospitality, retail, and contract since 1998.")}</p>
        </div>
        <div>
          <h4>{t("Explore")}</h4>
          <ul>
            <li><a href="/about" onClick={(e)=>{e.preventDefault(); onNavigate("about");}}>{t("About")}</a></li>
            <li><a href="#products" onClick={(e)=>{e.preventDefault(); onNavigate("products");}}>{t("Products")}</a></li>
            <li><a href="/partnerships" onClick={(e)=>{e.preventDefault(); onNavigate("partnerships");}}>{t("Partnerships")}</a></li>
            <li><a href="#design" onClick={(e)=>{e.preventDefault(); onNavigate("design");}}>{t("Design Service")}</a></li>
          </ul>
        </div>
        <div>
          <h4>{t("Sectors")}</h4>
          <ul>
            <li><a href="/partnerships" onClick={(e)=>{e.preventDefault(); onNavigate("partnerships");}}>{t("Hotels & Resorts")}</a></li>
            <li><a href="/partnerships" onClick={(e)=>{e.preventDefault(); onNavigate("partnerships");}}>{t("Restaurants & Cafés")}</a></li>
            <li><a href="/partnerships" onClick={(e)=>{e.preventDefault(); onNavigate("partnerships");}}>{t("Retail & Malls")}</a></li>
            <li><a href="/partnerships" onClick={(e)=>{e.preventDefault(); onNavigate("partnerships");}}>{t("Corporate Offices")}</a></li>
          </ul>
        </div>
        <div>
          <h4>{t("Contact")}</h4>
          <ul>
            <li><a href="mailto:projects@euromobilje.al">projects@euromobilje.al</a></li>
            <li><a href="tel:+35542000000">+355 4 200 00 00</a></li>
            <li>Rruga Dritan Hoxha 142, {t("Tirana")}</li>
            <li><a href="/contact" onClick={(e)=>{e.preventDefault(); onNavigate("contact");}}>{t("Send enquiry →")}</a></li>
          </ul>
        </div>
      </div>
      <div className="footer__bottom">
        <span>© 1998–2026 EUROMOBILJE SHPK · NIPT L01234567A</span>
        <span>{t("Made in Tirana")}</span>
      </div>
    </div>
  </footer>
);

// Standalone /products page — flattens all categories into one list with
// filters (category, max price, name search) and sorting.
const ProductsPage = () => {
  window.useLang();
  const allProducts = useMemo(() => {
    const out = [];
    Object.entries(window.EM_DATA.PRODUCTS).forEach(([cat, items]) => {
      items.forEach((p) => {
        const m = (p.meta[1] || "").match(/€\s*([\d,.]+)/);
        const price = m ? parseFloat(m[1].replace(/,/g, "")) : 0;
        out.push({ ...p, category: cat, price });
      });
    });
    return out;
  }, []);

  const categories = window.EM_DATA.PRODUCT_TABS;
  const maxPrice = useMemo(
    () => Math.ceil(Math.max(...allProducts.map((p) => p.price)) / 100) * 100,
    [allProducts]
  );

  const [selectedCats, setSelectedCats] = useState(() => new Set());
  const [priceCap, setPriceCap] = useState(maxPrice);
  const [search, setSearch] = useState("");
  const [sort, setSort] = useState("name");

  const toggleCat = (id) => {
    setSelectedCats((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    const result = allProducts.filter((p) => {
      if (selectedCats.size > 0 && !selectedCats.has(p.category)) return false;
      if (p.price > priceCap) return false;
      if (q && !p.name.toLowerCase().includes(q)) return false;
      return true;
    });
    if (sort === "price-asc") result.sort((a, b) => a.price - b.price);
    else if (sort === "price-desc") result.sort((a, b) => b.price - a.price);
    else result.sort((a, b) => a.name.localeCompare(b.name));
    return result;
  }, [allProducts, selectedCats, priceCap, search, sort]);

  const clearFilters = () => {
    setSelectedCats(new Set());
    setPriceCap(maxPrice);
    setSearch("");
    setSort("name");
  };

  // Cross-page navigation: hash anchors live on /, except for ids that
  // have their own page. "products" is here (this page) — scroll to top.
  const navigate = (id) => {
    if (id === "products") {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }
    if (id === "home") { window.location.href = "/"; return; }
    if (id === "about") { window.location.href = "/about"; return; }
    if (id === "partnerships") { window.location.href = "/partnerships"; return; }
    if (id === "contact") { window.location.href = "/contact"; return; }
    window.location.href = `/#${id}`;
  };
  const openContact = () => { window.location.href = "/contact"; };

  return (
    <>
      <Nav active="products" onNavigate={navigate} onOpenContact={openContact} />
      <main>
        <section className="section section--paper" style={{paddingTop: "120px"}}>
          <div className="container">
            <div className="section-head">
              <span className="eyebrow" style={{gridColumn: "1 / -1"}}>{t("All products · Browse the catalog")}</span>
              <h2>{t("Every piece, ")}<em>{t("one workshop.")}</em></h2>
              <p className="section-head__intro">
                {t("Browse our complete catalog. Filter by category, price, or search by name — every piece can be customized to your project. Lead times typically 6–10 weeks for residential, 8–14 weeks for contract.")}
              </p>
            </div>

            <div className="products-page">
              <aside className="filters">
                <div className="filter-group">
                  <h4>{t("Search")}</h4>
                  <input
                    type="text"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    placeholder={t("Find by name…")}
                    className="filter-input"
                  />
                </div>

                <div className="filter-group">
                  <h4>{t("Category")}</h4>
                  <div className="filter-options">
                    {categories.map((c) => (
                      <label key={c.id} className="filter-check">
                        <input
                          type="checkbox"
                          checked={selectedCats.has(c.id)}
                          onChange={() => toggleCat(c.id)}
                        />
                        <span>{t(c.label)}</span>
                      </label>
                    ))}
                  </div>
                </div>

                <div className="filter-group">
                  <h4>{t("Max price")}</h4>
                  <input
                    type="range"
                    min={0}
                    max={maxPrice}
                    step={100}
                    value={priceCap}
                    onChange={(e) => setPriceCap(Number(e.target.value))}
                    className="filter-range"
                  />
                  <div className="filter-range-val">
                    {window.__lang === "al" ? "deri në" : "up to"} €{priceCap.toLocaleString()}
                  </div>
                </div>

                <div className="filter-group">
                  <h4>{t("Sort")}</h4>
                  <select value={sort} onChange={(e) => setSort(e.target.value)} className="filter-input">
                    <option value="name">{t("Name (A–Z)")}</option>
                    <option value="price-asc">{t("Price (low to high)")}</option>
                    <option value="price-desc">{t("Price (high to low)")}</option>
                  </select>
                </div>

                <button type="button" className="btn btn--ghost filter-clear" onClick={clearFilters}>
                  {t("Clear filters")}
                </button>
              </aside>

              <div className="products-page__main">
                <div className="results-bar">
                  {window.__lang === "al" ? (
                    <span>Duke shfaqur <strong>{filtered.length}</strong> nga {allProducts.length} produkte</span>
                  ) : (
                    <span>Showing <strong>{filtered.length}</strong> of {allProducts.length} products</span>
                  )}
                </div>
                {filtered.length > 0 ? (
                  <div className="product-grid">
                    {filtered.map((p) => (
                      <div className="product" key={p.name + p.category}>
                        <div className="product__visual">
                          <Placeholder label={p.img} />
                        </div>
                        <div>
                          <div className="product__name">{p.name}</div>
                          <div className="product__meta">
                            <span>{t(p.meta[0])}</span>
                            <span>{window.tPrice(p.meta[1])}</span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="empty-results">
                    <p>{t("No products match your filters.")}</p>
                    <button type="button" className="btn btn--ghost" onClick={clearFilters}>
                      {t("Clear filters")}
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </section>
      </main>
      <Footer onNavigate={navigate} />
    </>
  );
};

// Standalone /partnerships page — editorial-monograph layout for selected
// client work. Alternating left/right blocks, oversized italic serif names,
// numbered sequence floating over each image.
const PartnershipsPage = () => {
  window.useLang();
  const items = window.EM_DATA.PARTNERSHIPS;

  const navigate = (id) => {
    if (id === "partnerships") {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }
    if (id === "home") { window.location.href = "/"; return; }
    if (id === "about") { window.location.href = "/about"; return; }
    if (id === "products") { window.location.href = "/products"; return; }
    if (id === "contact") { window.location.href = "/contact"; return; }
    window.location.href = `/#${id}`;
  };
  const openContact = () => { window.location.href = "/contact"; };

  return (
    <>
      <Nav active="partnerships" onNavigate={navigate} onOpenContact={openContact} />
      <main>
        <section className="section section--paper page-hero page-hero--compact">
          <div className="container">
            <span className="eyebrow">{t("Selected partnerships · trusted across the Balkans")}</span>
            <h1 className="page-hero__title">
              {t("The work that ")}<em>{t("got us asked back.")}</em>
            </h1>
            <p className="page-hero__lead">
              {t("Roughly seventy percent of our contract revenue each year comes from repeat clients or direct referrals from architects we've worked with before. Six of the projects we're proudest of, in no particular order — each one a new property, a new programme, and a relationship we still maintain.")}
            </p>
            <div className="page-hero__rule" aria-hidden="true"></div>
          </div>
        </section>

        <section className="section partnerships-list-wrap">
          <div className="container">
            <ol className="partnerships-list">
              {items.map((p, i) => (
                <li
                  className={`partnership partnership--${i % 2 === 0 ? "left" : "right"}`}
                  key={p.name}
                >
                  <div className="partnership__visual">
                    <div className="partnership__img-frame">
                      <img
                        src={p.img}
                        alt={`${p.name} — ${t(p.scope)}`}
                        className="partnership__img"
                        loading="lazy"
                      />
                    </div>
                  </div>
                  <div className="partnership__text">
                    <div className="partnership__sector">{t(p.sector)}</div>
                    <h2 className="partnership__name">
                      <em>{p.name}</em>
                    </h2>
                    <dl className="partnership__meta">
                      <div className="partnership__meta-row">
                        <dt>{t("Location")}</dt><dd>{t(p.location)}</dd>
                      </div>
                      <div className="partnership__meta-row">
                        <dt>{t("Year")}</dt><dd>{t(p.year)}</dd>
                      </div>
                      <div className="partnership__meta-row">
                        <dt>{t("Scope")}</dt><dd>{t(p.scope)}</dd>
                      </div>
                    </dl>
                    <p className="partnership__blurb">{t(p.blurb)}</p>
                  </div>
                </li>
              ))}
            </ol>
          </div>
        </section>

        <section className="section section--walnut partnerships-cta">
          <div className="container">
            <div className="partnerships-cta__inner">
              <span className="eyebrow" style={{color: "rgba(255,255,255,0.65)"}}>{t("Next chapter")}</span>
              <h2 className="partnerships-cta__title">
                {t("Bring us your ")}<em>{t("next project.")}</em>
              </h2>
              <p className="partnerships-cta__lead">
                {t("Hospitality, retail, residential, corporate — if it's a brief that benefits from a single workshop owning the whole programme, we'd like to hear about it.")}
              </p>
              <a
                className="btn btn--light"
                href="/contact"
                onClick={(e)=>{ e.preventDefault(); openContact(); }}
              >
                {t("Start a conversation")} <Icon name="arrow-right" size={14}/>
              </a>
            </div>
          </div>
        </section>
      </main>
      <Footer onNavigate={navigate} />
    </>
  );
};

// Standalone /about page — full studio story with timeline, stats,
// workshop visual, and CTA.
const AboutPage = () => {
  window.useLang();
  const navigate = (id) => {
    if (id === "about") {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }
    if (id === "home") { window.location.href = "/"; return; }
    if (id === "products") { window.location.href = "/products"; return; }
    if (id === "partnerships") { window.location.href = "/partnerships"; return; }
    if (id === "contact") { window.location.href = "/contact"; return; }
    window.location.href = `/#${id}`;
  };
  const openContact = () => { window.location.href = "/contact"; };

  return (
    <>
      <Nav active="about" onNavigate={navigate} onOpenContact={openContact} />
      <main>
        <section className="section section--paper page-hero page-hero--compact">
          <div className="container">
            <span className="eyebrow">{t("About · est. 1998 · Tirana")}</span>
            <h1 className="page-hero__title">
              {t("Quality and design, ")}<em>{t("since 1998.")}</em>
            </h1>
            <p className="page-hero__lead">
              {t("Furniture made to your needs, with the support of a dedicated team — from first sketch to final install.")}
            </p>
            <div className="page-hero__rule" aria-hidden="true"></div>
          </div>
        </section>

        <section className="section section--paper">
          <div className="container">
            <div className="story__grid">
              <div className="story__col">
                <p>{t("EUROMOBILJE Ltd. was founded in 1998. Over the years, our experience has helped us clearly understand our customers' true needs—high-quality products combined with refined design—allowing us to bring their ideas and preferences to life.")}</p>
                <p>{t("Our products are backed by integrity, along with dedicated support from our team. We offer detailed guidance for every product specification, as well as professional advice from our team of architects, who are ready to assist you in designing and furnishing your spaces.")}</p>
                <p>{t("Passion and a love for aesthetics are the core values that inspired the creation of EUROMOBILJE. One of the key pillars of our business strategy is offering competitive pricing without compromising on quality. We remain committed to being part of your homes through attractive offers and guaranteed excellence.")}</p>
                <blockquote className="story__quote">
                  {t("Our mission is simple: to achieve customer satisfaction through quality, service, and trust.")}
                  <span className="story__quote__by">{t("— EUROMOBILJE")}</span>
                </blockquote>
              </div>
              <div className="story__visual">
                <Placeholder label="workshop floor — cabinetmakers at work" />
              </div>
            </div>
          </div>
        </section>

        <section className="section section--walnut">
          <div className="container">
            <div className="partnerships-cta__inner">
              <span className="eyebrow" style={{color: "rgba(255,255,255,0.65)"}}>{t("Get in touch")}</span>
              <h2 className="partnerships-cta__title">
                {t("Bring us your ")}<em>{t("next project.")}</em>
              </h2>
              <p className="partnerships-cta__lead">
                {t("Residential, hospitality, retail, corporate. First consultation is free; first response within one business day.")}
              </p>
              <a
                className="btn btn--light"
                href="/contact"
                onClick={(e)=>{ e.preventDefault(); openContact(); }}
              >
                {t("Start a conversation")} <Icon name="arrow-right" size={14}/>
              </a>
            </div>
          </div>
        </section>
      </main>
      <Footer onNavigate={navigate} />
    </>
  );
};

Object.assign(window, {
  Icon, Placeholder, Nav, Hero, Marquee, Values, Categories,
  About, Products, Partnerships, Design, Testimonials, Footer,
  ProductsPage, PartnershipsPage, ContactPage, AboutPage,
});
