// app.jsx — Mounts Little Care Fund with mobile frame, desktop toggle, tweaks panel.

const PALETTE_PRESETS = {
  plum: {
    label: "Plum (default)",
    "--bg-1": "#D7DEDC", "--bg-2": "#CFCFCD", "--bg-3": "#E6EAE8",
    "--ink-soft": "#9A879D", "--ink-mid": "#7A3B69", "--ink-deep": "#563440",
    "--ink-text": "#2E1C26", "--ink-mute": "#6F5C6A",
  },
  mauve: {
    label: "Mauve forward",
    "--bg-1": "#D7DEDC", "--bg-2": "#CFCFCD", "--bg-3": "#E6EAE8",
    "--ink-soft": "#7A3B69", "--ink-mid": "#9A879D", "--ink-deep": "#563440",
    "--ink-text": "#2E1C26", "--ink-mute": "#6F5C6A",
  },
  aubergine: {
    label: "Aubergine deep",
    "--bg-1": "#D7DEDC", "--bg-2": "#CFCFCD", "--bg-3": "#E6EAE8",
    "--ink-soft": "#9A879D", "--ink-mid": "#563440", "--ink-deep": "#2E1C26",
    "--ink-text": "#1f1218", "--ink-mute": "#6F5C6A",
  },
};

const TYPE_PRESETS = {
  newsreader: { label: "Newsreader · Manrope", display: '"Newsreader", Georgia, serif', sans: '"Manrope", system-ui, sans-serif' },
  dmserif:    { label: "DM Serif · DM Sans",    display: '"DM Serif Display", Georgia, serif', sans: '"DM Sans", system-ui, sans-serif' },
  lora:       { label: "Lora · Plus Jakarta",   display: '"Lora", Georgia, serif', sans: '"Plus Jakarta Sans", system-ui, sans-serif' },
};

const HERO_PRESETS = {
  portrait: "Portrait + story",
  split:    "Split (card)",
  quiet:    "Quiet headline",
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "plum",
  "type": "newsreader",
  "hero": "portrait",
  "device": "desktop",
  "logo": "brand"
}/*EDITMODE-END*/;

const LOGO_PRESETS = {
  brand: "Official mark",
  cup:   "Cupped hands",
  bowl:  "Heart on bowl",
  palms: "Two open palms",
  lift:  "Lifting hands",
  nest:  "Heart in nest",
};

function applyTokens(t) {
  const root = document.documentElement;
  const pal = PALETTE_PRESETS[t.palette] || PALETTE_PRESETS.plum;
  Object.entries(pal).forEach(([k, v]) => { if (k.startsWith("--")) root.style.setProperty(k, v); });
  const tp = TYPE_PRESETS[t.type] || TYPE_PRESETS.newsreader;
  root.style.setProperty("--font-display", tp.display);
  root.style.setProperty("--font-sans", tp.sans);
}

function PageInner({ route, logo, heroVariant, onOpenCampaign, onOpenStory, onNavigate, onBack, onBackFromStory, navOpen, setNavOpen }) {
  return (
    <div style={{
      background: "var(--bg-1)",
      minHeight: "100%", color: "var(--ink-text)",
      fontFamily: "var(--font-sans)", position: "relative",
    }}>
      <TopBar
        key={logo}
        onMenu={() => setNavOpen(true)}
        onBack={route.page === "campaign" || route.page === "stories" || route.page === "story" || route.page === "about" || route.page === "faq" || route.page === "contact" || route.page === "find" || route.page === "donate" ? onBack : null}
        title={route.page === "campaign" ? CAMPAIGNS.find(c => c.id === route.id)?.name : route.page === "stories" ? "Stories" : route.page === "story" ? (STORY_ARTICLES.find(s => s.id === route.id)?.name || "Story") : route.page === "about" ? "About" : route.page === "faq" ? "FAQ" : route.page === "contact" ? "Contact" : route.page === "find" ? "Find a Child" : route.page === "donate" ? "Donate" : null}
      />
      {route.page === "home" && (
        <HomePage onOpenCampaign={onOpenCampaign} onNavigate={onNavigate} onOpenStory={onOpenStory} heroVariant={heroVariant} />
      )}
      {route.page === "campaign" && (
        <CampaignPage campaignId={route.id} onBack={onBack} onOpenCampaign={onOpenCampaign} onNavigate={onNavigate} />
      )}
      {route.page === "stories" && (
        <StoriesPage onOpenStory={onOpenStory} onNavigate={onNavigate} />
      )}
      {route.page === "story" && (
        <StoryDetailPage storyId={route.id} onBack={onBackFromStory} onNavigate={onNavigate} />
      )}
      {route.page === "about" && (
        <AboutPage onNavigate={onNavigate} />
      )}
      {route.page === "faq" && (
        <FaqPage onNavigate={onNavigate} />
      )}
      {route.page === "contact" && (
        <ContactPage onNavigate={onNavigate} />
      )}
      {route.page === "find" && (
        <FindPage onOpenCampaign={onOpenCampaign} onNavigate={onNavigate} />
      )}
      {route.page === "donate" && (
        <DonatePage onNavigate={onNavigate} onBack={onBack} />
      )}
      <NavMenu open={navOpen} onClose={() => setNavOpen(false)} onNavigate={onNavigate} />
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = React.useState({ page: "home" });
  const [navOpen, setNavOpen] = React.useState(false);
  const [vw, setVw] = React.useState(window.innerWidth);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    const onResize = () => setVw(window.innerWidth);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  React.useEffect(() => { applyTokens(t); window.__logoVariant = t.logo; }, [t.palette, t.type, t.logo]);

  // Seed initial history entry and handle device back button
  React.useEffect(() => {
    history.replaceState({ page: "home" }, "");
    const onPopState = (e) => {
      setRoute(e.state || { page: "home" });
    };
    window.addEventListener("popstate", onPopState);
    return () => window.removeEventListener("popstate", onPopState);
  }, []);

  React.useLayoutEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [route.page, route.id]);

  const navigate = (newRoute) => {
    setRoute(newRoute);
    history.pushState(newRoute, "");
  };

  const onOpenCampaign = (id) => navigate({ page: "campaign", id });
  const onOpenStory = (id) => navigate({ page: "story", id });
  const onNavigate = (id) => {
    if (id === "home") navigate({ page: "home" });
    else if (id === "find") navigate({ page: "find" });
    else if (id === "stories") navigate({ page: "stories" });
    else if (id === "about") navigate({ page: "about" });
    else if (id === "faq") navigate({ page: "faq" });
    else if (id === "contact") navigate({ page: "contact" });
    else if (id === "donate") navigate({ page: "donate" });
    else navigate({ page: "home", anchor: id });
  };
  const onBack = () => history.back();
  const onBackFromStory = () => history.back();

  const isWide = vw >= 768;

  const pageKey = route.page + (route.id || "");
  const pageContent = (
    <PageInner
      key={pageKey}
      route={route}
      logo={t.logo}
      heroVariant={t.hero}
      onOpenCampaign={onOpenCampaign}
      onOpenStory={onOpenStory}
      onNavigate={onNavigate}
      onBack={onBack}
      onBackFromStory={onBackFromStory}
      navOpen={navOpen}
      setNavOpen={setNavOpen}
    />
  );

  return (
    <div
      ref={scrollRef}
      className={isWide ? "live-desktop" : ""}
      style={{
        position: "fixed",
        inset: 0,
        overflowY: "auto",
        overflowX: "hidden",
        background: "var(--bg-1)",
        color: "var(--ink-text)",
        fontFamily: "var(--font-sans)",
        WebkitOverflowScrolling: "touch",
      }}
    >
      {isWide ? (
        <DesktopShell onNavigate={onNavigate}>{pageContent}</DesktopShell>
      ) : (
        pageContent
      )}
    </div>
  );
}

// Phone frame — wraps PageContent in iOS device + adds scroll
function PhoneFrame({ children }) {
  return (
    <div style={{ filter: "drop-shadow(0 30px 60px rgba(0,0,0,0.35))" }}>
      <IOSDevice width={402} height={874}>
        <div className="hfm-scroll" style={{ height: "100%", overflowY: "auto", overflowX: "hidden", paddingTop: 44 /* status bar room */, paddingBottom: 0 }}>
          {children}
        </div>
      </IOSDevice>
    </div>
  );
}

// Desktop frame — browser chrome
function DesktopFrame({ children, onNavigate }) {
  return (
    <div className="desktop-frame">
      <div className="desktop-chrome">
        <div className="desktop-dot" style={{ background: "#FF5F57" }} />
        <div className="desktop-dot" style={{ background: "#FEBC2E" }} />
        <div className="desktop-dot" style={{ background: "#28C840" }} />
        <div className="desktop-url">littlecarefund.org</div>
      </div>
      <div className="hfm-scroll" style={{ height: "calc(100% - 36px)", overflowY: "auto" }}>
        <DesktopShell onNavigate={onNavigate}>{children}</DesktopShell>
      </div>
    </div>
  );
}

// Lightweight desktop shell: top nav + content max-width.
// Reuses the same mobile sections — they look fine in a 760-820px column.
function DesktopShell({ children, onNavigate }) {
  return (
    <div style={{ background: "var(--bg-1)" }}>
      {/* Desktop top nav overlay */}
      <div
        className="desktop-topbar"
        style={{
          position: "sticky",
          top: 0,
          zIndex: 20,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "0 48px",
          height: "76px",
          overflow: "hidden",
          background: "rgba(215,222,220,0.85)",
          backdropFilter: "blur(12px) saturate(140%)",
          WebkitBackdropFilter: "blur(12px) saturate(140%)",
          borderBottom: "1px solid var(--line)"
        }}
      >
        <button onClick={() => onNavigate("home")} style={{ background: "none", border: 0, padding: 0, cursor: "pointer", display: "flex" }}>
          <Logo size={2.332} />
        </button>

        <nav style={{ display: "flex", gap: 28 }}>
          {[
            { label: "Home", id: "home" },
            { label: "Find a child", id: "find" },
            { label: "Stories", id: "stories" },
            { label: "About", id: "about" },
            { label: "FAQ", id: "faq" },
          ].map((item) => (
            <a
              key={item.id}
              href="#"
              onClick={(e) => { e.preventDefault(); onNavigate(item.id); }}
              style={{
                fontSize: 14,
                fontWeight: 500,
                color: "var(--ink-deep)",
                textDecoration: "none",
                letterSpacing: "-0.005em"
              }}
            >
              {item.label}
            </a>
          ))}
        </nav>

        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn--primary btn--sm" onClick={() => onNavigate("contact")}>Contact us</button>
        </div>
      </div>

      {/* Desktop-only layout rules — applied inside the preview frame (.desktop-frame)
          and in live desktop mode (.live-desktop) */}
      <style>{`
        .desktop-frame .mobile-topbar,
        .desktop-frame .mobile-nav-menu,
        .live-desktop .mobile-topbar,
        .live-desktop .mobile-nav-menu {
          display: none !important;
        }

        .desktop-frame .hfm-scroll > div,
        .live-desktop .hfm-scroll > div {
          padding-top: 0 !important;
        }

        .desktop-frame .campaigns-grid,
        .live-desktop .campaigns-grid {
          display: grid !important;
          grid-template-columns: repeat(3, 1fr) !important;
          gap: 22px !important;
        }

        .desktop-frame .stories-grid,
        .live-desktop .stories-grid {
          display: grid !important;
          grid-template-columns: repeat(2, 1fr) !important;
          gap: 28px !important;
        }

        .desktop-frame .hero-desc-overlay,
        .live-desktop .hero-desc-overlay {
          display: block !important;
        }

        .live-desktop .hero-desc-overlay {
          padding-left:  max(48px, calc((100vw - 1200px) / 2)) !important;
          padding-right: max(48px, calc((100vw - 1200px) / 2)) !important;
        }
        .desktop-frame .hero-desc-below,
        .live-desktop .hero-desc-below {
          display: none !important;
        }

        .desktop-frame .newsletter-form,
        .live-desktop .newsletter-form {
          flex-direction: row !important;
          align-items: center !important;
        }
        .desktop-frame .newsletter-form input,
        .live-desktop .newsletter-form input {
          width: auto !important;
          flex: 1 !important;
        }
        .desktop-frame .newsletter-form button,
        .live-desktop .newsletter-form button {
          width: auto !important;
          white-space: nowrap !important;
        }

        .desktop-frame .hero-actions,
        .live-desktop .hero-actions {
          flex-direction: row !important;
          align-items: center !important;
          gap: 28px !important;
        }
        .desktop-frame .hero-donate,
        .live-desktop .hero-donate {
          flex: 0 0 auto;
          padding-top: 0;
        }
        .desktop-frame .hero-donate-btn,
        .live-desktop .hero-donate-btn {
          white-space: nowrap;
        }
        .desktop-frame .hero-newsletter,
        .live-desktop .hero-newsletter {
          flex: 1;
          border-top: none !important;
          border-left: 1px solid var(--line);
          padding-top: 0 !important;
          margin-top: 0 !important;
          padding-left: 28px;
        }

        /* Preview frame: fixed 80px gutters inside the 1280px box */
        .desktop-frame section {
          padding-left: 80px !important;
          padding-right: 80px !important;
        }

        /* Live desktop: auto-center content at 1200px max, 48px min gutter */
        .live-desktop section {
          padding-left:  max(48px, calc((100vw - 1200px) / 2)) !important;
          padding-right: max(48px, calc((100vw - 1200px) / 2)) !important;
        }

        .live-desktop footer {
          padding-left:  max(48px, calc((100vw - 1200px) / 2)) !important;
          padding-right: max(48px, calc((100vw - 1200px) / 2)) !important;
        }

        .live-desktop .desktop-topbar {
          padding-left:  max(48px, calc((100vw - 1200px) / 2)) !important;
          padding-right: max(48px, calc((100vw - 1200px) / 2)) !important;
        }

        .desktop-frame .about-principles-grid,
        .live-desktop .about-principles-grid {
          display: grid !important;
          grid-template-columns: repeat(3, 1fr) !important;
          gap: 20px !important;
        }

        .desktop-frame .about-founder-layout,
        .live-desktop .about-founder-layout {
          flex-direction: row !important;
          align-items: flex-start !important;
          gap: 48px !important;
        }

        .desktop-frame .about-founder-img,
        .live-desktop .about-founder-img {
          width: 340px !important;
          flex-shrink: 0 !important;
        }

        .desktop-frame .about-founder-img img,
        .live-desktop .about-founder-img img {
          max-height: none !important;
        }

        .desktop-frame .contact-layout,
        .live-desktop .contact-layout {
          flex-direction: row !important;
          align-items: flex-start !important;
          gap: 56px !important;
        }

        .desktop-frame .contact-form-col,
        .live-desktop .contact-form-col {
          flex: 1 !important;
          min-width: 0 !important;
        }

        .desktop-frame .contact-info-col,
        .live-desktop .contact-info-col {
          width: 320px !important;
          flex-shrink: 0 !important;
        }

        .desktop-frame .contact-name-email,
        .live-desktop .contact-name-email {
          flex-direction: row !important;
          gap: 16px !important;
        }

        .live-desktop .hero-intro-block {
          padding-left:  max(48px, calc((100vw - 1200px) / 2)) !important;
          padding-right: max(48px, calc((100vw - 1200px) / 2)) !important;
        }

        .live-desktop .hero-img-wrap {
          height: 600px !important;
        }
      `}</style>

      {children}
    </div>
  );
}

// Visual logo picker — 2x2 grid of mark previews
function LogoPreviewRow({ value, onChange }) {
  const opts = [
    { k: "brand", l: "Official" },
    { k: "cup",   l: "Cupped hands" },
    { k: "bowl",  l: "Heart on bowl" },
    { k: "palms", l: "Two palms" },
    { k: "lift",  l: "Lifting" },
    { k: "nest",  l: "Heart in nest" },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
      {opts.map(o => (
        <button key={o.k} onClick={() => onChange(o.k)}
          style={{
            border: value === o.k ? "1.5px solid rgba(0,0,0,0.55)" : "0.5px solid rgba(0,0,0,0.15)",
            background: value === o.k ? "rgba(255,255,255,0.95)" : "rgba(255,255,255,0.55)",
            borderRadius: 8, padding: "10px 8px 8px",
            display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
            cursor: "default", color: "inherit", font: "inherit",
          }}>
          <LogoMark variant={o.k} color="#563440" accent="#FBF7F4" size={30} />
          <span style={{ fontSize: 10.5, color: "rgba(41,38,27,0.7)", textAlign: "center" }}>{o.l}</span>
        </button>
      ))}
    </div>
  );
}

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