/* chrome.jsx — Top status bar, Nav, Sticky Bottom CTA, Sales Notification */

const NAMES_POOL = [
  /* ── USA ~75% ── */
  ["Emma",          "Austin, TX"],
  ["Jessica",       "Miami, FL"],
  ["James",         "Brooklyn, NY"],
  ["Olivia",        "Los Angeles, CA"],
  ["Noah",          "Chicago, IL"],
  ["Ava",           "Houston, TX"],
  ["Liam",          "Phoenix, AZ"],
  ["Sophia",        "San Diego, CA"],
  ["Mason",         "Dallas, TX"],
  ["Isabella",      "Nashville, TN"],
  ["Logan",         "Denver, CO"],
  ["Mia",           "Seattle, WA"],
  ["Ethan",         "Portland, OR"],
  ["Charlotte",     "Atlanta, GA"],
  ["Aiden",         "Boston, MA"],
  ["Amelia",        "San Francisco, CA"],
  ["Lucas",         "Charlotte, NC"],
  ["Harper",        "Minneapolis, MN"],
  ["Jackson",       "Philadelphia, PA"],
  ["Evelyn",        "San Antonio, TX"],
  ["Carter",        "Orlando, FL"],
  ["Abigail",       "Columbus, OH"],
  ["Elijah",        "Las Vegas, NV"],
  ["Emily",         "Washington, DC"],
  ["Caleb",         "Salt Lake City, UT"],
  ["Scarlett",      "Raleigh, NC"],
  ["Ryan",          "Tampa, FL"],
  ["Grace",         "Kansas City, MO"],
  ["Hunter",        "Sacramento, CA"],
  ["Lily",          "Pittsburgh, PA"],
  ["Tyler",         "Richmond, VA"],
  ["Chloe",         "Scottsdale, AZ"],
  ["Wyatt",         "Indianapolis, IN"],
  ["Nora",          "Louisville, KY"],
  ["Jayden",        "New Orleans, LA"],
  ["Zoe",           "Boise, ID"],
  ["David & Lara",  "Austin, TX"],
  ["Mike & Sara",   "Denver, CO"],
  ["Tom & Amy",     "Chicago, IL"],
  /* ── International ~25% ── */
  ["Sarah",         "Manchester, UK"],
  ["Hannah",        "Dublin, IE"],
  ["Liam",          "Toronto, ON"],
  ["Priya",         "London, UK"],
  ["Marcus",        "Berlin, DE"],
  ["Isla",          "Sydney, AU"],
  ["Daniel",        "Lyon, FR"],
  ["Aria",          "Oslo, NO"],
  ["Sofia",         "Amsterdam, NL"],
  ["Chloe",         "Wellington, NZ"],
  ["Lucas",         "São Paulo, BR"],
  ["Anya",          "Edinburgh, UK"],
];
const TIMESTAMPS = ["just now", "1 min ago", "3 min ago", "5 min ago", "8 min ago", "12 min ago"];

function _rand(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
function _randItem(arr, exclude) {
  let pick = arr[_rand(0, arr.length - 1)];
  let guard = 0;
  while (exclude && pick === exclude && guard++ < 8) pick = arr[_rand(0, arr.length - 1)];
  return pick;
}

/* ===== Counter context (now with shared lastSale so ticker + popup stay in sync) ===== */
const LAUNCH_TOTAL = 1000;
const MIN_COPIES_LO = 400;
const MIN_COPIES_HI = 500;

function _dayKey() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}
function _msUntilNextMidnight() {
  const now = new Date();
  const next = new Date(now);
  next.setHours(24, 0, 0, 0);
  return Math.max(1000, next.getTime() - now.getTime());
}
/* Deterministic hash so the same day always yields the same base count
   on EVERY device (no localStorage randomness → desktop and mobile match). */
function _hashStr(s) {
  let h = 2166136261;
  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
  return h >>> 0;
}
/* Copies sold is a pure function of the wall clock: a per-day base (600-750)
   that starts exactly at 00:00 midnight and grows steadily through the day.
   Two devices at the same moment compute the exact same number. */
function _computeCopies() {
  const base = MIN_COPIES_LO + (_hashStr(_dayKey()) % (MIN_COPIES_HI - MIN_COPIES_LO + 1));
  const now = new Date();
  const minutesIntoDay = now.getHours() * 60 + now.getMinutes();
  const grown = base + Math.floor(minutesIntoDay / 4); // ~360 max growth over full day
  return Math.min(LAUNCH_TOTAL - 2, grown);
}

function _newSale(excludeName) {
  const pick = _randItem(NAMES_POOL, excludeName);
  return {
    name: pick[0],
    city: pick[1],
    cityShort: pick[1].split(",")[0].trim(),
    minutesAgo: _rand(1, 12)
  };
}
function _formatTime(min) {
  if (min <= 0) return "just now";
  if (min === 1) return "1 min ago";
  return `${min} min ago`;
}

const CounterCtx = React.createContext(null);
function CounterProvider({ children }) {
  // Copies sold is derived deterministically from the wall clock so every
  // device (desktop, mobile, tablet) always displays the same number.
  const [copiesSold, setCopiesSold] = React.useState(_computeCopies);
  const [viewing, setViewing] = React.useState(_rand(12, 28));
  const [lastSale, setLastSale] = React.useState(() => _newSale(null));
  const [saleNonce, setSaleNonce] = React.useState(0); // bumps each time a new sale lands so popup re-fires

  // viewing fluctuates within a realistic small range
  React.useEffect(() => {
    const t = setInterval(() => {
      setViewing((v) => Math.max(8, Math.min(36, v + _rand(-3, 4))));
    }, _rand(10000, 15000));
    return () => clearInterval(t);
  }, []);

  // Poll every 60s. When the clock-counter ticks +1 (every 4 min),
  // fire a popup — Option B: popup = counter are fully in sync.
  const prevCopies = React.useRef(null);
  React.useEffect(() => {
    prevCopies.current = _computeCopies();
    const t = setInterval(() => {
      const fresh = _computeCopies();
      if (fresh > prevCopies.current) {
        prevCopies.current = fresh;
        setCopiesSold(fresh);
        setLastSale((prev) => _newSale(prev ? prev.name : null));
        setSaleNonce((n) => n + 1);
      }
    }, 60000); // check every minute, fires popup when counter ticks
    return () => clearInterval(t);
  }, []);

  // Midnight rollover — recompute the new day's base.
  React.useEffect(() => {
    let timer;
    const schedule = () => {
      timer = setTimeout(() => {
        setCopiesSold(_computeCopies());
        schedule(); // schedule the next midnight
      }, _msUntilNextMidnight());
    };
    schedule();
    return () => clearTimeout(timer);
  }, []);

  // every minute, age the displayed minutesAgo by 1
  React.useEffect(() => {
    const t = setInterval(() => {
      setLastSale((s) => s ? { ...s, minutesAgo: Math.min(12, s.minutesAgo + 1) } : s);
    }, 60000);
    return () => clearInterval(t);
  }, []);

  const value = {
    copiesSold,
    copiesTotal: LAUNCH_TOTAL,
    copiesRemaining: LAUNCH_TOTAL - copiesSold,
    viewing,
    lastSale,
    saleNonce
  };
  return <CounterCtx.Provider value={value}>{children}</CounterCtx.Provider>;
}
function useCounters() { return React.useContext(CounterCtx); }

/* ===== Top status bar — redesigned with icons, animated dots, more visual rhythm ===== */
function TopStatusBar() {
  const { viewing, lastSale, copiesRemaining, copiesSold, copiesTotal } = useCounters();
  const pct = Math.min(100, (copiesSold / copiesTotal) * 100);
  return (
    <div className="sticky top-0 z-50 w-full backdrop-blur"
         style={{ background: "linear-gradient(90deg, #F4EDD8 0%, #FAF6EE 50%, #F4EDD8 100%)",
                  borderBottom: "1px solid #E8DFCC" }}>
      <div className="container-x flex items-center justify-between gap-3"
           style={{ minHeight: 36, paddingTop: 4, paddingBottom: 4 }}>
        {/* Left — live viewing */}
        <div className="ticker-chip" style={{ background: "rgba(74,124,89,0.10)", borderColor: "rgba(74,124,89,0.25)" }}>
          <span className="inline-block w-2 h-2 rounded-full bg-live live-dot" />
          <span className="font-ui text-ink" style={{ fontSize: 12, fontWeight: 500 }}>
            <span className="font-semibold text-live">{viewing}</span>
            <span className="hidden sm:inline"> reading right now</span>
            <span className="sm:hidden"> viewing</span>
          </span>
        </div>

        {/* Center — last sold ticker (desktop) — city + minutes sync with sales popup */}
        <div className="hidden lg:flex items-center gap-2 text-body" style={{ fontSize: 12 }}>
          <Icon name="Sparkles" size={13} color="#C8A24A" />
          <span className="font-ui">
            Last copy sold <span className="font-semibold text-ink">{_formatTime(lastSale.minutesAgo)}</span> in
            <span className="font-hand text-gold-h" style={{ fontSize: 15, marginLeft: 4 }}>{lastSale.cityShort}</span>
          </span>
        </div>

        {/* Right — copies sold */}
        <div className="flex items-center gap-2">
          <div className="ticker-chip" style={{ background: "rgba(217,119,87,0.12)", borderColor: "rgba(217,119,87,0.35)" }}>
            <span className="font-ui" style={{ fontSize: 12 }}>
              <span className="font-bold" style={{ color: "#A8851F" }}>{copiesSold.toLocaleString()}</span>
              <span className="text-muted">/{copiesTotal.toLocaleString()}</span>
              <span className="text-muted hidden sm:inline"> sold</span>
              <span className="text-muted ml-1">· <span style={{ color: "#D97757", fontWeight: 600 }}>{copiesRemaining.toLocaleString()} left</span></span>
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ===== Nav bar with section anchor links ===== */
const NAV_LINKS = [
  ["#story",    "Story"],
  ["#chapters", "Chapters"],
  ["#preview",  "Preview"],
  ["#reviews",  "Reviews"],
  ["#faq",      "FAQ"]
];
function NavBar() {
  const [open, setOpen] = React.useState(false);
  return (
    <header className="sticky z-40 w-full backdrop-blur"
            style={{ top: 36, background: "rgba(250,246,238,0.92)", borderBottom: "1px solid #E8DFCC", minHeight: 72 }}>
      <div className="container-x flex items-center justify-between gap-6" style={{ minHeight: 72 }}>
        <a href="#top" className="flex items-center gap-3 no-underline shrink-0" style={{ textDecoration: "none" }}>
          <img src="assets/logo-mark.png" alt="Born to Know" style={{ height: 40, width: 40 }} />
          <span className="font-display text-ink" style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-0.01em" }}>
            Born to Know
          </span>
        </a>

        {/* Center anchor nav (desktop) */}
        <nav className="hidden lg:flex items-center gap-7 flex-1 justify-center" aria-label="Section navigation">
          {NAV_LINKS.map(([href, label]) => (
            <a key={href} href={href}
               className="font-ui text-body hover:text-ink transition-colors"
               style={{ fontSize: 14, fontWeight: 500, textDecoration: "none", letterSpacing: "-0.005em" }}>
              {label}
            </a>
          ))}
        </nav>

        {/* CTA + mobile menu trigger */}
        <div className="flex items-center gap-2 shrink-0">
          <button aria-label="Open menu"
                  onClick={() => setOpen(o => !o)}
                  className="lg:hidden inline-flex items-center justify-center bg-surface border border-line rounded-md"
                  style={{ width: 40, height: 40 }}>
            <Icon name={open ? "X" : "Menu"} size={20} color="#3D3A33" />
          </button>
          <a href={CHECKOUT_URL} className="cta-primary hidden lg:inline-flex items-center gap-2 no-underline whitespace-nowrap"
             style={{ height: 44, fontSize: 14, padding: "0 16px" }}>
            <span className="hidden sm:inline">Get The Blueprint</span>
            <span className="sm:hidden">Get for $23.95</span>
            <Icon name="ArrowRight" size={16} color="#FFFCF5" />
          </a>
        </div>
      </div>

      {/* Mobile drawer */}
      {open && (
        <div className="lg:hidden border-t border-line bg-cream">
          <nav className="container-x py-3 flex flex-col gap-1" aria-label="Section navigation">
            {NAV_LINKS.map(([href, label]) => (
              <a key={href} href={href}
                 onClick={() => setOpen(false)}
                 className="font-ui text-ink py-2.5"
                 style={{ fontSize: 15, fontWeight: 500, textDecoration: "none" }}>
                {label}
              </a>
            ))}
          </nav>
        </div>
      )}
    </header>
  );
}

/* ===== Sticky bottom CTA bar — richer, more urgent ===== */
function StickyBottomCTA() {
  const [visible, setVisible] = React.useState(false);
  const [dismissed, setDismissed] = React.useState(false);

  // Reappear 60 seconds after being dismissed
  React.useEffect(() => {
    if (!dismissed) return;
    const t = setTimeout(() => setDismissed(false), 60000);
    return () => clearTimeout(t);
  }, [dismissed]);
  const { copiesRemaining, copiesSold, copiesTotal } = useCounters();
  const pct = Math.min(100, (copiesSold / copiesTotal) * 100);

  React.useEffect(() => {
    const onScroll = () => {
      if (!visible && window.scrollY > window.innerHeight * 0.7) setVisible(true);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [visible]);
  if (!visible || dismissed) return null;
  // Hide on mobile
  if (typeof window !== 'undefined' && window.innerWidth < 768) return null;

  return (
    <div className="fixed bottom-0 left-0 right-0 z-50 sticky-cta slide-up"
         style={{ background: "#FFFCF5", borderTop: "1px solid #E8DFCC" }}>
      {/* Top urgency strip */}
      <div className="w-full" style={{ background: "linear-gradient(90deg, #D97757 0%, #C8A24A 50%, #2C3A24 100%)", height: 3 }} />

      <div className="container-x flex items-center gap-3 md:gap-5 relative"
           style={{ minHeight: 80, paddingTop: 10, paddingBottom: 10 }}>
        {/* Product thumbnail (hidden < sm) */}
        <div className="hidden sm:flex items-center gap-3 shrink-0">
          <MiniBook size={64} />
          <div className="leading-tight">
            <div className="font-display text-ink" style={{ fontSize: 15, fontWeight: 700, letterSpacing: "-0.01em" }}>The Baby Blueprint</div>
            <div className="font-body text-muted flex items-center gap-1.5" style={{ fontSize: 11.5 }}>
              <Icon name="FileText" size={11} color="#6B655B" />108 pages · Instant PDF
            </div>
          </div>
        </div>

        {/* Price + progress (center, desktop) */}
        <div className="hidden md:flex items-center gap-3 mx-auto">
          <div className="flex items-end gap-2">
            <span className="strike-red font-display" style={{ fontSize: 18 }}>$39</span>
            <span className="font-display" style={{ fontSize: 32, fontWeight: 800, lineHeight: 1, letterSpacing: "-0.02em", color: "#2C3A24" }}>$23.95</span>
          </div>
          <div className="flex flex-col gap-1.5">
            <span className="save-stamp" style={{ fontSize: 11, padding: "4px 10px", transform: "rotate(-3deg)" }}>SAVE&nbsp;$15</span>
          </div>
          <div className="font-ui leading-tight" style={{ fontSize: 11 }}>
            <div style={{ color: "#D97757", fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase" }}>Going fast</div>
            <div className="text-muted">
              <span className="text-ink font-semibold">{copiesSold.toLocaleString()}</span> sold ·
              <span style={{ color: "#D97757", fontWeight: 600 }}> {copiesRemaining.toLocaleString()} left</span>
            </div>
          </div>
        </div>

        {/* Mobile compact column — price + same scarcity info as desktop */}
        <div className="md:hidden flex flex-col leading-tight flex-1 min-w-0">
          <div className="flex items-baseline gap-2">
            <span className="strike-red font-display" style={{ fontSize: 15 }}>$39</span>
            <span className="font-display text-forest" style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em" }}>$23.95</span>
            <span className="save-stamp" style={{ fontSize: 9, padding: "2px 7px", transform: "rotate(-3deg)" }}>SAVE&nbsp;$15</span>
          </div>
          <div className="mt-1 font-ui flex items-center gap-1.5"
               style={{ fontSize: 10.5, color: "#D97757", fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase" }}>
            <span className="inline-block w-1.5 h-1.5 rounded-full" style={{ background: "#D97757" }} />
            Only {copiesRemaining.toLocaleString()} left
          </div>
        </div>

        {/* Right — CTA */}
        <div className="flex-shrink-0 flex justify-end items-center">
          <a href={CHECKOUT_URL}
             className="cta-primary cta-pulse inline-flex items-center justify-center gap-2 no-underline relative overflow-hidden group"
             style={{ height: 56, fontSize: 15, padding: "0 18px" }}>
            <span className="relative z-10 flex items-center gap-2 whitespace-nowrap">
              <span>Get it — $23.95</span>
              <Icon name="ArrowRight" size={18} color="#FFFCF5" />
            </span>
          </a>
        </div>

        <button aria-label="Dismiss"
                onClick={() => setDismissed(true)}
                className="absolute right-2 top-1 text-muted hover:text-ink transition p-1">
          <Icon name="X" size={14} color="currentColor" />
        </button>
      </div>
    </div>
  );
}

/* ===== Mini Book product thumbnail (used in sales popup + sticky footer) ===== */
function MiniBook({ size = 56 }) {
  return (
    <img src="assets/book-mockup.png"
         alt="The Baby Blueprint"
         draggable="false"
         style={{ width: size, height: "auto", flexShrink: 0,
                  filter: "drop-shadow(0 8px 14px rgba(15,15,15,0.22))",
                  display: "block" }} />
  );
}

/* ===== Sales Notification — reads shared lastSale state so it syncs with the top ticker ===== */
function SalesNotification() {
  const { lastSale, saleNonce } = useCounters();
  const [phase, setPhase] = React.useState("hidden"); // 'in' | 'out' | 'hidden'
  const dismissed = React.useRef(false);
  const outTimer = React.useRef(null);
  const hideTimer = React.useRef(null);

  // Whenever lastSale rotates (saleNonce bumps), show a popup tied to that sale.
  React.useEffect(() => {
    if (dismissed.current) return;
    // small delay so the ticker text "clicks over" a beat before the popup arrives.
    // saleNonce === 0 is the page-load state (no sale has fired yet), so don't show then.
    if (saleNonce === 0) return;
    const inT = setTimeout(() => setPhase("in"), 400);
    clearTimeout(outTimer.current);
    clearTimeout(hideTimer.current);
    outTimer.current = setTimeout(() => setPhase("out"), 8400);
    hideTimer.current = setTimeout(() => setPhase("hidden"), 8720);
    return () => {
      clearTimeout(inT);
      clearTimeout(outTimer.current);
      clearTimeout(hideTimer.current);
    };
  }, [saleNonce]);

  if (!lastSale || phase === "hidden" || dismissed.current) return null;

  return (
    <div className="fixed z-40 pointer-events-none sales-notif-anchor"
         style={{ left: "max(12px, env(safe-area-inset-left))",
                  bottom: "calc(96px + env(safe-area-inset-bottom))" }}>
      <div className={`bg-surface pointer-events-auto ${phase === "in" ? "notif-in" : "notif-out"}`}
           role="status" aria-live="polite"
           style={{ borderRadius: 14, padding: 12, paddingRight: 30,
                    border: "1px solid rgba(200,162,74,0.45)",
                    boxShadow: "0 14px 36px rgba(15,15,15,0.18)",
                    width: "min(86vw, 320px)", minWidth: 240 }}>
        <div className="flex items-start gap-3">
          <MiniBook />
          <div className="leading-tight min-w-0 flex-1">
            <div className="font-ui text-ink truncate" style={{ fontSize: 13.5, fontWeight: 600 }}>
              {lastSale.name}
              <span className="text-muted font-normal"> · {lastSale.city}</span>
            </div>
            <div className="font-body text-gold-h mt-0.5" style={{ fontSize: 13 }}>
              just got The Blueprint
            </div>
            <div className="flex items-center gap-1.5 mt-1 font-ui text-muted" style={{ fontSize: 11 }}>
              <Icon name="Clock" size={11} color="#6B655B" />
              <span>{_formatTime(lastSale.minutesAgo)}</span>
            </div>
          </div>
        </div>
        <button aria-label="Dismiss notification"
                onClick={() => { dismissed.current = true; setPhase("out"); }}
                className="absolute top-2 right-2 text-muted hover:text-ink p-1 rounded"
                style={{ background: "transparent" }}>
          <Icon name="X" size={12} color="currentColor" />
        </button>
      </div>
    </div>
  );
}

/* ── Scroll Progress Indicator ───────────────────────── */
function ScrollProgress() {
  const [pct, setPct] = React.useState(0);
  React.useEffect(() => {
    const onScroll = () => {
      const el = document.documentElement;
      const scrolled = el.scrollTop || document.body.scrollTop;
      const total = el.scrollHeight - el.clientHeight;
      setPct(total > 0 ? Math.min(100, (scrolled / total) * 100) : 0);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <div style={{
      position: "fixed", top: 0, left: 0, right: 0, height: 3,
      zIndex: 9999, pointerEvents: "none",
      background: "rgba(200,162,74,0.15)"
    }}>
      <div style={{
        width: `${pct}%`, height: "100%",
        background: "linear-gradient(90deg, #D97757, #C8A24A, #2C3A24)",
        transition: "width 120ms linear",
        boxShadow: "0 0 8px rgba(200,162,74,0.60)"
      }} />
    </div>
  );
}

Object.assign(window, {
  CounterProvider, useCounters,
  TopStatusBar, NavBar, StickyBottomCTA, SalesNotification, MiniBook, ScrollProgress
});
