/* ============================================================
   PWC SECTIONS — part 1
   Global CSS + the C-CALL primitive + header, hero, stakes,
   value props, guide.
   ============================================================ */
const { INV } = window.PWC;

/* ---------- reveal wrapper (content always visible; entrance handled in CSS) ---------- */
function useReveal() { return React.useRef(null); }
function Reveal({ children, as = "div", className = "", style, delay = 0 }) {
  const ref = useReveal();
  const Tag = as;
  return <Tag ref={ref} className={`reveal ${className}`} style={{ ...style, transitionDelay: delay ? `${delay}ms` : undefined }}>{children}</Tag>;
}

/* ---------- C-CALL: the most important primitive ---------- */
function CallButton({ size = "xl", label, className = "", ...rest }) {
  return (
    <a href={`tel:${INV.tel}`} className={`call-btn call-${size} ${className}`} aria-label={`Call now, ${INV.phone}`} {...rest}>
      <span className="call-ico"><IconPhone size={size === "md" ? 18 : 22} stroke="var(--ember-ink)" /></span>
      <span className="call-txt">{label || <>Call Now<span className="call-num tnum"> {INV.phone}</span></>}</span>
    </a>
  );
}

/* ---------- Save the number (vCard) ---------- */
function buildVCard() {
  return [
    "BEGIN:VCARD", "VERSION:3.0",
    "N:Well Control;Permian;;;", "FN:Permian Well Control",
    "ORG:Permian Well Control", "TITLE:Rapid-Response Well Control",
    `TEL;TYPE=CELL,VOICE:${INV.tel}`, `EMAIL:${INV.email}`,
    "ADR;TYPE=WORK:;;Midland;TX;;;USA",
    "NOTE:Early stabilization, informed escalation. West Texas & SE New Mexico.",
    "END:VCARD",
  ].join("\n");
}
function SaveButton({ tone = "ghost", onSaved, className = "" }) {
  const save = (e) => {
    const blob = new Blob([buildVCard()], { type: "text/vcard" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = "Permian-Well-Control.vcf";
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1500);
    onSaved && onSaved();
  };
  return (
    <button type="button" onClick={save} className={`btn-ghost ${tone === "solid" ? "btn-ghost-solid" : ""} ${className}`}>
      {INV.ctaSave}
    </button>
  );
}

/* ---------- Life-safety precedence line (C-SAFETY) ---------- */
function SafetyLine({ variant = "hero" }) {
  return (
    <p className={`safety safety-${variant}`}>
      <span className="safety-ico" aria-hidden="true"><IconShield size={15} /></span>
      <span>
        <strong>Life-threatening — fire, injury, or H2S?</strong> Call{" "}
        <a href="tel:911" className="safety-911">911</a> first, then call us:{" "}
        <a href={`tel:${INV.tel}`} className="safety-num tnum">{INV.phone}</a>.
      </span>
    </p>
  );
}

/* ---------- decorative contour field (echoes logo + coverage bands) ---------- */
function ContourField() {
  return (
    <svg className="hero-topo" viewBox="0 0 600 600" fill="none" aria-hidden="true" preserveAspectRatio="xMaxYMid slice">
      <g stroke="#ffffff" strokeWidth="1.1" opacity="0.16">
        {[60, 130, 200, 270, 340, 410].map((r, i) => (
          <rect key={i} x={300 - r} y={300 - r} width={r * 2} height={r * 2} rx={r * 0.28} />
        ))}
      </g>
      <g stroke="var(--ember)" strokeWidth="2" opacity="0.5">
        <path d="M280 300h40M300 280v40" />
      </g>
    </svg>
  );
}

/* ============================ HEADER (C-HDR) ============================ */
function Header({ flavor, logo = "reticle", active, overDark = false }) {
  const [open, setOpen] = React.useState(false);
  const [solid, setSolid] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setSolid(window.scrollY > 12);
    onScroll(); window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <header className={`hdr ${solid ? "hdr-solid" : ""} ${overDark ? "over-dark" : ""}`}>
      <div className="wrap hdr-in">
        <a href={INV.home} className="brand" aria-label="Permian Well Control home">
          <PWCMark size={34} variant={logo} steel="var(--text)" />
          <span className="brand-word">
            <span className="brand-line1">PERMIAN</span>
            <span className="brand-line2">WELL CONTROL</span>
          </span>
        </a>

        <nav className="nav-desk" aria-label="Primary">
          {INV.nav.map((n) => <a key={n.label} href={n.href} className={active === n.label ? "active" : ""}>{n.label}</a>)}
        </nav>

        <div className="hdr-right">
          <CallButton size="md" className="hdr-call" />
          <button className="hamburger" aria-label="Menu" aria-expanded={open} onClick={() => setOpen((v) => !v)}>
            <span /><span /><span />
          </button>
        </div>
      </div>

      {open && (
        <div className="mobile-menu">
          <nav aria-label="Mobile">
            {INV.nav.map((n) => <a key={n.label} href={n.href} onClick={() => setOpen(false)}>{n.label}</a>)}
          </nav>
          <div className="mobile-menu-cta">
            <CallButton size="block" />
            <SafetyLine variant="menu" />
          </div>
        </div>
      )}
    </header>
  );
}

/* ============================ HERO (C-HERO) ============================ */
function Hero({ flavor, tone }) {
  const f = window.PWC.FLAVORS[flavor];
  const sub = window.PWC.heroSub(flavor, tone);
  return (
    <section className="hero">
      <image-slot id="pwc-hero-bg" class="hero-bg" shape="rect"
        placeholder="Drop a West Texas field photo — a controlled location at dusk (not flames)"></image-slot>
      <div className="hero-scrim" />
      <ContourField />
      <div className="wrap hero-in">
        <Reveal className="hero-content">
          <p className="eyebrow hero-eyebrow"><span className="loc-dot" />{INV.area}</p>
          <h1 className="hero-h1">{f.h1}</h1>
          <p className="hero-sub">{sub}</p>
          <div className="hero-cta">
            <CallButton size="xl" />
            <SaveButton tone="ghost" />
          </div>
          <SafetyLine variant="hero" />
        </Reveal>
      </div>
      <p className="hero-triage wrap">{INV.heroTriage}</p>
    </section>
  );
}

/* ============================ STAKES (C-STAKE) ============================ */
function Stakes() {
  const s = INV.stakes;
  return (
    <section className="section stakes">
      <div className="wrap stakes-in">
        <Reveal className="stakes-head">
          <p className="eyebrow">The cost of waiting</p>
          <h2 className="stakes-h">{s.h}</h2>
        </Reveal>
        <Reveal className="stakes-body" delay={80}>
          <p className="stakes-hook">{s.hook}</p>
          <ul className="stakes-list">
            {s.bullets.map((b, i) => (
              <li key={i}><span className="stake-mark" aria-hidden="true"><IconArrow size={15} /></span>{b}</li>
            ))}
          </ul>
        </Reveal>
      </div>
    </section>
  );
}

/* ============================ VALUE PROPS (C-VP) ============================ */
function ValueProps({ flavor }) {
  const f = window.PWC.FLAVORS[flavor];
  return (
    <section className="section vp-section alt">
      <div className="wrap">
        <Reveal className="sec-head">
          <p className="eyebrow">{f.eyebrow}</p>
          <h2 className="sec-h">What calling early gets you.</h2>
        </Reveal>
        <div className="vp-grid">
          {f.beats.map((b, i) => {
            const Icon = VP_ICONS[i] || VP_ICONS[0];
            return (
              <Reveal key={i} className="vp-card" as="article" delay={i * 90}>
                <span className="vp-ico" aria-hidden="true"><Icon size={28} /></span>
                <h3 className="vp-h">{b.t}</h3>
                <p className="vp-b">{b.b}</p>
              </Reveal>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ============================ GUIDE (C-GUIDE) ============================ */
function Guide({ flavor }) {
  const f = window.PWC.FLAVORS[flavor];
  return (
    <section className="section guide">
      <div className="wrap guide-in">
        <Reveal className="guide-text">
          <p className="eyebrow">Who answers</p>
          <h2 className="sec-h">We know what a well getting away costs. We've answered the call.</h2>
          <p className="guide-lead">{f.guideLead}</p>
          <p className="guide-lead">{INV.founderDirect}</p>
          <div className="auth-grid">
            {INV.authority.map((a, i) => (
              <div className="auth-cell" key={i}>
                <div className="auth-stat tnum">{a.stat}</div>
                <div className="auth-label">{a.label}</div>
              </div>
            ))}
          </div>
        </Reveal>
        <Reveal className="guide-media" delay={80}>
          <image-slot id="pwc-founder" class="founder-slot" shape="rect" radius="10"
            placeholder="Drop a real field photo of Michael — rig floor / location, not corporate"></image-slot>
          <div className="founder-cap">
            <span className="founder-name">{INV.founderName}</span>
            <span className="founder-role">{INV.founderRole}</span>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, {
  useReveal, Reveal, CallButton, SaveButton, SafetyLine, ContourField,
  Header, Hero, Stakes, ValueProps, Guide,
});
