// WattWatch — section components

const { useState, useMemo, useEffect } = React;

// ─── SVG bolts ───────────────────────────────────────────────────────
const BoltIcon = ({ size = 24, color = "currentColor", ...p }) => (
  <svg viewBox="0 0 24 24" width={size} height={size} fill={color} aria-hidden="true" {...p}>
    <path d="M13.5 2 4 14h6.5L9 22l9.5-12H12l1.5-8z" />
  </svg>
);

const PlugIcon = ({ size = 40 }) => (
  <svg viewBox="0 0 48 48" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
    <rect x="14" y="6" width="20" height="22" rx="6" />
    <line x1="20" y1="2" x2="20" y2="8" />
    <line x1="28" y1="2" x2="28" y2="8" />
    <path d="M24 28v8c0 4 4 6 4 10" />
  </svg>
);

const BellIcon = ({ size = 40 }) => (
  <svg viewBox="0 0 48 48" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M24 6c-6 0-10 5-10 11v6l-4 6h28l-4-6v-6c0-6-4-11-10-11z" />
    <path d="M20 36c0 2 2 4 4 4s4-2 4-4" />
    <line x1="24" y1="2" x2="24" y2="6" />
  </svg>
);

const BoltCircleIcon = ({ size = 40 }) => (
  <svg viewBox="0 0 48 48" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="24" cy="24" r="18" />
    <path d="M26 12 16 26h8l-2 10 10-14h-8l2-10z" fill="currentColor" stroke="none" />
  </svg>
);

// Big neon Z (logo)
const ZapZ = ({ size = 28, color }) => (
  <svg viewBox="0 0 32 40" width={size} height={size * 40 / 32} aria-hidden="true">
    <path d="M4 4h24L12 22h14l-4 14H6L18 18H4z" fill={color || "var(--yellow)"} style={{ filter: "drop-shadow(0 0 8px currentColor)", color: color || "var(--yellow)" }} />
  </svg>
);

// ─── Logomarks ───────────────────────────────────────────────────────
// Each renders inside the nav (~28px) and footer (~36px). All accept `size`.

const LogoBoltCircle = ({ size = 28 }) => (
  <svg viewBox="0 0 40 40" width={size} height={size} aria-hidden="true">
    <circle cx="20" cy="20" r="17" fill="none" stroke="var(--yellow)" strokeWidth="2.5" />
    <path d="M22 9 13 22h6l-2 9 9-13h-6l2-9z" fill="var(--yellow)" />
  </svg>
);

const LogoMeter = ({ size = 28 }) => (
  <svg viewBox="0 0 40 40" width={size} height={size} aria-hidden="true">
    {/* speedometer arc */}
    <path d="M6 26 A 16 16 0 0 1 34 26" fill="none" stroke="var(--cyan)" strokeWidth="2.5" strokeLinecap="round" />
    <path d="M10 26 A 11 11 0 0 1 30 26" fill="none" stroke="var(--yellow)" strokeWidth="2" strokeLinecap="round" opacity="0.6" />
    {/* needle as a bolt */}
    <path d="M22 11 17 23h4l-2 6 7-10h-4l2-8z" fill="var(--magenta)" />
    <circle cx="20" cy="26" r="2" fill="var(--yellow)" />
  </svg>
);

const LogoWaveBolt = ({ size = 28 }) => (
  <svg viewBox="0 0 44 40" width={size * 44 / 40} height={size} aria-hidden="true">
    {/* three horizontal bars like a signal/eq */}
    <rect x="2"  y="12" width="6" height="16" rx="1" fill="var(--cyan)" />
    <rect x="11" y="6"  width="6" height="28" rx="1" fill="var(--magenta)" />
    <rect x="20" y="14" width="6" height="12" rx="1" fill="var(--cyan)" />
    {/* bolt overlapping */}
    <path d="M36 4 28 22h6l-2 14 10-18h-6l2-14z" fill="var(--yellow)" />
  </svg>
);

const LogoPowerBolt = ({ size = 28 }) => (
  <svg viewBox="0 0 40 40" width={size} height={size} aria-hidden="true">
    {/* power ring with a gap at top */}
    <path d="M14 6 A 16 16 0 1 0 26 6" fill="none" stroke="var(--cyan)" strokeWidth="3" strokeLinecap="round" />
    {/* bolt where the power-button stem would be */}
    <path d="M22 4 15 20h5l-2 12 9-16h-5l2-12z" fill="var(--yellow)" />
  </svg>
);

const LogoBracketW = ({ size = 28 }) => (
  <svg viewBox="0 0 48 40" width={size * 48 / 40} height={size} aria-hidden="true">
    {/* corner brackets like a terminal target */}
    <path d="M3 11 V4 H10" fill="none" stroke="var(--cyan)" strokeWidth="2.5" strokeLinecap="round" />
    <path d="M45 11 V4 H38" fill="none" stroke="var(--cyan)" strokeWidth="2.5" strokeLinecap="round" />
    <path d="M3 29 V36 H10" fill="none" stroke="var(--cyan)" strokeWidth="2.5" strokeLinecap="round" />
    <path d="M45 29 V36 H38" fill="none" stroke="var(--cyan)" strokeWidth="2.5" strokeLinecap="round" />
    {/* center W made of two bolts */}
    <path d="M14 10 18 26 22 16 26 26 30 16 34 26" fill="none" stroke="var(--yellow)" strokeWidth="3" strokeLinejoin="miter" strokeLinecap="square" />
  </svg>
);

const LogoSpark = ({ size = 28 }) => (
  <svg viewBox="0 0 40 40" width={size} height={size} aria-hidden="true">
    {/* 4-point spark / sparkle */}
    <path d="M20 3 L23 17 L37 20 L23 23 L20 37 L17 23 L3 20 L17 17 Z" fill="var(--yellow)" />
    <circle cx="20" cy="20" r="3" fill="var(--magenta)" />
  </svg>
);

const LOGO_MARKS = {
  none:      null,
  boltcircle: LogoBoltCircle,
  meter:     LogoMeter,
  waveBolt:  LogoWaveBolt,
  powerBolt: LogoPowerBolt,
  bracketW:  LogoBracketW,
  spark:     LogoSpark,
};

function LogoMark({ mark = "boltcircle", size = 28 }) {
  const C = LOGO_MARKS[mark];
  if (!C) return null;
  return <C size={size} />;
}

// ─── Nav ─────────────────────────────────────────────────────────────
function Nav({ mark }) {
  return (
    <nav className="zw-nav">
      <div className="zw-logo">
        <LogoMark mark={mark} size={28} />
        <span className="neon neon-y">WATTWATCH</span>
      </div>
      <div className="zw-nav-links">
        <a href="#how">How it works</a>
        <a href="#rules">Alert rules</a>
        <a href="#faq">FAQ</a>
      </div>
      <a href="#rules" className="zw-nav-cta">What we watch</a>
    </nav>
  );
}

// ─── Hero with live ticker ───────────────────────────────────────────
function Hero({ price, stale, updatedAt, isOverride }) {
  const hasPrice = typeof price === "number" && Number.isFinite(price);
  const isNeg = hasPrice && price < 0;
  const isCheap = hasPrice && price >= 0 && price < 2;
  const status = !hasPrice
    ? "Waiting on first reading…"
    : isNeg
      ? "⚡ FREE ELECTRONS — PLUG IT ALL IN ⚡"
      : isCheap
        ? "Cheap juice. Run the dishwasher."
        : "Standard rates. Patience, young watt.";
  const statusColor = isNeg ? "neon-g" : isCheap ? "neon-c" : "neon-y";

  // Eyebrow reflects the live/stale/override state so the user can tell at a
  // glance whether they're looking at real ComEd data or a Tweaks override.
  const eyebrowText = isOverride
    ? "DEMO OVERRIDE · TWEAKS PANEL"
    : stale && !hasPrice
      ? "UNAVAILABLE · CAN’T REACH COMED"
      : stale
        ? "STALE · SHOWING LAST KNOWN PRICE"
        : !hasPrice
          ? "LOADING · COMED HOURLY PRICING"
          : "LIVE FROM THE GRID · COMED HOURLY PRICING";

  // "updated …" subtitle. When we have a real timestamp from the last
  // successful fetch, show it; otherwise fall back to a placeholder so we
  // never lie about a fixed "1m ago".
  const updatedText = updatedAt instanceof Date
    ? `updated ${updatedAt.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}`
    : isOverride
      ? "demo value — live updates paused"
      : "awaiting first reading";

  // sparkline heights, animated
  const bars = Array.from({ length: 9 }, (_, i) => i);

  return (
    <section className="zw-hero">
      <div className="zw-shell">
        <div className="zw-hero-eyebrow flicker">
          <BoltIcon size={14} color="var(--yellow)" />
          {eyebrowText}
          <BoltIcon size={14} color="var(--yellow)" />
        </div>

        <h1>
          <span className="l1 neon">CATCH</span>
          <br />
          <span className="l2 neon-strong">FREE WATTS.</span>
        </h1>

        <p className="zw-hero-sub">
          We watch the ComEd hourly real‑time price 24/7. When per‑kWh prices
          drop <b>below zero</b>, you get pinged. Run your dryer, charge your car,
          or just run the watts directly into the ground. All on the utility’s dime.
        </p>

        {/* TICKER */}
        <div className="zw-ticker" data-neg={isNeg ? "1" : "0"}>
          <div className="zw-ticker-label neon neon-c">
            Right now in Chicagoland
          </div>
          <div className={`zw-ticker-price neon-strong ${isNeg ? "neon-g" : "neon-m"}`}>
            {hasPrice ? `${price.toFixed(1)}¢` : "—¢"}
          </div>
          <div className="zw-ticker-unit">per kilowatt‑hour (current-hour avg) · {updatedText}</div>
          <div className={`zw-ticker-status neon ${statusColor}`}>
            {status}
          </div>
          <div className="zw-ticker-spark" aria-hidden="true">
            {bars.map(i => (
              <i key={i} style={{
                height: `${20 + Math.abs(Math.sin(i * 1.3)) * 80}%`,
                animationDelay: `${i * 0.13}s`,
                background: isNeg ? "var(--neg)" : i === 4 ? "var(--magenta)" : "var(--cyan)",
                color: isNeg ? "var(--neg)" : "var(--cyan)",
              }} />
            ))}
          </div>
        </div>

        <div className="zw-cta-row">
          <a href="#rules" className="zw-btn zw-btn-primary">
            <BoltIcon size={20} color="#0a0118" /> See what we watch for
          </a>
          <a href="#how" className="zw-btn zw-btn-ghost">How it works</a>
        </div>
      </div>

      {/* floating bolts */}
      <BoltIcon size={62} color="var(--magenta)" className="zw-bolt-float" style={{ top: 80, left: "6%", color: "var(--magenta)", "--r": "-14deg" }} />
      <BoltIcon size={44} color="var(--cyan)" className="zw-bolt-float" style={{ top: 260, right: "8%", color: "var(--cyan)", "--r": "18deg", animationDelay: "1.2s" }} />
      <BoltIcon size={32} color="var(--yellow)" className="zw-bolt-float" style={{ bottom: 60, left: "12%", color: "var(--yellow)", "--r": "8deg", animationDelay: "2.4s" }} />
    </section>
  );
}

// ─── Marquee ─────────────────────────────────────────────────────────
function Marquee() {
  const phrases = [
    "FREE ELECTRONS INCOMING!",
    "PLUG IN. POWER UP.",
    "NEGATIVE PRICES = POSITIVE VIBES",
    "WATCH THE WATTS",
    "WHEN IT GOES BELOW ZERO, YOU GO ALL IN",
  ];
  const items = [];
  for (let i = 0; i < 3; i++) phrases.forEach(p => items.push(p));
  return (
    <div className="zw-marquee" aria-hidden="true">
      <div className="zw-marquee-track">
        {items.map((p, i) => (
          <React.Fragment key={i}>
            <span>{p}</span>
            <span className="dot">⚡</span>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

// ─── How it works ────────────────────────────────────────────────────
function HowItWorks() {
  return (
    <section id="how">
      <div className="zw-shell">
        <p className="zw-eyebrow neon-c neon">HOW IT WORKS</p>
        <h2 className="zw-h2 neon neon-m">Three plugs. Zero math.</h2>

        <div className="zw-steps">
          <div className="zw-step">
            <span className="zw-step-n c neon neon-c">01</span>
            <div className="zw-step-icon neon-c"><PlugIcon /></div>
            <h3 className="neon neon-c">We watch the price.</h3>
            <p>
              We check ComEd’s hourly pricing every minute. Live read,
              nothing stored.
            </p>
          </div>

          <div className="zw-step">
            <span className="zw-step-n m neon neon-m">02</span>
            <div className="zw-step-icon neon-m"><BoltCircleIcon /></div>
            <h3 className="neon neon-m">Our rules trigger.</h3>
            <p>
              A handful of curated thresholds run against every reading. The
              instant one trips, an alert fires — no debouncing, no waiting.
            </p>
          </div>

          <div className="zw-step">
            <span className="zw-step-n y neon neon-y">03</span>
            <div className="zw-step-icon neon-y"><BellIcon /></div>
            <h3 className="neon neon-y">You get pinged.</h3>
            <p>
              Subscribers receive a push the moment a rule fires. Then it’s
              your call: laundry, EV, AC, big batch of cookies.
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Alert rules (presentational only) ─────────────────────────────
const ALERT_RULES = [
  {
    accent: "neg",
    name: "Free Electrons",
    op: "<",
    threshold: "0.0¢",
    why: "Wholesale prices flipped negative. The grid is paying users to plug things in.",
    tags: ["DO LAUNDRY", "CHARGE EV", "BAKE BREAD"],
    rarity: "RARE",
  },
  {
    accent: "cyan",
    name: "Cheap Juice",
    op: "<",
    threshold: "1.5¢",
    why: "Off‑peak window. Run heavy appliances now and you'll feel it on the bill.",
    tags: ["DISHWASHER", "DRYER", "POOL PUMP"],
    rarity: "COMMON",
  },
  {
    accent: "yellow",
    name: "Mega Spendy",
    op: ">",
    threshold: "8.0¢",
    why: "Demand spike. Hold off on the optional stuff for an hour or two.",
    tags: ["HOLD AC", "DELAY EV", "SKIP DRYER"],
    rarity: "OCCASIONAL",
  },
];

const accentMap = {
  neg:     { color: "var(--neg)",     label: "neon-g" },
  cyan:    { color: "var(--cyan)",    label: "neon-c" },
  magenta: { color: "var(--magenta)", label: "neon-m" },
  yellow:  { color: "var(--yellow)",  label: "neon-y" },
};

function RuleCard({ rule }) {
  const a = accentMap[rule.accent];
  return (
    <div className="zw-rule" style={{ color: a.color }}>
      <div className="zw-rule-top">
        <span className="zw-rule-rarity">{rule.rarity}</span>
        <BoltIcon size={20} color={a.color} />
      </div>
      <p className={`zw-rule-name neon ${a.label}`}>{rule.name}</p>
      <div className="zw-rule-thresh">
        <span className="op">price</span>
        <span className="sym">{rule.op}</span>
        <span className={`val neon ${a.label}`}>{rule.threshold}</span>
      </div>
      <p className="zw-rule-why">{rule.why}</p>
      <div className="zw-rule-tags">
        {rule.tags.map(t => <span key={t} className="zw-rule-tag">{t}</span>)}
      </div>
    </div>
  );
}

function AlertRules() {
  return (
    <section id="rules">
      <div className="zw-shell">
        <p className="zw-eyebrow neon-y neon">WHAT WE WATCH FOR</p>
        <h2 className="zw-h2 neon neon-m">Three rules.<br />That’s the whole list.</h2>
        <p style={{ maxWidth: 680, fontSize: 19, color: "var(--ink-dim)", margin: "0 0 40px" }}>
          WattWatch runs a small, opinionated set of alert rules against every
          price reading. You don’t configure them — we keep them tuned. Subscribe
          to any one and we’ll ping you the instant it trips.
        </p>

        <div className="zw-rules">
          {ALERT_RULES.map(r => <RuleCard key={r.name} rule={r} />)}
        </div>
      </div>
    </section>
  );
}

// ─── FAQ ─────────────────────────────────────────────────────────────
const FAQ_ITEMS = [
  {
    q: "Wait, electricity can really be free?",
    a: "Sometimes it’s better than free. When renewable supply outstrips demand — windy nights, sunny weekends — wholesale prices on ComEd’s real‑time hourly plan can dip below zero. If you’re on the hourly rate, you get paid (in credits) to use power. WATTWATCH tells you when.",
  },
  {
    q: "Why are there only three alert rules?",
    a: "Because every rule we add is one more thing to tune and one more reason to wake you up. Three is enough to capture ‘absurdly cheap’, ‘meaningfully cheap’, and ‘hold off’. More than that and the signal turns into noise.",
  },
  {
    q: "Why no chart of past prices?",
    a: "Because keeping history means keeping storage — and storage means a bill, a database, and a thing to keep secure. WattWatch only ever shows you what’s happening right now. The past doesn’t help you save money tonight.",
  },
  {
    q: "How fast are the alerts?",
    a: "We check ComEd’s public hourly pricing every 60 seconds. When a rule trips, your alert lands within a few seconds. If a check fails, we try again.",
  },
  {
    q: "Is this affiliated with ComEd?",
    a: "Nope. WattWatch is an independent project that reads ComEd’s public hourly pricing feed. Fans, not employees.",
  },
];

function FAQ() {
  const [open, setOpen] = useState(0);
  return (
    <section id="faq">
      <div className="zw-shell">
        <p className="zw-eyebrow neon-c neon">QUESTIONS</p>
        <h2 className="zw-h2 neon neon-c">Things people ask.</h2>

        <div className="zw-faq-list">
          {FAQ_ITEMS.map((item, i) => (
            <div key={i} className="zw-faq-item" data-open={open === i ? "1" : "0"}>
              <button className="zw-faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{item.q}</span>
                <i>+</i>
              </button>
              <div className="zw-faq-a">{item.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Footer ──────────────────────────────────────────────────────────
function Footer({ mark }) {
  return (
    <footer className="zw-foot">
      <div className="zw-logo neon neon-y">
        <LogoMark mark={mark} size={36} />
        <span>WATTWATCH</span>
      </div>
      <p>Made by humans who like cheap electrons.</p>
      <p style={{ color: "var(--ink-dim)" }}>
        Independent project · Data from <a href="https://hourlypricing.comed.com/live-prices/" target="_blank" rel="noreferrer">ComEd hourly pricing</a>
      </p>
      <p style={{ marginTop: 20, color: "rgba(247,233,255,.35)" }}>
        © 2026 · No watts were harmed in the making of this site
      </p>
    </footer>
  );
}

Object.assign(window, {
  BoltIcon, ZapZ, LogoMark,
  Nav, Hero, Marquee, HowItWorks, AlertRules, FAQ, Footer,
});
