// app.jsx — HOTMESS commercial layer (v2)
// Repositions HOTMESS as the live queer signal layer for partner conversion.

const GOLD_PRESETS = {
  brand: "#C8962C",
  bright: "#F2C24A",
  dark: "#8E6A1F",
  desat: "#A09682",
};

// ── Host-aware audience routing ───────────────────────────────
// World Doctrine (shared) + Emotional Entry (join.) + Infrastructure Entry (founders.)
// founders.* -> "founders"; everything else (join., vercel, local) -> "join".
const HM_SITE = (function () {
  try {
    var h = (window.location.hostname || "").toLowerCase();
    return h.indexOf("founders.") === 0 ? "founders" : "join";
  } catch (e) { return "join"; }
})();
const IS_JOIN = HM_SITE === "join";
const IS_FOUNDERS = HM_SITE === "founders";
const EDIT_MODE = (function () { try { return new URLSearchParams(window.location.search).get("edit") === "1"; } catch (e) { return false; } })();

function App() {
  const [t, setTweak] = useTweaks(window.HM_TWEAK_DEFAULTS || {
    goldIntensity: "brand",
    showWorldStates: true,
    showLiveProof: true,
    showHNH: true,
    showMembers: true,
  });

  // Apply gold to CSS variable
  React.useEffect(() => {
    const c = GOLD_PRESETS[t.goldIntensity] || GOLD_PRESETS.brand;
    document.documentElement.style.setProperty("--gold", c);
  }, [t.goldIntensity]);

  // ── Chapters: break the long scroll into short pages ──────────
  const CH = ["The World", "The Night", "Connection", "Care & Sound", "Story & Join"];
  const [chapter, setChapter] = React.useState(() => {
    try { const m = (window.location.hash.match(/ch=(\d)/) || [])[1]; return m ? Math.min(4, Math.max(0, +m)) : 0; }
    catch (e) { return 0; }
  });
  const go = (n) => {
    setChapter(n);
    try { window.history.replaceState(null, "", "#ch=" + n); } catch (e) {}
    try { window.scrollTo({ top: 0, behavior: "instant" }); } catch (e) { window.scrollTo(0, 0); }
  };

  return (
    <>
      <NavV2 />
      <ChapterNav chapter={chapter} go={go} labels={CH} />
      {chapter === 0 && <HeroV2 variant={IS_FOUNDERS ? "founders" : "join"} />}

      {/* CH0 · The World — what HOTMESS is */}
      {chapter === 0 && (<>
        {IS_JOIN && <HookSection />}
        <NightOnHotmessSection />
        <EcosystemSection />
        {IS_JOIN && <WhoItsForSection />}
      </>)}

      {/* CH1 · The Night — how the city moves */}
      {chapter === 1 && (<>
        <DifferenceSection />
        <SignalTypesSection />
        <PulseSectionV2 />
        {t.showWorldStates && <WorldStatesSection />}
        {IS_FOUNDERS && <WhyPartnersSection />}
      </>)}

      {/* CH2 · Connection — presence & mutuality */}
      {chapter === 2 && (<>
        <GhostedSection variant={HM_SITE} />
        <AmbientSection />
        <DispatchesSection variant={HM_SITE} />
      </>)}

      {/* CH3 · Care & Sound — the moat + radio */}
      {chapter === 3 && (<>
        <CareInfraSection variant={HM_SITE} />
        <SoundOfCitySection />
        {t.showHNH && IS_JOIN && <HNHMessSection />}
        <TrustSection />
        {IS_FOUNDERS && <TapPackV2 />}
        {t.showLiveProof && IS_FOUNDERS && <LiveProofSection />}
        {IS_FOUNDERS && <FoundingTiersV2 />}
        {IS_FOUNDERS && <CityRolloutSection />}
      </>)}

      {/* CH4 · Story & Join — why now, founder, join */}
      {chapter === 4 && (<>
        <WhyNowSection />
        <Dedication />
        <FounderNote />
        <FAQSection variant={HM_SITE} />
        {IS_FOUNDERS && <ConversionSection />}
        {t.showMembers && IS_JOIN && <MembersSection />}
      </>)}

      <ChapterPager chapter={chapter} go={go} labels={CH} />

      <Footer />

      {/* Signal Bot — bottom-left, chat widget trained on HOTMESS doctrine */}
      <SignalBot />

      {/* Floating WhatsApp — in-site contact dock (stays on site) */}
      <WhatsAppDock />

      {EDIT_MODE && <TweaksPanel>
        <TweakSection label="Gold accent" />
        <TweakColor
          label="Intensity"
          value={GOLD_PRESETS[t.goldIntensity] || GOLD_PRESETS.brand}
          options={[GOLD_PRESETS.brand, GOLD_PRESETS.bright, GOLD_PRESETS.dark, GOLD_PRESETS.desat]}
          onChange={(v) => {
            const key = Object.keys(GOLD_PRESETS).find((k) => GOLD_PRESETS[k] === v) || "brand";
            setTweak("goldIntensity", key);
          }}
        />

        <TweakSection label="Optional sections" />
        <TweakToggle label="World States" value={t.showWorldStates} onChange={(v) => setTweak("showWorldStates", v)} />
        <TweakToggle label="Live Proof"   value={t.showLiveProof}   onChange={(v) => setTweak("showLiveProof",   v)} />
        <TweakToggle label="HNH MESS"     value={t.showHNH}         onChange={(v) => setTweak("showHNH",         v)} />
        <TweakToggle label="Members"      value={t.showMembers}     onChange={(v) => setTweak("showMembers",     v)} />
      </TweaksPanel>}
    </>
  );
}

// ── Chapter navigation: turns the long scroll into short pages ──
function ChapterNav({ chapter, go, labels }) {
  return (
    <div style={{ position: "sticky", top: 0, zIndex: 45, background: "var(--bg)", borderBottom: "1px solid var(--line)" }}>
      <div className="wrap" style={{ display: "flex", gap: 6, padding: "12px 0", overflowX: "auto", WebkitOverflowScrolling: "touch" }}>
        {labels.map((l, i) => (
          <button
            key={i}
            type="button"
            onClick={() => go(i)}
            className="mono"
            style={{
              whiteSpace: "nowrap", padding: "9px 13px", cursor: "pointer",
              border: "1px solid " + (i === chapter ? "var(--gold)" : "var(--line)"),
              color: i === chapter ? "var(--bg)" : "var(--ink-2)",
              background: i === chapter ? "var(--gold)" : "transparent",
              fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase",
            }}
          >
            <span style={{ opacity: 0.6 }}>{String(i + 1).padStart(2, "0")}</span>&nbsp; {l}
          </button>
        ))}
      </div>
    </div>
  );
}

function ChapterPager({ chapter, go, labels }) {
  const last = labels.length - 1;
  return (
    <div className="wrap" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, padding: "56px 0 88px" }}>
      {chapter > 0
        ? <button type="button" onClick={() => go(chapter - 1)} className="btn btn-ghost">← {labels[chapter - 1]}</button>
        : <span />}
      {chapter < last
        ? <button type="button" onClick={() => go(chapter + 1)} className="btn btn-solid">{labels[chapter + 1]} →</button>
        : <a href="/members" className="btn btn-solid">Claim your spot →</a>}
    </div>
  );
}

// Updated nav for v2 IA — with mobile hamburger
function NavV2() {
  const [open, setOpen] = React.useState(false);
  return (
    <header className="nav">
      <div className="nav-inner" style={{ position: "relative" }}>
        <a href="#top" aria-label="HOTMESS home">
          <Wordmark />
        </a>
        <nav className={`nav-links${open ? " open" : ""}`} onClick={() => setOpen(false)}>
          <a href={IS_FOUNDERS ? "#why-now" : "#why"}>Why</a>
          <a href="#night">Night</a>
          <a href="#what">What</a>
          {IS_JOIN && <a href="#who" className="nav-tertiary">Who</a>}
          <a href="#signals">Signals</a>
          <a href="#pulse">Pulse</a>
          {IS_JOIN && <a href="#ghosted" className="nav-tertiary">Ghosted</a>}
          {IS_FOUNDERS && <a href="#why-partners" className="nav-secondary">Why join</a>}
          <a href="#care">Care</a>
          <a href="#sound">Sound</a>
          {IS_FOUNDERS && <a href="#partners">Tiers</a>}
          {IS_JOIN && <a href="#members" className="nav-tertiary">Wave</a>}
          <a href="#faq" className="nav-tertiary">FAQ</a>
          {IS_JOIN
            ? <a href="/members" className="nav-cta-mobile">Claim your spot ↗</a>
            : <a href="#conversion" className="nav-cta-mobile">Become a partner ↗</a>}
        </nav>
        {IS_JOIN
          ? <a href="/members" className="nav-cta">Claim your spot ↗</a>
          : <a href="#conversion" className="nav-cta">Become a partner ↗</a>}
        <button
          type="button"
          className={`nav-mobile-toggle${open ? " open" : ""}`}
          aria-label={open ? "Close menu" : "Open menu"}
          aria-expanded={open}
          onClick={() => setOpen((v) => !v)}
        ><span></span></button>
      </div>
    </header>
  );
}

function WhatsAppDock() {
  const [open, setOpen] = React.useState(false);
  return (
    <>
      {open && (
        <div role="dialog" aria-label="WhatsApp Direct" style={{
          position: "fixed", right: "clamp(16px, 3vw, 28px)", bottom: "clamp(84px, 11vw, 96px)",
          width: "min(320px, calc(100vw - 32px))", zIndex: 71,
          background: "var(--bg, #050507)", border: "1px solid var(--line, rgba(255,255,255,0.14))",
          boxShadow: "0 24px 70px rgba(0,0,0,0.55)", padding: "20px 20px 18px",
        }}>
          <div className="mono" style={{ color: "#25D366", letterSpacing: "0.16em", fontSize: 11, display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#25D366", display: "inline-block" }}></span>
            WHATSAPP DIRECT
          </div>
          <p className="serif" style={{ fontSize: 21, lineHeight: 1.15, color: "var(--ink, #fff)", margin: "14px 0 6px" }}>Real operator. Real number.</p>
          <p style={{ fontSize: 13, color: "var(--ink-2, #c9c4bb)", lineHeight: 1.55, margin: "0 0 14px" }}>Phil reads messages personally.</p>
          <div className="mono" style={{ fontSize: 11, color: "var(--ink-3, #8a8a8a)", lineHeight: 2.0, letterSpacing: 0, textTransform: "none" }}>
            For:<br/>&middot; partnerships<br/>&middot; venues<br/>&middot; city conversations<br/>&middot; Radio<br/>&middot; recovery<br/>&middot; signal questions
          </div>
          <a href="https://wa.me/447457404159?text=Hi%20HOTMESS%20%E2%80%94" target="_blank" rel="noreferrer"
             style={{ display: "block", textAlign: "center", marginTop: 16, padding: "12px", background: "#25D366", color: "#04210f", fontWeight: 700, letterSpacing: "0.1em", fontSize: 12, textDecoration: "none" }}>
            OPEN WHATSAPP
          </a>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-4, #6a6a6a)", marginTop: 10, textAlign: "center" }}>07457 404159 &middot; you choose when to leave</div>
        </div>
      )}
      <button type="button" aria-label="WhatsApp HOTMESS" aria-expanded={open} onClick={() => setOpen((v) => !v)} style={{
        position: "fixed", right: "clamp(16px, 3vw, 28px)", bottom: "clamp(16px, 3vw, 28px)",
        width: 56, height: 56, borderRadius: "50%", border: "none", cursor: "pointer",
        background: "#25D366", display: "flex", alignItems: "center", justifyContent: "center",
        boxShadow: "0 10px 30px rgba(37,211,102,0.4), 0 0 0 1px rgba(0,0,0,0.2)", zIndex: 70, transition: "transform .2s ease",
      }} onMouseEnter={(e) => { e.currentTarget.style.transform = "scale(1.08)"; }} onMouseLeave={(e) => { e.currentTarget.style.transform = "scale(1)"; }}>
        <svg width="28" height="28" viewBox="0 0 24 24" fill="#fff" aria-hidden="true"><path d="M17.6 14.2c-.3-.1-1.7-.8-2-.9s-.5-.1-.7.1-.8.9-1 1.1-.4.2-.7.1c-.3-.1-1.2-.5-2.3-1.4-.9-.7-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.4.4-.5.1-.2.2-.3.3-.5s0-.4 0-.5-.7-1.7-1-2.3c-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.7.4-.3.3-1 1-1 2.4s1 2.8 1.2 3c.2.2 2.1 3.3 5.2 4.6.7.3 1.3.5 1.7.7.7.2 1.4.2 1.9.1.6-.1 1.7-.7 2-1.4.3-.7.3-1.3.2-1.4-.1-.1-.3-.2-.6-.3M12 2C6.5 2 2 6.5 2 12c0 1.7.4 3.3 1.2 4.7L2 22l5.4-1.2c1.4.7 2.9 1.1 4.6 1.1 5.5 0 10-4.5 10-10S17.5 2 12 2"/></svg>
      </button>
    </>
  );
}

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