// app.jsx — root app, routing, theming, tweaks panel

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "direction": "sunny",
  "palette": ["#FF7A4A", "#FFD27A", "#FAF4EC"],
  "headline": "price",
  "heroLayout": "split",
  "density": "regular",
  "dark": false,
  "fontPair": "auto",
  "accent": "sand"
}/*EDITMODE-END*/;

// Accent band: a few alternates for the bg-3 "feature" section tone.
// Each option has a representative swatch shown in the Tweaks panel.
const ACCENT_OPTIONS = [
  { key: "sand",  hex: "#EDDDB6" }, // warm sandy cream (default)
  { key: "sage",  hex: "#D9DECC" }, // soft desaturated green-gray
  { key: "mist",  hex: "#D7DEE7" }, // cool blue-gray
  { key: "peach", hex: "#F2D7C2" }, // primary-tinted blush
  { key: "stone", hex: "#DCD7CE" }, // warm neutral putty
  { key: "ink",   hex: "#231C16" }, // dark dramatic slab
];
const ACCENT_HEX_TO_KEY = Object.fromEntries(ACCENT_OPTIONS.map((o) => [o.hex, o.key]));

// Direction → palette presets (for the palette tweak)
const DIRECTION_PRESETS = {
  sunny:  ["#FF7A4A", "#FFD27A", "#FAF4EC"],
  citrus: ["#A8E63A", "#1F2A14", "#FAF8F0"],
  sky:    ["#5F8DEF", "#B49CE8", "#F2F5FB"],
};

// Calendly popup URL — single source of truth for every "Book a demo" button.
const CALENDLY_URL = "https://calendly.com/99-social-demo-call/99-social-demo-call?hide_gdpr_banner=1&primary_color=ff9900";
const PAGES = ["home","services","pricing","about","contact","examples","careers","social-media-reseller-program","social-media-management","instagram-growth","seo-blog-articles","short-form-video","policy","schedule-a-call","call-confirmed"];

// Pages that should appear as clean pathname URLs (e.g. /social-media-management)
// rather than hash routes. Anything not in this set keeps the existing hash-based flow.
const PATH_PAGES = new Set(["social-media-management", "instagram-growth", "seo-blog-articles", "short-form-video"]);

// Read the current page from either the path or the hash. Path wins.
function pageFromLocation() {
  const path = window.location.pathname.replace(/\/+$/, "").split("/").pop();
  if (path && PATH_PAGES.has(path) && PAGES.includes(path)) return path;
  const h = window.location.hash.replace("#", "");
  if (PAGES.includes(h)) return h;
  return "home";
}

// Trigger the Calendly popup widget. Falls back to opening the URL in a new tab
// if the widget script hasn't loaded yet (rare — script is in <head>).
function openCalendly() {
  if (window.Calendly && typeof window.Calendly.initPopupWidget === "function") {
    window.Calendly.initPopupWidget({ url: CALENDLY_URL });
    return false;
  }
  window.open(CALENDLY_URL, "_blank", "noopener");
  return false;
}
window.openCalendly = openCalendly;

function useTweaks(defaults) {
  const [values, setValues] = React.useState(defaults);
  const setTweak = React.useCallback(() => {}, []);
  return [values, setTweak];
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [page, setPage] = React.useState(() => pageFromLocation());
  const [modalOpen, setModalOpen] = React.useState(false);
  // "Get started" buttons site-wide go straight to checkout.
  const openSignup = () => { window.location.href = "https://clients.99dollarsocial.com/order/checkout"; };
  // "Book a demo" now navigates to the dedicated /schedule-a-call page.
  const openDemo = () => { goto("schedule-a-call"); };

  // Expose a global so the Logo link doesn't need to thread through props
  React.useEffect(() => { window.__nav = (p) => goto(p); }, [page]);

  const goto = (p) => {
    setPage(p);
    if (PATH_PAGES.has(p)) {
      // Pretty-path route: push pathname, clear hash.
      const base = window.location.pathname.replace(/\/[^/]*$/, "/");
      try {
        window.history.pushState({}, "", base + p);
      } catch (e) {
        window.location.hash = p;
      }
    } else {
      // If we were on a pretty path, return to the index before setting hash.
      const curPath = window.location.pathname.replace(/\/+$/, "").split("/").pop();
      if (PATH_PAGES.has(curPath)) {
        const base = window.location.pathname.replace(/\/[^/]*$/, "/");
        try { window.history.pushState({}, "", base + (p === "home" ? "" : "#" + p)); }
        catch (e) { window.location.hash = p; }
      } else {
        window.location.hash = p;
      }
    }
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  // React to hash + path changes (back/forward)
  React.useEffect(() => {
    const sync = () => setPage(pageFromLocation());
    window.addEventListener("hashchange", sync);
    window.addEventListener("popstate", sync);
    return () => {
      window.removeEventListener("hashchange", sync);
      window.removeEventListener("popstate", sync);
    };
  }, []);

  // Apply theming via data-* attrs on body so CSS vars switch.
  React.useEffect(() => {
    document.body.dataset.dir = t.direction;
    document.body.dataset.theme = t.dark ? "dark" : "light";
    document.body.dataset.density = t.density;
    document.body.dataset.heroLayout = t.heroLayout;
    document.body.dataset.accent = t.accent || "sand";
  }, [t.direction, t.dark, t.density, t.heroLayout, t.accent]);

  // Switching direction via palette: changing the palette chip changes direction
  const setPalette = (p) => {
    setTweak("palette", p);
    const matchedDir = Object.keys(DIRECTION_PRESETS).find(
      (k) => JSON.stringify(DIRECTION_PRESETS[k]) === JSON.stringify(p),
    );
    if (matchedDir) setTweak("direction", matchedDir);
  };

  const setDirection = (d) => {
    setTweak("direction", d);
    setTweak("palette", DIRECTION_PRESETS[d]);
  };

  return (
    <>
      <Nav page={page} onNav={goto} onOpenModal={openSignup} onBookDemo={openDemo} />

      {page === "home"     && <HomePage    headlineKey={t.headline} onOpenModal={openSignup} onBookDemo={openDemo} onNav={goto} />}
      {page === "services" && <ServicePage onOpenModal={openSignup} onBookDemo={openDemo} />}
      {page === "pricing"  && <PricingPage onOpenModal={openSignup} onBookDemo={openDemo} />}
      {page === "about"    && <AboutPage   onOpenModal={openSignup} onBookDemo={openDemo} />}
      {page === "contact"  && <ContactPage onOpenModal={openSignup} onBookDemo={openDemo} />}
      {page === "examples" && <ExamplesPage onOpenModal={openSignup} onBookDemo={openDemo} />}
      {page === "policy"   && <PolicyPage  onOpenModal={openSignup} onBookDemo={openDemo} onNav={goto} />}
      {page === "careers"  && <CareersPage onOpenModal={openSignup} onBookDemo={openDemo} onNav={goto} />}
      {page === "social-media-reseller-program" && <ResellerPage onOpenModal={openSignup} onBookDemo={openDemo} onNav={goto} />}
      {page === "social-media-management" && <SocialMediaManagementPage onOpenModal={openSignup} onBookDemo={openDemo} onNav={goto} />}
      {page === "instagram-growth" && <InstagramGrowthPage onOpenModal={openSignup} onBookDemo={openDemo} onNav={goto} />}
      {page === "seo-blog-articles" && <SeoBlogPage onOpenModal={openSignup} onBookDemo={openDemo} onNav={goto} />}
      {page === "short-form-video" && <ShortFormVideoPage onOpenModal={openSignup} onBookDemo={openDemo} onNav={goto} />}
      {page === "schedule-a-call" && <SchedulePage    onOpenModal={openSignup} onBookDemo={openDemo} onNav={goto} />}
      {page === "call-confirmed"  && <CallConfirmedPage onOpenModal={openSignup} onBookDemo={openDemo} onNav={goto} />}

      <Footer onNav={goto} />

      <StickyCTA onOpenModal={openSignup} />
      <SignupModal open={modalOpen} onClose={() => setModalOpen(false)} onBookDemo={openDemo} />
    </>
  );
}

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