// XBD Collective — main app
const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA } = React;

function Nav({ route, onNavigate, t, lang, onLang, ar }) {
  const F = window.XBD.firm;
  const [time, setTime] = useStateA("");

  useEffectA(() => {
    const fmt = () => {
      const now = new Date();
      // Dubai = UTC+4
      const utc = now.getTime() + now.getTimezoneOffset() * 60000;
      const dxb = new Date(utc + 4 * 3600 * 1000);
      const hh = String(dxb.getHours()).padStart(2, "0");
      const mm = String(dxb.getMinutes()).padStart(2, "0");
      setTime(`${hh}:${mm} GST`);
    };
    fmt();
    const id = setInterval(fmt, 30000);
    return () => clearInterval(id);
  }, []);

  const langs = [
    { id: "en", label: "EN" },
    { id: "ar", label: "ع" },
    { id: "ru", label: "RU" },
    { id: "zh", label: "中" }
  ];
  const links = [
    { id: "projects", label: t.nav.projects, num: "01" },
    { id: "services", label: t.nav.services || "Services", num: "02" },
    { id: "studio", label: t.nav.studio, num: "03" },
    { id: "contact", label: t.nav.contact, num: "04" }
  ];

  return (
    <nav className="nav" data-screen-label="Navigation">
      {/* Top utility row */}
      <div className="nav-top">
        <div className="nav-top-left">
          <span><span className="dot"/>Studio open · {time || "—— GST"}</span>
          <span style={{ opacity: 0.7 }}>Dubai Design District · Bldg 06</span>
        </div>
        <div className="nav-top-right">
          <a href={`tel:${F.phoneRaw}`}>{F.phone}</a>
          <span style={{ opacity: 0.5 }}>·</span>
          <a href={`mailto:${F.email}`}>{F.email}</a>
          <span style={{ opacity: 0.5 }}>·</span>
          <a href="https://wa.me/97145535362" target="_blank" rel="noopener" style={{ color: "var(--accent)" }}>WhatsApp</a>
        </div>
      </div>

      {/* Main nav row */}
      <div className="nav-main">
        <button className="nav-logo" onClick={() => onNavigate("home")} aria-label="XBD Collective — home">
          <Logo height={28}/>
          <div className="sub">
            Architecture &<br/>Interior Design
          </div>
        </button>

        <div className="nav-links">
          {links.map(l => (
            <button key={l.id} className={`nav-link ${route === l.id ? "active" : ""}`} onClick={() => onNavigate(l.id)}>
              <span className="num">{l.num}</span>
              <span>{l.label}</span>
            </button>
          ))}
        </div>

        <div className="nav-right">
          <div className="lang-toggle">
            {langs.map((l, i) => (
              <React.Fragment key={l.id}>
                {i > 0 && <span className="sep">/</span>}
                <button className={lang === l.id ? "active" : ""} onClick={() => onLang(l.id)}>{l.label}</button>
              </React.Fragment>
            ))}
          </div>
          <button className="nav-cta" onClick={() => onNavigate("contact")}>
            <span>{t.cta.start}</span>
            <span className="arrow">→</span>
          </button>
        </div>
      </div>
    </nav>
  );
}

function App() {
  const defaults = window.__TWEAK_DEFAULTS;
  const [tw, setTweak] = useTweaks(defaults);

  const [route, setRoute] = useStateA("home");
  const [project, setProject] = useStateA(null);
  const [routeMeta, setRouteMeta] = useStateA(null);

  const lang = tw.lang || "en";
  const t = window.XBD.i18n[lang] || window.XBD.i18n.en;
  const ar = lang === "ar";

  // Apply dir + surface globally
  useEffectA(() => {
    document.documentElement.setAttribute("dir", t.dir);
    document.documentElement.setAttribute("lang", lang);
    document.body.setAttribute("data-surface", tw.surface || "noir");
    // Accent color
    const accents = { brass: "#B08D57", clay: "#B5613A", sage: "#6F8268" };
    document.documentElement.style.setProperty("--accent", accents[tw.accent || "brass"]);
  }, [lang, tw.surface, tw.accent, t.dir]);

  // Scroll to top on route change
  useEffectA(() => {
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [route, project?.slug]);

  function navigate(to, meta) {
    if (to === "home") { setRoute("home"); setProject(null); setRouteMeta(null); return; }
    if (to === "projects") { setRoute("projects"); setProject(null); setRouteMeta(meta || null); return; }
    if (to === "case-study") { setRoute("case-study"); return; }
    setRoute(to);
    setProject(null);
    setRouteMeta(meta || null);
  }

  function openProject(p) {
    setProject(p);
    setRoute("case-study");
  }

  const navProps = { route, onNavigate: navigate, t, lang, onLang: (l) => setTweak("lang", l), ar };

  return (
    <div className="app-shell" data-screen-label={`XBD · ${route}`}>
      <Nav {...navProps}/>

      <main className="viewport" key={`${route}-${project?.slug || ""}-${lang}`}>
        {route === "home" && <HomeView t={t} ar={ar} onNavigate={navigate} onOpenProject={openProject}/>}
        {route === "projects" && <ProjectsView t={t} ar={ar} onOpenProject={openProject} initialFilter={routeMeta}/>}
        {route === "case-study" && project && <CaseStudyView t={t} ar={ar} project={project} onNavigate={navigate} onOpenProject={openProject} layout={tw.caseLayout}/>}
        {route === "services" && <ServicesView t={t} ar={ar} onNavigate={navigate}/>}
        {route === "studio" && <StudioView t={t} ar={ar} onNavigate={navigate}/>}
        {route === "contact" && <ContactView t={t} ar={ar} prefillProject={routeMeta?.project}/>}
      </main>

      <Footer t={t} onNavigate={navigate} ar={ar}/>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Language">
          <TweakSelect
            label="Locale"
            value={tw.lang}
            onChange={(v) => setTweak("lang", v)}
            options={[
              { value: "en", label: "English" },
              { value: "ar", label: "العربية (RTL)" },
              { value: "ru", label: "Русский" },
              { value: "zh", label: "中文" }
            ]}
          />
        </TweakSection>

        <TweakSection label="Surface">
          <TweakRadio
            label="Theme"
            value={tw.surface}
            onChange={(v) => setTweak("surface", v)}
            options={[
              { value: "noir", label: "Noir" },
              { value: "paper", label: "Paper" }
            ]}
          />
        </TweakSection>

        <TweakSection label="Accent">
          <TweakColor
            label="Brand accent"
            value={tw.accent}
            onChange={(v) => setTweak("accent", v)}
            options={[
              { value: "brass", color: "#B08D57", label: "Brass" },
              { value: "clay", color: "#B5613A", label: "Clay" },
              { value: "sage", color: "#6F8268", label: "Sage" }
            ]}
          />
        </TweakSection>

        <TweakSection label="Try the prototype">
          <TweakButton onClick={() => navigate("home")}>→ Home</TweakButton>
          <TweakButton onClick={() => navigate("projects")}>→ Projects (filterable)</TweakButton>
          <TweakButton onClick={() => openProject(window.XBD.projects[0])}>→ Case study: Casa del Sol</TweakButton>
          <TweakButton onClick={() => openProject(window.XBD.projects[2])}>→ Case study: Rixos Residences</TweakButton>
          <TweakButton onClick={() => navigate("studio")}>→ Studio + Awards</TweakButton>
          <TweakButton onClick={() => navigate("contact")}>→ Project enquiry</TweakButton>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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