// app.jsx — Router + per-route SEO + tweaks + bootstrap.

const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "mood": "clinical",
  "accent": ["#409d70", "#2f7a55"],
  "rhythm": "regular"
}/*EDITMODE-END*/;

// Per-route SEO map (TR primary).
const SEO = {
  "/":          { title: "Hornpiper · Growth Architecture, GTM Strategy ve Growth Operations",
                  desc:  "Hornpiper, Demand · Conversion · Systems katmanlarını birlikte kuran bir growth architecture firmasıdır. Önce bottleneck teşhis edilir, sonra sistem kurulur." },
  "/solutions": { title: "Solutions · Demand · Conversion · Systems | Hornpiper",
                  desc:  "Üç katman · tek mimari. Hornpiper'ın Demand, Conversion ve Systems katmanlarında ne kurduğu, ne kırıldığı ve ne zaman başlamak gerektiği." },
  "/approach":  { title: "Approach · DDIO Methodology | Hornpiper",
                  desc:  "Hornpiper ile çalışmanın dört fazı: Diagnose, Design, Implement, Optimize. Müşteri her fazda neyi yaşar, neyi yazılı olarak alır." },
  "/products":  { title: "Products · Luna AI · Harvester · Kastelan | Hornpiper",
                  desc:  "Luna AI growth intelligence, Harvester first-party veri pipeline'ı, Kastelan attribution savunması. Üç üretim ürünü." },
  "/insights":  { title: "Insights · Engineering Log | Hornpiper",
                  desc:  "Yapısal analiz, GTM kararları ve sistem tasarımı üzerine yazılar. Tactical tip değildir." },
  "/about":     { title: "About · Hornpiper Growth Architecture Firm",
                  desc:  "Hornpiper, ajansların doldurmadığı yapısal boşluğu doldurur. Bir growth architecture firmasıdır. 2024'te Istanbul'da kuruldu." },
  "/contact":   { title: "Diagnose Intake · Bir Diagnose ile Başlayın | Hornpiper",
                  desc:  "Diagnose, 90 dakikalık yapısal bir incelemedir. Satış görüşmesi değil. 24 saat içinde yazılı yanıt verilir." },
};
function seoFor(route) {
  if (SEO[route]) return SEO[route];
  if (route.startsWith("/insights/")) {
    const slug = route.slice("/insights/".length);
    const e = (HP_DATA.insights.entries || []).find((x) => x.slug === slug);
    return e
      ? { title: `${e.title} · Insights | Hornpiper`, desc: e.sum }
      : SEO["/insights"];
  }
  if (route.startsWith("/products/")) return SEO["/products"];
  return SEO["/"];
}

function useSeo(route, lang) {
  useEffect(() => {
    const s = seoFor(route);
    document.title = s.title;
    setMeta("name", "description", s.desc);
    setMeta("property", "og:title", s.title);
    setMeta("property", "og:description", s.desc);
    setMeta("property", "og:url", `https://hornpiper.com${route === "/" ? "/" : route}`);
    setMeta("name", "twitter:title", s.title);
    setMeta("name", "twitter:description", s.desc);
    setCanonical(`https://hornpiper.com${route === "/" ? "/" : route}`);
    setJsonLd("hp-breadcrumb", breadcrumbJsonLd(route));
  }, [route, lang]);
}
function setMeta(attr, key, val) {
  let el = document.head.querySelector(`meta[${attr}="${key}"]`);
  if (!el) { el = document.createElement("meta"); el.setAttribute(attr, key); document.head.appendChild(el); }
  el.setAttribute("content", val || "");
}
function setCanonical(href) {
  let el = document.head.querySelector('link[rel="canonical"]');
  if (!el) { el = document.createElement("link"); el.setAttribute("rel", "canonical"); document.head.appendChild(el); }
  el.setAttribute("href", href);
}
function setJsonLd(id, data) {
  let el = document.getElementById(id);
  if (!el) { el = document.createElement("script"); el.id = id; el.type = "application/ld+json"; document.head.appendChild(el); }
  el.textContent = JSON.stringify(data);
}
function breadcrumbJsonLd(route) {
  const labels = { "/": "Home", "/solutions": "Solutions", "/approach": "Approach",
                   "/products": "Products", "/insights": "Insights",
                   "/about": "About", "/contact": "Contact" };
  const parts = route.split("/").filter(Boolean);
  const items = [{ name: "Home", url: "https://hornpiper.com/" }];
  let acc = "";
  parts.forEach((p) => {
    acc += "/" + p;
    items.push({ name: labels[acc] || p, url: `https://hornpiper.com${acc}` });
  });
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: items.map((it, i) => ({
      "@type": "ListItem", position: i + 1, name: it.name, item: it.url,
    })),
  };
}

const REDIRECTS = {
  "/growth-architecture": "/solutions",
  "/methodology":         "/approach",
  "/technology":          "/teknoloji",
  "/products":            "/teknoloji",
  "/faaliyet-alanlari":   "/industries",
  "/blog":                "/insights",
  "/forge":               "/insights",
  "/manifesto":           "/about",
  "/engagements":         "/approach",
  "/who-it-is-for":       "/about",
  "/work":                "/insights",
};
function applyRedirect(p) {
  if (REDIRECTS[p]) return REDIRECTS[p];
  if (p.startsWith("/blog/"))    return "/insights/" + p.slice("/blog/".length);
  if (p.startsWith("/forge/"))   return "/insights/" + p.slice("/forge/".length);
  if (p.startsWith("/work/"))    return "/insights";
  if (p.startsWith("/technology/")) return "/teknoloji";
  if (p.startsWith("/products/"))   return "/teknoloji";
  return null;
}

function useHashRoute() {
  const parse = () => {
    const h = window.location.hash.replace(/^#/, "") || "/";
    return h.startsWith("/") ? h : "/" + h;
  };
  const [route, setRoute] = useState(parse());
  useEffect(() => {
    const onHash = () => {
      const next = parse();
      const r = applyRedirect(next);
      if (r) { window.location.replace("#" + r); return; }
      setRoute(next);
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    onHash();
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const navigate = (path) => {
    const r = applyRedirect(path);
    window.location.hash = r || path;
  };
  return [route, navigate];
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, navigate] = useHashRoute();
  const [lang, setLang] = useState("tr");

  useEffect(() => { document.documentElement.lang = lang; }, [lang]);
  useSeo(route, lang);

  useEffect(() => {
    const root = document.documentElement;
    root.setAttribute("data-mood", t.mood);
    root.setAttribute("data-rhythm", t.rhythm);
    const [a, a2] = Array.isArray(t.accent) ? t.accent : [t.accent, t.accent];
    root.style.setProperty("--hp-gold", a);
    root.style.setProperty("--hp-gold-2", a2 || a);
  }, [t.mood, t.rhythm, t.accent]);

  let page;
  if (route === "/")               page = <HomePage lang={lang} navigate={navigate}/>;
  else if (route === "/solutions") page = <SolutionsPage lang={lang} navigate={navigate}/>;
  else if (route === "/approach")  page = <ApproachPage lang={lang} navigate={navigate}/>;
  else if (route === "/teknoloji") page = <ProductsPage lang={lang} navigate={navigate}/>;
  else if (route === "/industries")page = <SectorsPage lang={lang} navigate={navigate}/>;
  else if (route === "/insights")  page = <InsightsPage lang={lang} navigate={navigate}/>;
  else if (route.startsWith("/insights/")) page = <InsightDetail lang={lang} navigate={navigate} slug={route.slice("/insights/".length)}/>;
  else if (route === "/about")     page = <AboutPage lang={lang} navigate={navigate}/>;
  else if (route === "/contact")   page = <ContactPage lang={lang} navigate={navigate}/>;
  else if (route === "/privacy")   page = <PrivacyPage lang={lang} navigate={navigate}/>;
  else if (route === "/terms")     page = <TermsPage lang={lang} navigate={navigate}/>;
  else if (route === "/admin")     page = <AdminPage lang={lang} navigate={navigate}/>;
  else                             page = <NotFound lang={lang} navigate={navigate}/>;

  // Admin renders without header/footer chrome.
  if (route === "/admin") {
    return <div data-screen-label="Admin">{page}</div>;
  }

  return (
    <>
      <HpHeader route={route} navigate={navigate} lang={lang} setLang={setLang}/>
      {page}
      <HpFooter lang={lang} navigate={navigate}/>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Mood"/>
        <TweakRadio label="Register" value={t.mood}
                    options={["clinical", "editorial", "ops"]}
                    onChange={(v) => setTweak("mood", v)}/>
        <TweakSection label="Accent"/>
        <TweakColor label="Palette" value={t.accent}
                    options={[
                      ["#409d70", "#2f7a55"],
                      ["#e0c07f", "#c9a965"],
                      ["#e94f37", "#b53a26"],
                      ["#0f3e6d", "#0a2a4a"],
                      ["#f6f7eb", "#bbcbc6"],
                    ]}
                    onChange={(v) => setTweak("accent", v)}/>
        <TweakSection label="Rhythm"/>
        <TweakRadio label="Spacing" value={t.rhythm}
                    options={["compact", "regular", "spacious"]}
                    onChange={(v) => setTweak("rhythm", v)}/>
      </TweaksPanel>
    </>
  );
}

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