// Main app + Tweaks

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "rust",
  "headline": "DIG YOUR OWN GRAVE.",
  "tagline": "A vanilla+ DayZ server for adults who want loot that matters, bases that hold, and admins that actually read the ticket.",
  "showShovelWatermark": true,
  "showMarquee": true,
  "showMap": true,
  "showLeaderboard": false,
  "showLiveQueue": false,
  "showPriority": false,
  "showHeatmap": false,
  "heatmapIntensity": 0.7,
  "mockStaff": false,
  "grain": 0.06
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const liveStatus = useLiveStatus(47);
  const live = liveStatus.players;
  const [acctOpen, setAcctOpen] = React.useState(false);
  const [adminOpen, setAdminOpen] = React.useState(false);
  const openAcct = () => setAcctOpen(true);
  const openAdmin = () => setAdminOpen(true);
  const { session } = useAuth();
  const staff = isStaff(session, t.mockStaff);

  // ── Owner-mode unlock ────────────────────────────────────────────────
  // Visiting shovelhead.net/?adminmode=1 prompts for the admin password.
  // If it matches ADMIN_SECRET on the API, we set a local flag that makes
  // the ADMIN button appear in the nav AND cache the password in
  // sessionStorage so pin saves don't re-prompt this session.
  // Visiting /?adminmode=0 clears the flag and the cached password.
  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const v = params.get("adminmode");
    if (v == null) return;

    // Clean the query string regardless of outcome
    const cleanUrl = () => {
      params.delete("adminmode");
      const q = params.toString();
      history.replaceState(null, "", window.location.pathname + (q ? "?" + q : "") + window.location.hash);
    };

    if (v === "0") {
      try {
        localStorage.removeItem("shovelhead.adminUI");
        sessionStorage.removeItem("shovelhead.admin.v1");
      } catch {}
      cleanUrl();
      window.location.reload();
      return;
    }

    if (v === "1") {
      (async () => {
        const apiUrl = window.SHOVELHEAD_CONFIG?.pinsApiUrl;
        const pwd = prompt("Admin password to unlock pin editing:");
        if (!pwd) { cleanUrl(); return; }

        // If no API configured (local prototype mode), accept anything.
        if (!apiUrl) {
          try {
            localStorage.setItem("shovelhead.adminUI", "1");
            sessionStorage.setItem("shovelhead.admin.v1", pwd);
          } catch {}
          cleanUrl();
          window.location.reload();
          return;
        }

        // Verify against the API
        try {
          const r = await fetch(apiUrl.replace(/\/$/, "") + "/verify", {
            method: "POST",
            headers: { "X-Admin-Secret": pwd },
          });
          if (r.status === 200) {
            try {
              localStorage.setItem("shovelhead.adminUI", "1");
              sessionStorage.setItem("shovelhead.admin.v1", pwd);
            } catch {}
            cleanUrl();
            window.location.reload();
          } else if (r.status === 401) {
            alert("Wrong password. Admin mode NOT unlocked.");
            cleanUrl();
          } else {
            alert("Unexpected response from API: " + r.status);
            cleanUrl();
          }
        } catch (e) {
          alert("Couldn't reach API: " + e.message);
          cleanUrl();
        }
      })();
    }
  }, []);

  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", t.theme);
    document.documentElement.style.setProperty("--grain", String(t.grain));
  }, [t.theme, t.grain]);

  React.useEffect(() => {
    document.body.classList.toggle("no-shovel", !t.showShovelWatermark);
  }, [t.showShovelWatermark]);

  React.useEffect(() => {
    document.body.classList.toggle("no-livequeue", !t.showLiveQueue);
  }, [t.showLiveQueue]);

  React.useEffect(() => {
    document.body.classList.toggle("no-leaderboard", !t.showLeaderboard);
  }, [t.showLeaderboard]);

  React.useEffect(() => {
    document.body.classList.toggle("no-map", !t.showMap);
  }, [t.showMap]);

  React.useEffect(() => {
    document.body.classList.toggle("no-priority", !t.showPriority);
  }, [t.showPriority]);

  return (
    <>
      <Nav live={live} />
      <Hero />
      {t.showMarquee && <Marquee />}
      <StatusSection />
      <RulesSection />
      <ModsSection />
      {t.showMap && <MapSection heatmap={t.showHeatmap} heatmapIntensity={t.heatmapIntensity} />}
      <TradersSection />
      <StaffSection />
      <DiscordCTA />
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Aesthetic">
          <TweakSelect
            label="Theme"
            value={t.theme}
            options={[
              { value: "rust",     label: "Rust — gritty post-apoc" },
              { value: "military", label: "Military — tactical OD/FDE" },
              { value: "cold",     label: "Cold — winter steel & ice" },
              { value: "terminal", label: "Terminal — CRT green" },
            ]}
            onChange={v => setTweak("theme", v)}
          />
          <TweakSlider
            label="Film grain"
            min={0} max={0.2} step={0.01}
            value={t.grain}
            onChange={v => setTweak("grain", v)}
          />
        </TweakSection>

        <TweakSection label="Hero">
          <TweakText
            label="Headline"
            value={t.headline}
            onChange={v => setTweak("headline", v)}
          />
          <TweakText
            label="Tagline"
            value={t.tagline}
            onChange={v => setTweak("tagline", v)}
          />
          <TweakToggle
            label="Big shovel"
            value={t.showShovelWatermark}
            onChange={v => setTweak("showShovelWatermark", v)}
          />
        </TweakSection>

        <TweakSection label="Map">
          <TweakToggle
            label="Show map section"
            value={t.showMap}
            onChange={v => setTweak("showMap", v)}
          />
          {t.showMap && (
            <>
              <TweakToggle
                label="Death heatmap"
                value={t.showHeatmap}
                onChange={v => setTweak("showHeatmap", v)}
              />
              <TweakSlider
                label="Heatmap intensity"
                min={0.2} max={1.5} step={0.05}
                value={t.heatmapIntensity}
                onChange={v => setTweak("heatmapIntensity", v)}
              />
            </>
          )}
        </TweakSection>

        <TweakSection label="Page">
          <TweakToggle
            label="Marquee strip"
            value={t.showMarquee}
            onChange={v => setTweak("showMarquee", v)}
          />
        </TweakSection>

        <TweakSection label="Staff (private)">
          <TweakButton
            label="Open admin panel"
            onClick={() => { setTweak("mockStaff", true); openAdmin(); }}
          />
          <div style={{padding:"8px 12px",fontSize:11,color:"var(--ink-3)",fontFamily:"JetBrains Mono",letterSpacing:"0.08em",lineHeight:1.5}}>
            Opens the local admin overlay so you can place map pins.
            Saved to your browser only — the public site still needs a redeploy to show new pins.
          </div>
        </TweakSection>
      </TweaksPanel>

      <HeroOverride headline={t.headline} tagline={t.tagline} />
      <AccountModal open={acctOpen} onClose={() => setAcctOpen(false)} />
      <AdminOverlay open={adminOpen} onClose={() => setAdminOpen(false)} />
    </>
  );
}

// Surgically override hero copy from tweaks (so users editing the headline see it live).
function HeroOverride({ headline, tagline }) {
  React.useEffect(() => {
    const h1 = document.querySelector(".hero h1");
    const sub = document.querySelector(".hero-sub");
    if (h1 && headline) {
      const parts = headline.trim().split(/\s+/);
      if (parts.length >= 3) {
        const last = parts.pop();
        h1.innerHTML = `<span class="outline">${parts[0]}</span> ${parts.slice(1).join(" ")}<br/><span class="accent">${last}</span>`;
      } else if (parts.length === 2) {
        h1.innerHTML = `<span class="outline">${parts[0]}</span> <span class="accent">${parts[1]}</span>`;
      } else {
        h1.innerHTML = `<span class="accent">${headline}</span>`;
      }
    }
    if (sub && tagline) sub.textContent = tagline;
  }, [headline, tagline]);
  return null;
}

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