/* global React, ReactDOM, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakSelect, TweakColor, TweakToggle,
   Nav, Home, Archive, ProjectDetail, About, Contact, IntroSplash, Wordmark,
   CONTACT_EMAIL, MAIL_HREF, TEL_HREF, ROUTES */

// Tweaks paneli yalnızca geliştirme ortamında (localhost) veya ?tweaks
// parametresiyle görünür; ziyaretçiler görmez.
const SHOW_TWEAKS =
  window.location.hostname === "localhost" ||
  window.location.hostname === "127.0.0.1" ||
  window.location.search.includes("tweaks");

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "cream",
  "type": "editorial",
  "nav": "top",
  "hero": "editorial",
  "density": "comfortable"
}/*EDITMODE-END*/;

function Footer({ navigate }) {
  return (
    <footer style={{
      marginTop: 64,
      padding: "56px 32px 28px",
      borderTop: "1px solid var(--line)",
      background: "var(--bg-alt)",
    }}>
      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr 1fr", gap: 48, alignItems: "start" }}>
        <div>
          <Wordmark height={26} />
          <p style={{ marginTop: 24, fontSize: 14, lineHeight: 1.5, color: "var(--muted)", maxWidth: 360, textWrap: "pretty" }}>
            Gizem Güleç — Bergama merkezli yüksek mimar ve restorasyon uzmanı.
            Mimari proje, restorasyon, rölöve, 3B görselleştirme ve şantiye takibi.
          </p>
        </div>
        <div>
          <div className="t-meta">Menü</div>
          <ul style={{ listStyle: "none", padding: 0, margin: "16px 0 0", display: "flex", flexDirection: "column", gap: 10 }}>
            {["home", "archive", "about", "contact"].map((p) => (
              <li key={p}>
                <a
                  href={ROUTES.routeToPath({ page: p })}
                  onClick={(e) => {
                    if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
                    e.preventDefault();
                    navigate({ page: p });
                  }}
                  style={{ fontSize: 14, cursor: "pointer" }}
                >
                  {p === "home" ? "Ana Sayfa" : p === "archive" ? "Projeler" : p === "about" ? "Hakkımızda" : "İletişim"}
                </a>
              </li>
            ))}
          </ul>
        </div>
        <div>
          <div className="t-meta">Bergama Ofisi</div>
          <div style={{ marginTop: 16, fontSize: 14, lineHeight: 1.55 }}>
            Ertuğrul Mh. Park Otel Sk.<br />
            No: 9 · D: 3<br />
            Bergama, İzmir
          </div>
          <div style={{ marginTop: 12, fontFamily: "var(--font-mono)", fontSize: 12 }}>
            <a href={TEL_HREF} style={{ color: "var(--muted)" }}>+90 506 461 20 68</a>
          </div>
          <div style={{ marginTop: 4, fontFamily: "var(--font-mono)", fontSize: 12, wordBreak: "break-all" }}>
            <a href={MAIL_HREF} style={{ color: "var(--muted)" }}>{CONTACT_EMAIL}</a>
          </div>
        </div>
        <div>
          <div className="t-meta">Sosyal</div>
          <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 8 }}>
            {["Instagram", "Are.na", "LinkedIn"].map((s) => (
              <a key={s} style={{ fontSize: 14, borderBottom: "1px solid var(--line)", alignSelf: "start" }}>{s}</a>
            ))}
          </div>
        </div>
      </div>
      <div style={{
        marginTop: 56,
        paddingTop: 20,
        borderTop: "1px solid var(--line-soft)",
        display: "flex",
        justifyContent: "space-between",
      }} className="t-mono">
        <span style={{ color: "var(--muted)" }}>© Gizem Güleç Mimarlık · 2014—{new Date().getFullYear()}</span>
        <span style={{ color: "var(--muted)" }}>Bergama · İzmir</span>
        <span style={{ color: "var(--muted)" }}>TR / EN</span>
      </div>
    </footer>
  );
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  // Açılışta adres çubuğundaki yola göre sayfa belirlenir; bilinmeyen yol
  // Worker tarafından zaten 404'e düşer, burada güvenlik amaçlı ana sayfa.
  const [route, setRoute] = React.useState(
    () => ROUTES.pathToRoute(window.location.pathname) || { page: "home" }
  );
  const projects = window.PROJECTS;

  // Intro splash plays on every page load.
  const [introDone, setIntroDone] = React.useState(false);
  const finishIntro = React.useCallback(() => {
    setIntroDone(true);
  }, []);

  const replayIntro = React.useCallback(() => {
    setIntroDone(false);
  }, []);

  // Sayfa geçişinde adres çubuğu da güncellenir (sayfa yenilenmeden)
  const navigate = React.useCallback((r) => {
    const path = ROUTES.routeToPath(r);
    if (path !== window.location.pathname) {
      window.history.pushState({}, "", path);
    }
    setRoute(r);
    window.scrollTo({ top: 0, behavior: "instant" });
  }, []);

  // Tarayıcının geri / ileri tuşları
  React.useEffect(() => {
    const onPop = () => {
      setRoute(ROUTES.pathToRoute(window.location.pathname) || { page: "home" });
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  // Her sayfanın kendi başlığı, açıklaması ve canonical adresi olsun
  React.useEffect(() => {
    ROUTES.applyMeta(route);
  }, [route]);

  // Apply theme + type attributes to <html>
  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", tweaks.theme);
    document.documentElement.setAttribute("data-type", tweaks.type);
  }, [tweaks.theme, tweaks.type]);

  // padding-left adjustment when side nav is active
  const navPadLeft = tweaks.nav === "side" ? 200 : 0;
  const navPadTop = tweaks.nav === "minimal" ? 0 : 0;

  let pageEl = null;
  if (route.page === "home") pageEl = <Home projects={projects} navigate={navigate} tweaks={tweaks} />;
  else if (route.page === "archive") pageEl = <Archive projects={projects} navigate={navigate} tweaks={tweaks} />;
  else if (route.page === "project") {
    const project = projects.find((p) => p.id === route.id);
    pageEl = <ProjectDetail project={project} projects={projects} navigate={navigate} />;
  }
  else if (route.page === "about") pageEl = <About projects={projects} navigate={navigate} />;
  else if (route.page === "contact") pageEl = <Contact navigate={navigate} />;

  return (
    <>
      {!introDone && <IntroSplash onDone={finishIntro} />}
      <Nav variant={tweaks.nav} route={route} navigate={navigate} introDone={introDone} />
      <div
        className="app-shell"
        style={{
          paddingLeft: navPadLeft,
          paddingTop: navPadTop,
          transition: "padding 240ms ease",
        }}
      >
        <main>{pageEl}</main>
        <Footer navigate={navigate} />
      </div>

      {SHOW_TWEAKS && (
      <TweaksPanel title="Tweaks · Görünüm">
        <TweakSection label="Tema">
          <TweakSelect
            label="Palet"
            value={tweaks.theme}
            onChange={(v) => setTweak("theme", v)}
            options={[
              { value: "cream", label: "Krem (sıcak)" },
              { value: "bone", label: "Kemik (nötr)" },
              { value: "stone", label: "Taş (yeşil)" },
              { value: "ink", label: "Mürekkep (koyu)" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Tipografi">
          <TweakSelect
            label="Pair"
            value={tweaks.type}
            onChange={(v) => setTweak("type", v)}
            options={[
              { value: "editorial", label: "Editorial · Instrument + Geist" },
              { value: "classic", label: "Klasik · Cormorant + Newsreader" },
              { value: "modern", label: "Modern · Geist + Geist" },
              { value: "brutalist", label: "Brutalist · Mono + Sans" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Navigasyon">
          <TweakRadio
            label="Stil"
            value={tweaks.nav}
            onChange={(v) => setTweak("nav", v)}
            options={[
              { value: "top", label: "Üst" },
              { value: "side", label: "Yan" },
              { value: "minimal", label: "Mini" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Ana sayfa Hero">
          <TweakSelect
            label="Layout"
            value={tweaks.hero}
            onChange={(v) => setTweak("hero", v)}
            options={[
              { value: "editorial", label: "Editorial — manifesto + görsel" },
              { value: "fullbleed", label: "Tam ekran görsel" },
              { value: "marquee", label: "Tipografik marquee" },
              { value: "index", label: "Tüm projeler grid" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Arşiv yoğunluğu">
          <TweakSelect
            label="Grid"
            value={tweaks.density}
            onChange={(v) => setTweak("density", v)}
            options={[
              { value: "sparse", label: "Seyrek (2 sütun)" },
              { value: "comfortable", label: "Rahat (3 sütun)" },
              { value: "dense", label: "Yoğun (4 sütun)" },
              { value: "list", label: "Liste" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Açılış animasyonu">
          <div style={{ padding: "0 12px 4px" }}>
            <button
              onClick={replayIntro}
              className="t-mono"
              style={{
                width: "100%",
                padding: "10px 14px",
                border: "1px solid var(--line)",
                borderRadius: 6,
                color: "var(--fg)",
                fontSize: 11,
                letterSpacing: "0.1em",
                textTransform: "uppercase",
                cursor: "pointer",
              }}
            >
              ↻ Açılışı yeniden oynat
            </button>
          </div>
        </TweakSection>
      </TweaksPanel>
      )}
    </>
  );
}

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