/* global React, ReactDOM, TweaksPanel, useTweaks, TweakSection, TweakColor, TweakRadio, TweakToggle */

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

// -- Data loaders --------------------------------------------------------
const projectsData = JSON.parse(document.getElementById("projects-data").textContent);
const awardsData   = JSON.parse(document.getElementById("awards-data").textContent);
const clientsData  = JSON.parse(document.getElementById("clients-data").textContent);
const teamData     = JSON.parse(document.getElementById("team-data").textContent);

const SECTORS = [
  { id: "all",          label: "All",                     labelAr: "الكل" },
  { id: "commercial",   label: "Commercial / Workplace",  labelAr: "الأعمال" },
  { id: "hospitality",  label: "Hospitality / F&B",       labelAr: "الضيافة" },
  { id: "public",       label: "Public / Education",      labelAr: "العام" },
  { id: "residential",  label: "Residential",             labelAr: "السكنية" },
];

const COPY = {
  en: {
    dir: "ltr",
    nav: { work: "Work", sectors: "Sectors", studio: "Studio", awards: "Awards", contact: "Contact", cta: "Start a project" },
    hero: {
      eyebrow: "Swiss Bureau — A Design & Build Practice",
      h: "Interior\nDesign & Build,\nDubai. Since 2003.",
      meta1: "Established",
      meta1v: "2003",
      meta2: "Studio",
      meta2v: "Bay Square, Business Bay",
      meta3: "Group",
      meta3v: "Edifice · Lausanne",
      strip: [
        { k: "Practice", v: "Single accountable partner —\ndesign through delivery." },
        { k: "Sectors",  v: "Commercial · Hospitality ·\nF&B · Public · Residential." },
        { k: "Region",   v: "United Arab Emirates +\nKingdom of Saudi Arabia." },
        { k: "Recent",   v: "CID Awards 2024 — Winner.\n2025 — Shortlist, ALEC HQ." },
      ],
    },
    sectorsTitle: "Sectors",
    sectorsLead: "Five disciplines under one Swiss-precision practice. Each sector portfolio is the work of the same team — only the brief and the section header change.",
    workTitle: "Selected Work",
    workLead: "A working portfolio. Click any project to open its case study. Per-project years and areas are populated on confirmation with the client.",
    studioTitle: "The Studio",
    studioP1: "Swiss Bureau Interior Design was founded in 2003 by Swiss interior architect Joakim de Rham as a Dubai outpost of the Edifice group of Lausanne — a 60-year design lineage rooted in Swiss precision.",
    studioP2: "Two decades on, the practice operates two licensed entities — Swiss Bureau Interior Design LLC and Swiss Bureau Projects Supply LLC — delivering interior design and the fit-out that realises it under a single accountable partnership.",
    studioP3: "Our work is the work of long client relationships: AtkinsRéalis, Egon Zehnder, ICD Brookfield, ALEC, Galadari Brothers, the W Hotel ATTIKO concept, Sharjah Broadcasting Authority, the University of Europe campus, and a residential portfolio for Jubail Island.",
    awardsTitle: "Awards & Press",
    clientsTitle: "Selected Clients",
    contactTitle: "Start a project",
    contactLead: "Tell us about the brief. We will reply within one working day.",
    submit: "Send enquiry",
    footnote: "We respect client confidentiality. Submissions route to sales@sb-id.com. Photography on this site is third-party and credited per project; per-project metadata (year, area) is confirmed prior to publication.",
  },
  ar: {
    dir: "rtl",
    nav: { work: "المشاريع", sectors: "القطاعات", studio: "الاستوديو", awards: "الجوائز", contact: "تواصل", cta: "ابدأ مشروعك" },
    hero: {
      eyebrow: "سويس بيرو — تصميم وتنفيذ",
      h: "تصميم داخلي\nوتنفيذ متكامل،\nدبي. منذ ٢٠٠٣.",
      meta1: "تأسس",
      meta1v: "٢٠٠٣",
      meta2: "الاستوديو",
      meta2v: "باي سكوير، الخليج التجاري",
      meta3: "المجموعة",
      meta3v: "إديفيس · لوزان",
      strip: [
        { k: "الممارسة", v: "شريك واحد للمسؤولية\nمن التصميم إلى التسليم." },
        { k: "القطاعات", v: "أعمال · ضيافة ·\nمطاعم · عام · سكني." },
        { k: "الإقليم",   v: "الإمارات العربية المتحدة\nوالمملكة العربية السعودية." },
        { k: "الأحدث",   v: "جوائز سي آي دي ٢٠٢٤ — فائز.\n٢٠٢٥ — قائمة قصيرة." },
      ],
    },
    sectorsTitle: "القطاعات",
    sectorsLead: "خمس تخصصات في ممارسة واحدة بدقة سويسرية. كل قطاع يحمل توقيع الفريق نفسه — فقط البرنامج يتغير.",
    workTitle: "أعمال مختارة",
    workLead: "محفظة أعمال حيّة. اضغط على أي مشروع لفتح دراسة الحالة. يتم تأكيد سنة كل مشروع ومساحته مع العميل قبل النشر.",
    studioTitle: "الاستوديو",
    studioP1: "تأسست سويس بيرو للتصميم الداخلي عام ٢٠٠٣ على يد المهندس المعماري السويسري يواكيم دو رام، كفرع لمجموعة إديفيس في لوزان — إرث تصميمي يمتد لستين عاماً.",
    studioP2: "بعد عقدين، تدير الممارسة كيانين مرخصين يقدمان التصميم والتنفيذ تحت شراكة واحدة مسؤولة.",
    studioP3: "أعمالنا هي نتاج علاقات طويلة مع عملاء كبار: AtkinsRéalis، Egon Zehnder، ICD Brookfield، ALEC، وغيرهم.",
    awardsTitle: "جوائز وإعلام",
    clientsTitle: "عملاء مختارون",
    contactTitle: "ابدأ مشروعك",
    contactLead: "أخبرنا عن البرنامج. سنرد خلال يوم عمل واحد.",
    submit: "إرسال",
    footnote: "نحترم سرية العميل. ترسل الطلبات إلى sales@sb-id.com.",
  }
};

// -- Tweaks defaults -----------------------------------------------------
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "red",
  "density": "comfortable",
  "language": "en",
  "heroAuto": true,
  "showProjectCodes": true
}/*EDITMODE-END*/;

// -- Utilities -----------------------------------------------------------
function useScrolled(threshold = 24) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > threshold);
    on();
    window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, [threshold]);
  return scrolled;
}

function fmtN(n) {
  return String(n).padStart(2, "0");
}

// -- Components ----------------------------------------------------------

function LogoMark({ size = 22 }) {
  return (
    <span className="logo-mark" style={{ fontSize: size }}>
      SB<span className="dot">·</span>ID
    </span>
  );
}

function Nav({ onCta, t, locale, setLocale }) {
  const solid = useScrolled(40);
  const links = [
    { id: "work",     label: t.nav.work },
    { id: "sectors",  label: t.nav.sectors },
    { id: "studio",   label: t.nav.studio },
    { id: "awards",   label: t.nav.awards },
    { id: "contact",  label: t.nav.contact },
  ];
  const scrollTo = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  return (
    <header className={`nav ${solid ? "solid" : ""}`}>
      <div className="nav-inner">
        <a href="#top" onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: "smooth" }); }}>
          <LogoMark />
        </a>
        <nav className="nav-links hidden-on-mobile">
          {links.map((l) => (
            <a key={l.id} className="nav-link" href={`#${l.id}`} onClick={(e) => { e.preventDefault(); scrollTo(l.id); }}>
              {l.label}
            </a>
          ))}
        </nav>
        <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
          <div className="nav-locale hidden-on-mobile" role="group" aria-label="Language">
            <button className={locale === "en" ? "on" : ""} onClick={() => setLocale("en")}>EN</button>
            <button className={locale === "ar" ? "on" : ""} onClick={() => setLocale("ar")}>عربي</button>
          </div>
          <button className="nav-cta" onClick={onCta}>
            {t.nav.cta}
            <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--accent)" }} />
          </button>
        </div>
      </div>
    </header>
  );
}

function Hero({ t, autoplay }) {
  const heroImages = projectsData.filter((p) => p.hero).slice(0, 6);
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    if (!autoplay) return;
    const tm = setInterval(() => setIdx((i) => (i + 1) % heroImages.length), 4200);
    return () => clearInterval(tm);
  }, [autoplay, heroImages.length]);

  const current = heroImages[idx];
  return (
    <section className="hero" id="top">
      <div>
        <div className="hero-top">
          <div className="hero-tag">
            <div className="eyebrow">{t.hero.eyebrow}</div>
            <h1 className="display">{t.hero.h.split("\n").map((line, i) => (
              <React.Fragment key={i}>{line}<br/></React.Fragment>
            ))}</h1>
          </div>
          <div className="hero-meta hidden-on-mobile">
            <div>{t.hero.meta1} <b>{t.hero.meta1v}</b></div>
            <div>{t.hero.meta2} <b>{t.hero.meta2v}</b></div>
            <div>{t.hero.meta3} <b>{t.hero.meta3v}</b></div>
          </div>
        </div>
      </div>

      <div className="hero-stage">
        {heroImages.map((p, i) => (
          <img key={p.id} src={p.hero} alt={p.name} className={i === idx ? "on" : ""} loading={i === 0 ? "eager" : "lazy"} />
        ))}
        <div className="hero-caption">
          <span className="l">№ {fmtN(idx + 1)} / {fmtN(heroImages.length)}&nbsp;&nbsp; <b>{current?.name}</b> &nbsp;·&nbsp; {current?.location}</span>
          <span className="l">{current?.sectorLabel}</span>
        </div>
      </div>

      <div>
        <div className="hero-strip">
          {t.hero.strip.map((c, i) => (
            <div className="cell" key={i}>
              <div className="k">{c.k}</div>
              <div className="v">{c.v.split("\n").map((s, j) => <React.Fragment key={j}>{s}<br/></React.Fragment>)}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Sectors({ t, onSelect, activeSector }) {
  const sectorCounts = useMemo(() => {
    const c = {};
    projectsData.forEach((p) => { c[p.sector] = (c[p.sector] || 0) + 1; });
    return c;
  }, []);
  const sectors = [
    { id: "commercial",  label: "Commercial / Workplace", arLabel: "أعمال",  hint: "HQs · Offices · Boardrooms" },
    { id: "hospitality", label: "Hospitality",            arLabel: "ضيافة",  hint: "Hotels · Lounges" },
    { id: "fb",          label: "Food & Beverage",        arLabel: "مطاعم",  hint: "Restaurants · Bars" },
    { id: "public",      label: "Public / Education",     arLabel: "عام",    hint: "Universities · Civic" },
    { id: "residential", label: "Residential",            arLabel: "سكني",   hint: "Branded residence · Homes" },
  ];
  // hospitality and fb share the hospitality bucket in data
  const sampleFor = {
    commercial: "media/project-atkinsrealis-hq-commercial.webp",
    hospitality: "media/project-attiko-lounge-fb.webp",
    fb: "media/project-attiko-restaurant-fb.webp",
    public: "media/project-university-of-europe-public.webp",
    residential: "media/project-town-center-jubail-residential.webp",
  };
  const countFor = (id) => id === "fb" ? 0 : (sectorCounts[id] || 0);

  return (
    <section className="section" id="sectors">
      <div className="section-head">
        <div>
          <div className="num">02 — {t.sectorsTitle}</div>
          <h2 className="display-2">{t.sectorsTitle}.</h2>
        </div>
        <div style={{ maxWidth: 420, color: "var(--muted)", fontSize: 14 }}>
          {t.sectorsLead}
        </div>
      </div>

      <div className="sectors">
        {sectors.map((s, i) => (
          <div
            key={s.id}
            className={`sector ${activeSector === s.id ? "on" : ""}`}
            onClick={() => onSelect(s.id === "fb" ? "hospitality" : s.id)}
          >
            <div className="idx">{fmtN(i + 1)}</div>
            <div className="label">{s.label}</div>
            <div className="ct">{s.hint}</div>
            <div className="peek" style={{ backgroundImage: `url(${sampleFor[s.id]})` }} />
            <div className="arrow">
              View → &nbsp;<span style={{ color: "var(--muted)" }}>{countFor(s.id) || "—"}</span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function ProjectCard({ p, num, onOpen, showCodes }) {
  // Editorial sizing — vary aspect by index
  const aspect = num % 5 === 0 ? "ar-16-10" :
                 num % 4 === 0 ? "ar-4-5" :
                 num % 3 === 0 ? "ar-1-1" : "ar-3-2";
  return (
    <article className="card" onClick={() => onOpen(p)}>
      <div className={`card-frame ${aspect}`}>
        {showCodes && <div className="card-num">SB · {fmtN(num)}</div>}
        <img src={p.hero} alt={p.name} loading="lazy" />
        <div className="card-hover-cta">Case Study →</div>
      </div>
      <div className="card-meta">
        <div>
          <div className="card-name">{p.name}</div>
          <div className="card-sub">{p.location}</div>
        </div>
        <div className="card-tag">{p.sectorLabel.split(" / ")[0]}</div>
      </div>
    </article>
  );
}

function Work({ t, sector, setSector, onOpen, showCodes }) {
  const filtered = useMemo(() => {
    if (sector === "all") return projectsData;
    return projectsData.filter((p) => p.sector === sector);
  }, [sector]);

  const countBy = useMemo(() => {
    const c = { all: projectsData.length };
    projectsData.forEach((p) => { c[p.sector] = (c[p.sector] || 0) + 1; });
    return c;
  }, []);

  // Span pattern for editorial cadence
  const spans = ["col-7", "col-5", "col-4", "col-8", "col-6", "col-6", "col-5", "col-7", "col-8", "col-4", "col-6", "col-6", "col-4", "col-8", "col-5", "col-7"];

  return (
    <section className="section" id="work">
      <div className="section-head">
        <div>
          <div className="num">03 — {t.workTitle}</div>
          <h2 className="display-2">{t.workTitle}.</h2>
        </div>
        <div style={{ maxWidth: 460, color: "var(--muted)", fontSize: 14 }}>
          {t.workLead}
        </div>
      </div>

      <div className="filters" style={{ paddingTop: 36 }}>
        {SECTORS.map((s) => (
          <button
            key={s.id}
            className={`chip ${sector === s.id ? "on" : ""}`}
            onClick={() => setSector(s.id)}
          >
            <span>{s.label}</span>
            <span className="n">{fmtN(countBy[s.id] || 0)}</span>
          </button>
        ))}
      </div>

      <div className="grid">
        {filtered.map((p, i) => (
          <div key={p.id} className={spans[i % spans.length]}>
            <ProjectCard p={p} num={i + 1} onOpen={onOpen} showCodes={showCodes} />
          </div>
        ))}
      </div>
    </section>
  );
}

function CaseStudy({ project, onClose, allProjects, onOpen, onStartProject }) {
  const open = !!project;
  useEffect(() => {
    if (open) {
      document.documentElement.style.overflow = "hidden";
      const onKey = (e) => { if (e.key === "Escape") onClose(); };
      window.addEventListener("keydown", onKey);
      return () => { document.documentElement.style.overflow = ""; window.removeEventListener("keydown", onKey); };
    }
  }, [open, onClose]);

  // Find prev/next within same sector for context
  const { prev, next } = useMemo(() => {
    if (!project) return { prev: null, next: null };
    const samesector = allProjects.filter((p) => p.sector === project.sector);
    const idx = samesector.findIndex((p) => p.id === project.id);
    return {
      prev: samesector[(idx - 1 + samesector.length) % samesector.length],
      next: samesector[(idx + 1) % samesector.length],
    };
  }, [project, allProjects]);

  return (
    <React.Fragment>
      <div className={`cs-mask ${open ? "on" : ""}`} onClick={onClose} />
      <aside className={`cs ${open ? "on" : ""}`} aria-hidden={!open}>
        {project && (
          <React.Fragment>
            <div className="cs-top">
              <div className="eyebrow">Case Study · SB · {project.id.toUpperCase()}</div>
              <button className="cs-close" onClick={onClose} aria-label="Close case study">
                <span>Close</span>
                <span style={{ width: 14, height: 14, position: "relative", display: "inline-block" }}>
                  <span style={{ position: "absolute", inset: 0, borderTop: "1px solid currentColor", transform: "rotate(45deg)", top: 6 }} />
                  <span style={{ position: "absolute", inset: 0, borderTop: "1px solid currentColor", transform: "rotate(-45deg)", top: 6 }} />
                </span>
              </button>
            </div>

            <div className="cs-hero">
              <img src={project.hero} alt={project.name} />
              <div className="cap">{project.sectorLabel} · {project.location}</div>
            </div>

            <div className="cs-title">
              <div className="eyebrow">{project.tag}</div>
              <h2 className="display-2">{project.name}.</h2>
            </div>

            <div className="cs-meta">
              <div className="cell">
                <div className="k">Client</div>
                <div className="v">{project.client}</div>
              </div>
              <div className="cell">
                <div className="k">Sector</div>
                <div className="v">{project.sectorLabel}</div>
              </div>
              <div className="cell">
                <div className="k">Location</div>
                <div className="v">{project.location}</div>
              </div>
              <div className="cell">
                <div className="k">Year</div>
                <div className={`v ${project.year === "TBC" ? "tbc" : ""}`}>{project.year === "TBC" ? "— TBC" : project.year}</div>
              </div>
              <div className="cell">
                <div className="k">Scope</div>
                <div className="v">{project.scope}</div>
              </div>
            </div>

            <div className="cs-narrative">
              <div>
                <div className="eyebrow">Narrative</div>
                <div style={{ height: 8 }} />
                <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--muted)" }}>
                  Brief · Concept · Material · Outcome
                </div>
              </div>
              <div className="blocks">
                <div>
                  <h3>Brief</h3>
                  <p>{project.brief}</p>
                </div>
                <div>
                  <h3>Concept</h3>
                  <p>{project.concept}</p>
                </div>
                <div>
                  <h3>Material</h3>
                  <p>{project.material}</p>
                </div>
                <div>
                  <h3>Outcome</h3>
                  <p>{project.outcome}</p>
                </div>
              </div>
            </div>

            <div className="cs-gallery">
              {project.gallery.map((src, i) => {
                const span = i === 0 ? "col-12" : (i % 3 === 1 ? "col-7" : i % 3 === 2 ? "col-5" : "col-6");
                const ar = i === 0 ? "ar-16-10" : (i % 3 === 1 ? "ar-3-2" : "ar-4-5");
                return (
                  <div key={i} className={`item ${span} ${ar}`}>
                    <img src={src} alt={`${project.name} — image ${i + 1}`} loading="lazy" />
                  </div>
                );
              })}
            </div>

            <div className="cs-credit">
              <div>
                <span className="pill">Photography</span>
                &nbsp;&nbsp;Third-party · photographer credit to confirm with client prior to publication.
                {project.note && <div style={{ marginTop: 8, color: "var(--muted-2)" }}>Note: {project.note}</div>}
              </div>
              <div>
                <span className="pill">Practice</span>
                &nbsp;&nbsp;Swiss Bureau Interior Design — Design &amp; Build, Dubai.
              </div>
            </div>

            <div className="cs-cta-band">
              <h3>Start a project<br/>with the same hand.</h3>
              <button className="btn" onClick={() => { onClose(); setTimeout(onStartProject, 380); }}>
                Begin enquiry
                <span style={{ width: 18, height: 1, background: "currentColor", position: "relative", display: "inline-block" }}>
                  <span style={{ position: "absolute", right: 0, top: -3, width: 7, height: 7, borderRight: "1px solid currentColor", borderTop: "1px solid currentColor", transform: "rotate(45deg)" }} />
                </span>
              </button>
            </div>

            <div className="cs-nav">
              <a onClick={() => onOpen(prev)}>
                <span className="lbl">← Previous · {prev?.sectorLabel}</span>
                <span className="nm">{prev?.name}</span>
              </a>
              <a className="right" onClick={() => onOpen(next)}>
                <span className="lbl">Next · {next?.sectorLabel} →</span>
                <span className="nm">{next?.name}</span>
              </a>
            </div>
          </React.Fragment>
        )}
      </aside>
    </React.Fragment>
  );
}

function Studio({ t }) {
  return (
    <section className="section" id="studio" style={{ background: "var(--paper-2)" }}>
      <div className="section-head">
        <div>
          <div className="num">04 — {t.studioTitle}</div>
          <h2 className="display-2">{t.studioTitle}.</h2>
        </div>
      </div>

      <div className="studio" style={{ paddingTop: 56 }}>
        <div className="studio-photo">
          <div className="placeholder">
            Founder portrait<br/>Joakim de Rham<br/>—— request hi-res master ——
          </div>
          <div className="studio-photo-meta">
            <div className="n">Joakim de Rham</div>
            <div className="r">Founder & CEO · Swiss Interior Architect · Edifice Lausanne</div>
          </div>
        </div>
        <div>
          <p>{t.studioP1}</p>
          <p style={{ marginTop: 24 }}>{t.studioP2}</p>
          <p style={{ marginTop: 24 }}>{t.studioP3}</p>

          <div className="studio-points">
            <div className="pt">
              <div className="k">Practice model</div>
              <div>Design &amp; Build — design and fit-out delivered under a single accountable partner.</div>
            </div>
            <div className="pt">
              <div className="k">Heritage</div>
              <div>Part of the Edifice group of Lausanne. Swiss precision, Dubai practice.</div>
            </div>
            <div className="pt">
              <div className="k">Disciplines</div>
              <div>Interior architecture, FF&amp;E, joinery procurement, MEP coordination.</div>
            </div>
            <div className="pt">
              <div className="k">Region</div>
              <div>United Arab Emirates &amp; the Kingdom of Saudi Arabia. International on referral.</div>
            </div>
          </div>
        </div>
      </div>

      <div className="team-row">
        {teamData.map((m, i) => (
          <div className="team-card" key={i}>
            <div className="ph" />
            <div className="nm">{m.name}</div>
            <div className="rl">{m.role}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function Awards({ t }) {
  return (
    <section className="section" id="awards">
      <div className="section-head">
        <div>
          <div className="num">05 — {t.awardsTitle}</div>
          <h2 className="display-2">{t.awardsTitle}.</h2>
        </div>
        <div style={{ maxWidth: 460, color: "var(--muted)", fontSize: 14 }}>
          Attributed entries only. Refresh with the client's current list — we publish no aggregate count without an attributable list.
        </div>
      </div>

      <div className="awards-grid" style={{ marginTop: 40 }}>
        <div className="h yr">Year</div>
        <div className="h">Issuer · Project</div>
        <div className="h">Detail</div>
        <div className="h res">Status</div>
        {awardsData.map((a, i) => (
          <React.Fragment key={i}>
            <div className="yr">{a.year}</div>
            <div>
              <div style={{ fontFamily: "Inter Tight, sans-serif", fontWeight: 500, fontSize: 16, letterSpacing: "-0.01em" }}>
                {a.issuer}
              </div>
              <div style={{ color: "var(--muted)", marginTop: 4, fontSize: 13 }}>{a.project}</div>
            </div>
            <div>
              <div style={{ color: "var(--muted)", fontSize: 13 }}>
                {a.kind === "winner" && "Category winner"}
                {a.kind === "shortlist" && "Workplace category shortlist"}
                {a.kind === "feature" && "Industry recognition feature"}
              </div>
            </div>
            <div className="res">
              <span className={`badge ${a.kind === "feature" ? "muted" : ""}`}>
                <span className="d" /> {a.result}
              </span>
            </div>
          </React.Fragment>
        ))}
      </div>

      <div style={{ marginTop: 64 }}>
        <div className="eyebrow" style={{ marginBottom: 18 }}>{t.clientsTitle}</div>
        <div className="clients-strip">
          {clientsData.map((c, i) => (
            <div className="c" key={i}>{c}</div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Contact({ t }) {
  const [data, setData] = useState({
    name: "", company: "", email: "", phone: "",
    sector: "", projectType: "", location: "", message: "",
  });
  const [sent, setSent] = useState(false);
  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));

  const sectorOpts = ["Commercial / Workplace", "Hospitality", "Food & Beverage", "Public / Education", "Residential", "Other"];
  const typeOpts = ["Design & Build", "Fit-out only", "Design only", "FF&E", "Consultation"];

  const onSubmit = (e) => {
    e.preventDefault();
    setSent(true);
    // In real build this would route to Formspree → sales@sb-id.com
  };

  return (
    <section className="section" id="contact">
      <div className="section-head">
        <div>
          <div className="num">06 — {t.contactTitle}</div>
          <h2 className="display-2">{t.contactTitle}.</h2>
        </div>
        <div style={{ maxWidth: 420, color: "var(--muted)", fontSize: 14 }}>
          {t.contactLead}
        </div>
      </div>

      <div className="contact" style={{ marginTop: 56 }}>
        <div className="contact-info">
          <div className="info-row">
            <div className="k">Studio</div>
            <div className="v">
              <div className="line">Office 105, Building 6</div>
              <div className="line small">Bay Square, Marasi Drive, Business Bay</div>
              <div className="line small">P.O. Box 111581 — Dubai, UAE</div>
            </div>
          </div>
          <div className="info-row">
            <div className="k">Telephone</div>
            <div className="v">
              <div className="line"><a href="tel:+97142770402">+971 4 277 04 02</a></div>
              <div className="line"><a href="tel:+97142778549">+971 4 277 85 49</a></div>
            </div>
          </div>
          <div className="info-row">
            <div className="k">Email</div>
            <div className="v">
              <div className="line"><a href="mailto:sales@sb-id.com">sales@sb-id.com</a> <span className="small">— new projects</span></div>
              <div className="line"><a href="mailto:careers@sb-id.com">careers@sb-id.com</a> <span className="small">— careers</span></div>
              <div className="line"><a href="mailto:marketing@sb-id.com">marketing@sb-id.com</a> <span className="small">— press</span></div>
            </div>
          </div>
          <div className="info-row">
            <div className="k">Hours</div>
            <div className="v">
              <div className="line small">Sunday – Thursday — to confirm</div>
            </div>
          </div>
          <div className="info-row">
            <div className="k">Group</div>
            <div className="v">
              <div className="line">Edifice — Lausanne, Switzerland</div>
            </div>
          </div>
        </div>

        {!sent ? (
          <form className="form" onSubmit={onSubmit}>
            <div className="form-row">
              <div className="field"><label>Your name</label><input value={data.name} onChange={(e) => set("name", e.target.value)} placeholder="Full name" required /></div>
              <div className="field"><label>Company</label><input value={data.company} onChange={(e) => set("company", e.target.value)} placeholder="Optional" /></div>
              <div className="field"><label>Email</label><input type="email" value={data.email} onChange={(e) => set("email", e.target.value)} placeholder="you@company.com" required /></div>
              <div className="field"><label>Phone</label><input value={data.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+971 …" /></div>
            </div>

            <div className="field full">
              <label>Sector</label>
              <div className="chip-row">
                {sectorOpts.map((s) => (
                  <button type="button" key={s} className={`chip-pick ${data.sector === s ? "on" : ""}`} onClick={() => set("sector", s)}>{s}</button>
                ))}
              </div>
            </div>

            <div className="field full">
              <label>Project type</label>
              <div className="chip-row">
                {typeOpts.map((s) => (
                  <button type="button" key={s} className={`chip-pick ${data.projectType === s ? "on" : ""}`} onClick={() => set("projectType", s)}>{s}</button>
                ))}
              </div>
            </div>

            <div className="form-row">
              <div className="field full"><label>Location</label><input value={data.location} onChange={(e) => set("location", e.target.value)} placeholder="City · country" /></div>
            </div>

            <div className="field full">
              <label>About the brief</label>
              <textarea
                value={data.message}
                onChange={(e) => set("message", e.target.value)}
                placeholder="A few sentences on programme, area, timeline."
              />
            </div>

            <div className="submit-row">
              <div className="footnote">{t.footnote}</div>
              <button type="submit" className="submit">
                {t.submit}
                <span className="arrow" />
              </button>
            </div>
          </form>
        ) : (
          <div style={{ borderTop: "1px solid var(--line)", paddingTop: 32 }}>
            <div className="eyebrow">Received</div>
            <h3 className="display-2" style={{ fontSize: 36, margin: "12px 0 24px" }}>Thank you, {data.name || "—"}.</h3>
            <p style={{ fontSize: 18, lineHeight: 1.5, maxWidth: 560, color: "var(--muted)" }}>
              Your enquiry has been routed to <strong style={{ color: "var(--ink)" }}>sales@sb-id.com</strong>.
              You will hear back within one working day. In urgent matters please call +971 4 277 04 02.
            </p>
            <button className="submit" style={{ marginTop: 32 }} onClick={() => setSent(false)}>Send another</button>
          </div>
        )}
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer>
      <div className="col">
        <LogoMark size={28} />
        <div style={{ marginTop: 14, color: "var(--muted)", maxWidth: 320, fontSize: 13 }}>
          A Swiss-rooted interior design &amp; build practice. Dubai, since 2003. Part of the Edifice group of Lausanne.
        </div>
      </div>
      <div className="col">
        <h4>Practice</h4>
        <a href="#work">Selected Work</a>
        <a href="#sectors">Sectors</a>
        <a href="#studio">Studio</a>
        <a href="#awards">Awards</a>
      </div>
      <div className="col">
        <h4>Contact</h4>
        <a href="mailto:sales@sb-id.com">sales@sb-id.com</a>
        <a href="mailto:careers@sb-id.com">careers@sb-id.com</a>
        <a href="tel:+97142770402">+971 4 277 04 02</a>
      </div>
      <div className="col">
        <h4>Connect</h4>
        <a href="https://www.instagram.com/swissbureauinteriordesign" target="_blank" rel="noreferrer">Instagram</a>
        <a href="https://www.linkedin.com" target="_blank" rel="noreferrer">LinkedIn</a>
        <a href="https://www.pinterest.com/swissbureau" target="_blank" rel="noreferrer">Pinterest</a>
        <a href="https://www.youtube.com" target="_blank" rel="noreferrer">YouTube</a>
      </div>
      <div className="bottom">
        <span>© Swiss Bureau Interior Design · Edifice Group</span>
        <span>Dubai · Lausanne</span>
      </div>
    </footer>
  );
}

function FabCTA({ onCta, label }) {
  return (
    <button className="fab" onClick={onCta} aria-label={label}>
      <span className="dot" />
      {label}
    </button>
  );
}

// -- App ----------------------------------------------------------------

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [sector, setSector] = useState("all");
  const [openProject, setOpenProject] = useState(null);

  useEffect(() => {
    document.body.dataset.accent = tweaks.accent;
    document.body.dataset.density = tweaks.density;
    document.body.classList.toggle("rtl", tweaks.language === "ar");
    document.documentElement.lang = tweaks.language;
    document.documentElement.dir = tweaks.language === "ar" ? "rtl" : "ltr";
  }, [tweaks]);

  const t = COPY[tweaks.language] || COPY.en;
  const startProject = useCallback(() => {
    document.getElementById("contact")?.scrollIntoView({ behavior: "smooth" });
  }, []);

  const handleSectorSelect = (sectorId) => {
    setSector(sectorId);
    setTimeout(() => {
      document.getElementById("work")?.scrollIntoView({ behavior: "smooth" });
    }, 80);
  };

  return (
    <React.Fragment>
      <Nav onCta={startProject} t={t} locale={tweaks.language} setLocale={(l) => setTweak("language", l)} />
      <Hero t={t} autoplay={tweaks.heroAuto} />
      <Sectors t={t} onSelect={handleSectorSelect} activeSector={sector} />
      <Work t={t} sector={sector} setSector={setSector} onOpen={setOpenProject} showCodes={tweaks.showProjectCodes} />
      <Studio t={t} />
      <Awards t={t} />
      <Contact t={t} />
      <Footer />
      <FabCTA onCta={startProject} label={t.nav.cta} />
      <CaseStudy
        project={openProject}
        onClose={() => setOpenProject(null)}
        allProjects={projectsData}
        onOpen={setOpenProject}
        onStartProject={startProject}
      />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Visual">
          <TweakColor
            label="Accent"
            value={tweaks.accent === "red" ? "#D4262C" : tweaks.accent === "ink" ? "#15171A" : tweaks.accent === "ember" ? "#C24A1F" : "#2C5347"}
            onChange={(hex) => {
              const map = { "#D4262C": "red", "#15171A": "ink", "#C24A1F": "ember", "#2C5347": "forest" };
              setTweak("accent", map[hex] || "red");
            }}
            options={["#D4262C", "#15171A", "#C24A1F", "#2C5347"]}
          />
          <TweakRadio
            label="Density"
            value={tweaks.density}
            onChange={(v) => setTweak("density", v)}
            options={[
              { value: "comfortable", label: "Editorial" },
              { value: "dense", label: "Compact" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Behaviour">
          <TweakRadio
            label="Language"
            value={tweaks.language}
            onChange={(v) => setTweak("language", v)}
            options={[
              { value: "en", label: "EN" },
              { value: "ar", label: "عربي" },
            ]}
          />
          <TweakToggle
            label="Hero auto-cycle"
            value={tweaks.heroAuto}
            onChange={(v) => setTweak("heroAuto", v)}
          />
          <TweakToggle
            label="Project codes"
            value={tweaks.showProjectCodes}
            onChange={(v) => setTweak("showProjectCodes", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

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