// tweaks.jsx — Purna Web tweakable controls
// Reads from window.PW_TWEAKS (mutated by setTweak) and applies via CSS variables + class flags.

const PW_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "navy": "#0B2D4D",
  "teal": "#2EB5B4",
  "green": "#22C55E",
  "bg": "#FFFFFF",
  "ink": "#1A2B3C",
  "fontFamily": "Poppins",
  "headingScale": 1,
  "bodySize": 16,
  "radius": 16,
  "density": "regular",
  "containerWidth": 1240,
  "buttonStyle": "rounded",
  "navStyle": "default",
  "heroVariant": "engine",
  "heroHeadline": "Turn every lead into revenue.",
  "heroAccent": "revenue.",
  "ctaCopy": "Book a free demo",
  "showLogos": true,
  "showLeak": true,
  "showThera": true,
  "showFAQ": true,
  "showQuote": true,
  "darkHeroSection": false,
  "stickyNav": true,
  "showGrain": false,
  "motion": "smooth",
  "revealStrength": 16,
  "engineSpeed": 900,
  "shadowDepth": "medium",
  "gradientIntensity": 0.18
}/*EDITMODE-END*/;

const FONT_OPTIONS = [
  { value: "Poppins", label: "Poppins" },
  { value: "Inter Tight", label: "Inter Tight" },
  { value: "Space Grotesk", label: "Space Grotesk" },
  { value: "Manrope", label: "Manrope" },
  { value: "DM Sans", label: "DM Sans" },
  { value: "Plus Jakarta Sans", label: "Jakarta" },
];

// Inject a Google Fonts link tag dynamically when font changes
function ensureFont(name) {
  if (!name) return;
  const id = "pw-font-" + name.replace(/\s+/g, "-");
  if (document.getElementById(id)) return;
  const link = document.createElement("link");
  link.id = id;
  link.rel = "stylesheet";
  link.href = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(name)}:wght@400;500;600;700&display=swap`;
  document.head.appendChild(link);
}

// Convert hex to comma-separated RGB string for use in rgba()
function hexToRgb(hex) {
  const h = hex.replace("#", "");
  const v = h.length === 3 ? h.split("").map(c => c + c).join("") : h;
  const n = parseInt(v, 16);
  return `${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}`;
}

// Mix a color with white or black for derivative shades
function shade(hex, amount) {
  const h = hex.replace("#", "");
  const v = h.length === 3 ? h.split("").map(c => c + c).join("") : h;
  const n = parseInt(v, 16);
  let r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
  if (amount > 0) { r = Math.round(r + (255 - r) * amount); g = Math.round(g + (255 - g) * amount); b = Math.round(b + (255 - b) * amount); }
  else { const a = -amount; r = Math.round(r * (1 - a)); g = Math.round(g * (1 - a)); b = Math.round(b * (1 - a)); }
  return "#" + [r, g, b].map(x => x.toString(16).padStart(2, "0")).join("");
}

function applyTweaks(t) {
  const r = document.documentElement.style;
  r.setProperty("--navy", t.navy);
  r.setProperty("--navy-2", shade(t.navy, 0.08));
  r.setProperty("--navy-3", shade(t.navy, 0.18));
  r.setProperty("--teal", t.teal);
  r.setProperty("--teal-2", shade(t.teal, -0.1));
  r.setProperty("--teal-3", shade(t.teal, 0.18));
  r.setProperty("--teal-rgb", hexToRgb(t.teal));
  r.setProperty("--green", t.green);
  r.setProperty("--green-2", shade(t.green, -0.1));
  r.setProperty("--green-rgb", hexToRgb(t.green));
  r.setProperty("--white", t.bg);
  r.setProperty("--text", t.ink);

  // derive a soft grey from bg
  const isLightBg = t.bg.toLowerCase() !== "#000000" && t.bg.toLowerCase() !== "#0a0a0a";
  r.setProperty("--grey", isLightBg ? shade(t.bg, -0.04) : shade(t.bg, 0.08));
  r.setProperty("--grey-2", isLightBg ? shade(t.bg, -0.08) : shade(t.bg, 0.14));
  r.setProperty("--line", isLightBg ? shade(t.bg, -0.1) : shade(t.bg, 0.18));
  r.setProperty("--line-2", isLightBg ? shade(t.bg, -0.18) : shade(t.bg, 0.28));
  r.setProperty("--text-muted", isLightBg ? shade(t.ink, 0.35) : shade(t.ink, -0.35));

  // Type
  ensureFont(t.fontFamily);
  r.setProperty("--sans", `"${t.fontFamily}", -apple-system, BlinkMacSystemFont, sans-serif`);
  document.body.style.fontSize = t.bodySize + "px";
  r.setProperty("--heading-scale", t.headingScale);

  // Density / spacing
  const densityMap = { compact: 80, regular: 120, comfy: 160 };
  r.setProperty("--section-y", (densityMap[t.density] || 120) + "px");

  // Radius
  r.setProperty("--r-sm", Math.max(2, t.radius * 0.4) + "px");
  r.setProperty("--r-md", Math.max(4, t.radius * 0.6) + "px");
  r.setProperty("--r-lg", t.radius + "px");
  r.setProperty("--r-xl", (t.radius * 1.5) + "px");

  // Container
  r.setProperty("--container", t.containerWidth + "px");

  // Shadows
  const shadowMap = {
    none: ["none", "none", "none"],
    soft: ["0 1px 2px rgba(11,45,77,0.04)", "0 2px 8px rgba(11,45,77,0.05)", "0 8px 24px rgba(11,45,77,0.06)"],
    medium: ["0 1px 2px rgba(11,45,77,0.06), 0 1px 3px rgba(11,45,77,0.04)", "0 4px 16px rgba(11,45,77,0.08), 0 2px 6px rgba(11,45,77,0.04)", "0 24px 48px rgba(11,45,77,0.12), 0 8px 16px rgba(11,45,77,0.06)"],
    deep: ["0 2px 4px rgba(11,45,77,0.1)", "0 8px 24px rgba(11,45,77,0.16)", "0 32px 64px rgba(11,45,77,0.22), 0 12px 24px rgba(11,45,77,0.12)"]
  };
  const sh = shadowMap[t.shadowDepth] || shadowMap.medium;
  r.setProperty("--shadow-sm", sh[0]);
  r.setProperty("--shadow-md", sh[1]);
  r.setProperty("--shadow-lg", sh[2]);
  r.setProperty("--shadow-teal", `0 8px 24px rgba(${hexToRgb(t.teal)}, 0.25)`);
  r.setProperty("--gradient-intensity", t.gradientIntensity);

  // Motion
  const motionMap = {
    none: "0s",
    snappy: "0.18s",
    smooth: "0.4s",
    cinematic: "0.9s"
  };
  r.setProperty("--reveal-dur", motionMap[t.motion] || "0.4s");
  r.setProperty("--reveal-y", t.revealStrength + "px");

  // Body class flags
  document.body.classList.toggle("pw-grain", t.showGrain);
  document.body.classList.toggle("pw-btn-pill", t.buttonStyle === "pill");
  document.body.classList.toggle("pw-btn-square", t.buttonStyle === "square");
  document.body.classList.toggle("pw-nav-floating", t.navStyle === "floating");
  document.body.classList.toggle("pw-nav-flush", t.navStyle === "flush");
  document.body.classList.toggle("pw-no-sticky", !t.stickyNav);
  document.body.classList.toggle("pw-dark-hero", t.darkHeroSection);

  // Engine speed for global use
  window.PW_ENGINE_SPEED = t.engineSpeed;
}

function PWTweaks({ t, setT }) {
  const presets = [
    { name: "Default Navy", values: { navy: "#0B2D4D", teal: "#2EB5B4", green: "#22C55E", bg: "#FFFFFF", ink: "#1A2B3C" } },
    { name: "Midnight", values: { navy: "#0A0E1A", teal: "#7C3AED", green: "#10B981", bg: "#FAFAFA", ink: "#0A0E1A" } },
    { name: "Sunset", values: { navy: "#1F1147", teal: "#F97316", green: "#FACC15", bg: "#FFF8F1", ink: "#1F1147" } },
    { name: "Forest", values: { navy: "#14271F", teal: "#059669", green: "#84CC16", bg: "#F8FAF6", ink: "#14271F" } },
    { name: "Crimson", values: { navy: "#1A0E14", teal: "#DC2626", green: "#F59E0B", bg: "#FFFAF5", ink: "#1A0E14" } },
    { name: "Cobalt", values: { navy: "#0F172A", teal: "#3B82F6", green: "#06B6D4", bg: "#F8FAFC", ink: "#0F172A" } },
    { name: "Mono", values: { navy: "#000000", teal: "#525252", green: "#737373", bg: "#FAFAFA", ink: "#0A0A0A" } },
    { name: "Inverse", values: { navy: "#000000", teal: "#39FF14", green: "#00FFFF", bg: "#0A0A0A", ink: "#F5F5F5" } },
  ];

  const headlines = [
    { value: "Turn every lead into revenue.", accent: "revenue." },
    { value: "AI infrastructure for businesses that grow.", accent: "grow." },
    { value: "Stop losing leads after 6 PM.", accent: "after 6 PM." },
    { value: "Systems that ship. Support that stays.", accent: "Support that stays." },
    { value: "Built in-house. Owned by you.", accent: "Owned by you." },
  ];

  return (
    <TweaksPanel title="Purna Web · Tweaks">
      <TweakSection label="Color presets"/>
      <div style={{display:"grid", gridTemplateColumns:"repeat(2, 1fr)", gap:6, marginTop: 4}}>
        {presets.map(p => (
          <button key={p.name} className="twk-btn secondary" style={{height: 32, padding: "0 8px", fontSize: 11.5, display:"flex", alignItems:"center", gap:6, justifyContent:"flex-start"}}
            onClick={() => setT(p.values)}>
            <span style={{display:"inline-flex", flexShrink:0}}>
              <span style={{width:10,height:10,borderRadius:2,background:p.values.navy}}/>
              <span style={{width:10,height:10,borderRadius:2,background:p.values.teal,marginLeft:2}}/>
              <span style={{width:10,height:10,borderRadius:2,background:p.values.green,marginLeft:2}}/>
            </span>
            {p.name}
          </button>
        ))}
      </div>

      <TweakSection label="Custom colors"/>
      <TweakColor label="Brand navy" value={t.navy} onChange={v => setT("navy", v)}/>
      <TweakColor label="Accent teal" value={t.teal} onChange={v => setT("teal", v)}/>
      <TweakColor label="Success green" value={t.green} onChange={v => setT("green", v)}/>
      <TweakColor label="Background" value={t.bg} onChange={v => setT("bg", v)}/>
      <TweakColor label="Text ink" value={t.ink} onChange={v => setT("ink", v)}/>

      <TweakSection label="Typography"/>
      <TweakSelect label="Font family" value={t.fontFamily} options={FONT_OPTIONS} onChange={v => setT("fontFamily", v)}/>
      <TweakSlider label="Body size" value={t.bodySize} min={13} max={20} unit="px" onChange={v => setT("bodySize", v)}/>
      <TweakSlider label="Heading scale" value={t.headingScale} min={0.7} max={1.4} step={0.05} onChange={v => setT("headingScale", v)}/>

      <TweakSection label="Layout"/>
      <TweakRadio label="Density" value={t.density} options={["compact","regular","comfy"]} onChange={v => setT("density", v)}/>
      <TweakSlider label="Container" value={t.containerWidth} min={960} max={1440} step={20} unit="px" onChange={v => setT("containerWidth", v)}/>
      <TweakSlider label="Corner radius" value={t.radius} min={0} max={32} unit="px" onChange={v => setT("radius", v)}/>
      <TweakRadio label="Buttons" value={t.buttonStyle} options={["square","rounded","pill"]} onChange={v => setT("buttonStyle", v)}/>
      <TweakRadio label="Nav style" value={t.navStyle} options={["flush","default","floating"]} onChange={v => setT("navStyle", v)}/>
      <TweakToggle label="Sticky nav" value={t.stickyNav} onChange={v => setT("stickyNav", v)}/>

      <TweakSection label="Hero"/>
      <TweakSelect label="Hero variant" value={t.heroVariant}
        options={[
          { value: "engine", label: "Live engine demo" },
          { value: "split", label: "Split metric panel" },
          { value: "centered", label: "Centered statement" },
          { value: "terminal", label: "Terminal feed" },
        ]}
        onChange={v => setT("heroVariant", v)}/>
      <TweakSelect label="Headline preset" value={t.heroHeadline}
        options={headlines.map(h => ({value: h.value, label: h.value}))}
        onChange={v => {
          const h = headlines.find(x => x.value === v);
          setT({ heroHeadline: v, heroAccent: h ? h.accent : "" });
        }}/>
      <TweakText label="Custom CTA" value={t.ctaCopy} onChange={v => setT("ctaCopy", v)}/>

      <TweakSection label="Sections"/>
      <TweakToggle label="Logo strip" value={t.showLogos} onChange={v => setT("showLogos", v)}/>
      <TweakToggle label="Problem leak" value={t.showLeak} onChange={v => setT("showLeak", v)}/>
      <TweakToggle label="Quote" value={t.showQuote} onChange={v => setT("showQuote", v)}/>
      <TweakToggle label="TheraNote" value={t.showThera} onChange={v => setT("showThera", v)}/>
      <TweakToggle label="FAQ" value={t.showFAQ} onChange={v => setT("showFAQ", v)}/>

      <TweakSection label="Motion & atmosphere"/>
      <TweakRadio label="Motion" value={t.motion} options={["none","snappy","smooth","cinematic"]} onChange={v => setT("motion", v)}/>
      <TweakSlider label="Reveal lift" value={t.revealStrength} min={0} max={48} unit="px" onChange={v => setT("revealStrength", v)}/>
      <TweakSlider label="Engine speed" value={t.engineSpeed} min={300} max={2200} step={100} unit="ms" onChange={v => setT("engineSpeed", v)}/>
      <TweakRadio label="Shadows" value={t.shadowDepth} options={["none","soft","medium","deep"]} onChange={v => setT("shadowDepth", v)}/>
      <TweakSlider label="Glow intensity" value={t.gradientIntensity} min={0} max={0.5} step={0.02} onChange={v => setT("gradientIntensity", v)}/>
      <TweakToggle label="Grain texture" value={t.showGrain} onChange={v => setT("showGrain", v)}/>

      <TweakSection label="Reset"/>
      <TweakButton label="Restore defaults" secondary onClick={() => setT(PW_TWEAK_DEFAULTS)}/>
    </TweaksPanel>
  );
}

Object.assign(window, { PW_TWEAK_DEFAULTS, PWTweaks, applyTweaks });
