// Solo Content Studio — shared primitives for the pre-launch page

const { useState, useEffect, useMemo } = React;

// ── Viewport hook — returns {width, isMobile, isTablet, isDesktop}
// Mobile ≤ 640, Tablet 641–1024, Desktop > 1024.
window.useViewport = function useViewport() {
  const [width, setWidth] = useState(() =>
    typeof window !== "undefined" ? window.innerWidth : 1200
  );
  useEffect(() => {
    const onResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);
  return {
    width,
    isMobile: width <= 640,
    isTablet: width > 640 && width <= 1024,
    isDesktop: width > 1024,
  };
};

// ── The ten specialists ───────────────────────────────────────
window.SPECIALISTS = [
  { num: "01", title: "Newsletter Editor",   animal: "Hedgehog", portrait: "assets/headshots/hedgehog_newsletter-editor.png", accent: "coral", dot: "var(--orange)" },
  { num: "02", title: "Chief Brand Officer", animal: "Badger",   portrait: "assets/headshots/badger_brand-officer.png",       accent: "gold",  dot: "var(--gold-2)" },
  { num: "03", title: "Social Director",     animal: "Parrot",   portrait: "assets/headshots/parrot_social-director.png",      accent: "pink",  dot: "var(--pink-2-soft)" },
  { num: "04", title: "Podcast Producer",    animal: "Bear",     portrait: "assets/headshots/bear_podcast-producer.png",       accent: "gold",  dot: "var(--gold-2-soft)" },
  { num: "05", title: "Sales Page Builder",  animal: "Raccoon",  portrait: "assets/headshots/raccoon_sales-page-builder.png",  accent: "iris",  dot: "var(--iris-2)" },
  { num: "06", title: "Email Strategist",    animal: "Owl",      portrait: "assets/headshots/owl_email-strategist.png",        accent: "sage",  dot: "var(--sage-2)" },
  { num: "07", title: "Blog Writer",         animal: "Deer",     portrait: "assets/headshots/deer_blog-writer.png",            accent: "ice",   dot: "var(--ice-2-soft)" },
  { num: "08", title: "Slide Designer",      animal: "Magpie",   portrait: "assets/headshots/magpie_slide-designer.png",       accent: "pink",  dot: "var(--pink-2)" },
  { num: "09", title: "Video Producer",      animal: "Otter",    portrait: "assets/headshots/otter_video-producer.png",        accent: "ice",   dot: "var(--ice-2)" },
  { num: "10", title: "Content Repurposer",  animal: "Octopus",  portrait: "assets/headshots/octopus_content-repurposer.png",  accent: "lime",  dot: "var(--lime-2)" },
];

// ── Badge ─────────────────────────────────────────────────────
window.Badge = function Badge({ variant = "coral", children, style }) {
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 8,
      fontFamily: "var(--font-mono)", fontWeight: 500, fontSize: 11,
      letterSpacing: "0.08em", textTransform: "uppercase",
      padding: "7px 14px", borderRadius: 999, lineHeight: 1.2,
      background: `var(--${variant}-3)`, color: `var(--${variant}-1)`,
      ...style,
    }}>{children}</span>
  );
};

// ── Button ────────────────────────────────────────────────────
window.SCSButton = function SCSButton({ variant = "primary", size = "lg", children, onClick, style, type }) {
  const [hov, setHov] = useState(false);
  const bySize = {
    sm: { fontSize: 13, padding: "8px 16px" },
    md: { fontSize: 15, padding: "12px 24px" },
    lg: { fontSize: 16, padding: "15px 28px" },
    xl: { fontSize: 17, padding: "18px 32px" },
  };
  const base = {
    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 10,
    fontFamily: "var(--font-body)", fontWeight: 600,
    border: "2px solid transparent", borderRadius: 999,
    cursor: "pointer", lineHeight: 1,
    transition: "transform 0.15s ease, background 0.15s ease, box-shadow 0.2s ease",
    transform: hov ? "translateY(-1px)" : "translateY(0)",
  };
  const variants = {
    primary:  { background: hov ? "var(--orange-deep)" : "var(--orange)", color: "#fff",
                boxShadow: hov ? "0 8px 24px hsl(12 72% 50% / 0.35)" : "0 4px 14px hsl(12 72% 50% / 0.25)" },
    secondary:{ background: "var(--ink)", color: "#fff",
                boxShadow: hov ? "0 8px 24px hsl(348 52% 15% / 0.35)" : "0 4px 14px hsl(348 52% 15% / 0.2)" },
    outline:  { background: hov ? "var(--snow)" : "transparent", color: "var(--ink)", borderColor: "var(--ink)" },
    ghost:    { background: "transparent", color: "var(--orange)" },
    onDark:   { background: hov ? "var(--orange-deep)" : "var(--orange)", color: "#fff",
                boxShadow: hov ? "0 10px 30px hsl(12 72% 45% / 0.55)" : "0 4px 18px hsl(12 72% 50% / 0.45)" },
  };
  return (
    <button type={type} onClick={onClick} onMouseEnter={()=>setHov(true)} onMouseLeave={()=>setHov(false)}
      style={{...base, ...bySize[size], ...variants[variant], ...style}}>{children}</button>
  );
};

// ── Emphasis helper — Instrument Serif italic orange at 1.15em ─
window.Em = function Em({ children, color }) {
  return <em style={color ? { color } : undefined}>{children}</em>;
};

// ── Eyebrow ───────────────────────────────────────────────────
window.Eyebrow = function Eyebrow({ children, color, style }) {
  return (
    <div style={{
      fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 500,
      letterSpacing: "0.18em", textTransform: "uppercase",
      color: color || "var(--muted)", ...style,
    }}>{children}</div>
  );
};

// ── Countdown ─────────────────────────────────────────────────
window.LAUNCH_DATE = new Date("2026-04-27T13:00:00Z").getTime(); // 9am ET
window.useCountdown = function useCountdown(target = window.LAUNCH_DATE) {
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, target - now);
  return {
    days:  Math.floor(diff / 86400000),
    hours: Math.floor((diff % 86400000) / 3600000),
    mins:  Math.floor((diff % 3600000) / 60000),
    secs:  Math.floor((diff % 60000) / 1000),
  };
};

// ── Waitlist form (wired to Kit form 9335645) ─────────────────
window.KIT_FORM_ID = "9335645";
window.WaitlistForm = function WaitlistForm({
  variant = "light",
  size = "md",
  align = "center",
  buttonLabel = "Join the waitlist →",
  successHeadline = "You're on the list.",
  successBody = "We'll email you the moment doors open. That's it.",
}) {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("idle");
  const [notifyMode, setNotifyMode] = useState(false);

  // Kit newsletter subscribers can be linked in with ?email=...&notify=1,
  // which prefills the input and switches the CTA so they don't feel like
  // they're being asked to enter their email a second time.
  useEffect(() => {
    if (typeof window === "undefined") return;
    const params = new URLSearchParams(window.location.search);
    const e = params.get("email");
    const n = params.get("notify");
    if (e && e.includes("@")) setEmail(e);
    if (n === "1" || n === "true") setNotifyMode(true);
  }, []);

  const effectiveButtonLabel = notifyMode ? "Notify me →" : buttonLabel;
  const effectiveSuccessHeadline = notifyMode ? "You're set." : successHeadline;
  const effectiveSuccessBody = notifyMode
    ? "We'll email you the moment doors open. Nothing else changes."
    : successBody;

  const submit = async (e) => {
    e.preventDefault();
    if (!email || !email.includes("@")) return;
    setStatus("loading");
    try {
      await fetch(`https://app.kit.com/forms/${window.KIT_FORM_ID}/subscriptions`, {
        method: "POST",
        mode: "no-cors",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({ email_address: email }),
      });
      setStatus("success");
    } catch (err) {
      setStatus("error");
    }
  };

  const isDark = variant === "dark";

  if (status === "success") {
    return (
      <div style={{
        background: isDark ? "hsl(12 72% 55% / 0.15)" : "hsl(12 72% 55% / 0.08)",
        border: "1.5px solid var(--orange)",
        padding: "20px 28px", borderRadius: 20,
        display: "inline-block", textAlign: "center",
      }}>
        <div style={{
          fontFamily: "var(--font-emphasis)", fontStyle: "italic",
          fontSize: isDark ? 28 : 24,
          color: "var(--orange)", marginBottom: 4, lineHeight: 1,
        }}>{effectiveSuccessHeadline}</div>
        <div style={{
          fontSize: 14,
          color: isDark ? "hsl(350 15% 82%)" : "var(--ink-light)",
        }}>{effectiveSuccessBody}</div>
      </div>
    );
  }

  const inputPad = size === "xl" ? "20px 24px" : size === "lg" ? "17px 22px" : "15px 20px";
  const inputFontSize = size === "xl" ? 18 : 16;

  const inputStyle = isDark
    ? {
        flex: "1 1 0", minWidth: 0, padding: inputPad, borderRadius: 999,
        border: "1.5px solid hsl(348 40% 28%)",
        background: "hsl(348 40% 12%)", color: "var(--white)",
        fontFamily: "var(--font-body)", fontSize: inputFontSize, outline: "none",
        transition: "border-color 0.2s",
      }
    : {
        flex: "1 1 0", minWidth: 0, padding: inputPad, borderRadius: 999,
        border: "1.5px solid var(--border)",
        background: "var(--white)", color: "var(--ink)",
        fontFamily: "var(--font-body)", fontSize: inputFontSize, outline: "none",
        transition: "border-color 0.2s, box-shadow 0.2s",
        boxShadow: "0 1px 3px hsl(335 50% 15% / 0.06)",
      };

  const justify = align === "start" ? "flex-start" : align === "end" ? "flex-end" : "center";

  return (
    <form onSubmit={submit} className="scs-waitlist-form" style={{
      display: "flex", gap: 10,
      width: "100%",
      maxWidth: size === "xl" ? 580 : 480,
      margin: align === "center" ? "0 auto" : "0",
      flexWrap: "nowrap", justifyContent: justify, alignItems: "stretch",
    }}>
      <input
        type="email" required placeholder="you@yourstudio.com"
        value={email} onChange={(e) => setEmail(e.target.value)}
        style={inputStyle}
        onFocus={(e) => e.target.style.borderColor = "var(--orange)"}
        onBlur={(e) => e.target.style.borderColor = isDark ? "hsl(348 40% 28%)" : "var(--border)"}
      />
      <window.SCSButton
        variant={isDark ? "onDark" : "primary"}
        size={size}
        type="submit"
      >
        {status === "loading" ? "Joining..." : effectiveButtonLabel}
      </window.SCSButton>
    </form>
  );
};

// ── Mesh gradient bg (warm, editorial) ────────────────────────
window.MeshBg = function MeshBg({ variant = "warm", style }) {
  const meshes = {
    warm:   "radial-gradient(ellipse 80% 60% at 15% 20%, hsla(12, 80%, 85%, 0.6), transparent 60%), radial-gradient(ellipse 70% 60% at 85% 10%, hsla(38, 80%, 85%, 0.5), transparent 60%), radial-gradient(ellipse 60% 70% at 50% 100%, hsla(340, 70%, 92%, 0.5), transparent 60%)",
    cool:   "radial-gradient(ellipse 70% 60% at 20% 80%, hsla(210, 60%, 88%, 0.5), transparent 60%), radial-gradient(ellipse 70% 60% at 85% 15%, hsla(258, 60%, 92%, 0.5), transparent 60%)",
    vibrant:"radial-gradient(ellipse 80% 70% at 25% 25%, hsla(12, 85%, 75%, 0.35), transparent 60%), radial-gradient(ellipse 60% 60% at 80% 70%, hsla(340, 70%, 78%, 0.3), transparent 60%)",
  };
  return <div style={{ position: "absolute", inset: 0, background: meshes[variant], pointerEvents: "none", ...style }} />;
};
