/* Tidewell — page sections (homepage + shared) */

const { useState: useStateS, useEffect: useEffectS, useMemo: useMemoS } = React;
const LinkS = (props) => window.Link(props);

/* ─────────── Top utility bar ─────────── */
function Topbar({ region }) {
  const r = window.REGION_DATA[region];
  return (
    <div className="topbar">
      <div className="container">
        <div className="links">
          <a href="#/">Free freight on dealer orders 2K+</a>
        </div>
        <div className="links">
          <a href="#/">Dealers</a>
          <a href="#/">Spec sheets</a>
          <a href="#/contact">{r.phone}</a>
        </div>
      </div>
    </div>
  );
}

/* ─────────── Header / nav ─────────── */
function Header({ region, setRegion }) {
  return (
    <header className="header">
      <div className="container">
        <a href="#/" className="brand">
          <span className="brand-mark"></span>
          Tidewell
        </a>
        <nav className="nav">
          <a href="#/products" className="has-sub">Products</a>
          <a href="#/applications">Applications</a>
          <a href="#/#planner">Pool Planner</a>
          <a href="#/about">About</a>
          <a href="#/contact">Contact</a>
        </nav>
        <div className="header-right">
          <div className="region-toggle" role="tablist" aria-label="Region">
            <button
              role="tab"
              aria-selected={region === "US"}
              className={region === "US" ? "active" : ""}
              onClick={() => setRegion("US")}
            >US</button>
            <button
              role="tab"
              aria-selected={region === "CA"}
              className={region === "CA" ? "active" : ""}
              onClick={() => setRegion("CA")}
            >CA</button>
          </div>
          <a href="#/contact" className="btn">
            Request Quote
            <span className="arr"></span>
          </a>
        </div>
      </div>
    </header>
  );
}

/* ─────────── Reusable styled product card ─────────── */
function ProductCard({ p, featured, region }) {
  const { formatPrice } = window;
  return (
    <a
      href={"#/products/" + p.slug}
      className={"product-card" + (featured ? " featured" : "")}
      aria-label={p.name}
    >
      <div className="pc-img">
        <img src={p.image} alt={p.name} loading="lazy" onError={(e) => { e.currentTarget.style.display = "none"; }} />
        <span className="pc-num-badge">{p.n} / 10</span>
        <div className="pc-caption">
          <span>{p.category}</span>
          <span>{p.short}</span>
        </div>
      </div>
      <div>
        <div className="pc-title">{p.name}</div>
        <div className="pc-meta" style={{ marginTop: 8 }}>
          <span>{p.short}</span>
        </div>
      </div>
      <div className="pc-meta">
        <span className="mono">From {formatPrice(p.priceUSD, region)}</span>
        <span className="arrow" aria-hidden="true">→</span>
      </div>
    </a>
  );
}

/* ─────────── Hero (homepage) ─────────── */
function Hero({ region, variant }) {
  const r = window.REGION_DATA[region];
  // Editorial hero — night pool with cover & underwater light glow
  const heroPhoto = "images/filter-pump.jpg";
  return (
    <section className="hero" data-hero={variant}>
      <div className="container">
        <div className="hero-grid">
          <div>
            <div className="eyebrow">North America Edition · Est. 2008</div>
            <h1 style={{ marginTop: 28 }}>
              Pool equipment,<br />
              <em>obsessively</em><br />
              engineered.
            </h1>
            <p className="hero-sub">
              {r.tagline}. Ten product lines, one ecosystem — covers, heating, sanitation, filtration, lighting — built to spec, shipped from {region === "US" ? "Phoenix and Charlotte" : "Mississauga and Calgary"}, supported by a dealer network you can actually reach.
            </p>
            <div className="hero-cta">
              <a className="btn" href="#/products">Browse the catalog<span className="arr"></span></a>
              <a className="btn btn-ghost" href="#/#planner">Configure my pool</a>
            </div>
            <dl className="hero-meta">
              <div>
                <dt>Established</dt>
                <dd>2008</dd>
              </div>
              <div>
                <dt>Pools shipped</dt>
                <dd>42,180</dd>
              </div>
              <div>
                <dt>Warranty</dt>
                <dd>10<span className="unit">years</span></dd>
              </div>
            </dl>
          </div>
          <div className="hero-visual" aria-label="Tracked automatic pool cover at night">
            <img src={heroPhoto} alt="Pool with automatic cover retracted, lit at night" />
            <span className="placeholder-tag">Toronto, ON · 9:18 PM</span>
            <div className="float-card">
              <span className="dot"></span>
              <div>
                <div className="label">Water temp · in-pool sensor</div>
                <div className="value">{region === "US" ? "84 °F" : "29 °C"}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─────────── Marquee compliance bar ─────────── */
function Marquee({ region }) {
  const r = window.REGION_DATA[region];
  const items = [
    "Designed in North America",
    `${r.certs.join(" · ")} certified`,
    "Free freight on dealer orders",
    "Ships in 5 business days",
    "10-year manufacturer warranty",
    "Built for −40° winters"
  ];
  return (
    <div className="marquee" aria-hidden="true">
      <div className="marquee-track">
        {[0, 1].map(j => (
          <span key={j}>
            {items.map((t, i) => (
              <React.Fragment key={i}>
                {t}
                <span className="dot"></span>
              </React.Fragment>
            ))}
          </span>
        ))}
      </div>
    </div>
  );
}

/* ─────────── Product grid (homepage section) ─────────── */
function ProductGrid({ region, cardStyle }) {
  return (
    <section className="section" id="products" data-cardstyle={cardStyle}>
      <div className="container">
        <div className="section-head">
          <div>
            <div className="eyebrow">01 / Catalog</div>
            <h2 className="display">Ten product lines.<br />One <em style={{ fontStyle: "italic" }}>ecosystem</em>.</h2>
          </div>
          <p>
            Every Tidewell product is built to work together — same controller bus, same plumbing dimensions, same warranty desk. Mix and match without an integration project.
          </p>
        </div>
        <div className="product-grid">
          {window.PRODUCTS.map((p) => (
            <ProductCard key={p.slug} p={p} featured={p.featured} region={region} />
          ))}
        </div>
        <div style={{ marginTop: 40, display: "flex", justifyContent: "flex-end" }}>
          <a href="#/products" className="btn btn-ghost">
            View full catalog
            <span className="arr"></span>
          </a>
        </div>
      </div>
    </section>
  );
}

/* ─────────── Certifications ─────────── */
function Certs({ region }) {
  const data = {
    US: [
      { code: "UL", title: "UL Listed", desc: "All electrical components carry UL 1081 listing for pool equipment." },
      { code: "ETL", title: "ETL / Intertek", desc: "Heat pumps and chlorinators independently verified to ANSI standards." },
      { code: "NSF/50", title: "NSF-50 Materials", desc: "Pool fittings, filters and feeders certified for potable contact." },
      { code: "APSP-7", title: "APSP-7 Safety", desc: "Suction-entrapment compliant. VGB Act covered. Drain covers ANSI/APSP-16." }
    ],
    CA: [
      { code: "CSA", title: "CSA Certified", desc: "Every wired product carries a CSA mark — accepted by all provincial inspectors." },
      { code: "cULus", title: "cULus Listing", desc: "Pumps and lights dual-listed for Canadian and US electrical codes." },
      { code: "NSF/50", title: "NSF-50 Materials", desc: "Pool fittings certified for potable contact under NSF/ANSI 50." },
      { code: "ULC", title: "ULC S102", desc: "Solar collector materials tested to ULC fire-spread for roof-mount." }
    ]
  };
  const items = data[region];
  return (
    <section className="section certs">
      <div className="container">
        <div className="certs-grid">
          <div>
            <div className="eyebrow">02 / Compliance</div>
            <h2 className="display" style={{ fontSize: "clamp(40px,4.5vw,60px)", margin: "16px 0 20px" }}>
              {region === "US" ? "Listed, tested, and inspector-ready." : "Certified for Canadian codes."}
            </h2>
            <p style={{ color: "var(--ink-2)", maxWidth: "42ch" }}>
              {region === "US"
                ? "Tidewell publishes a full certification dossier for every SKU. Your code official will thank you."
                : "Tidewell maintains a complete compliance dossier for every SKU — accepted by every provincial inspector."}
            </p>
            <div style={{ marginTop: 32, display: "flex", gap: 12, flexWrap: "wrap" }}>
              <a className="btn btn-ghost" href="#/products">Download spec library</a>
              <a className="btn btn-ghost" href="#/contact">Find a licensed installer</a>
            </div>
          </div>
          <div className="certs-list">
            {items.map(c => (
              <div className="cert-item" key={c.code}>
                <div className="cert-badge">{c.code}</div>
                <h4>{c.title}</h4>
                <p>{c.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─────────── Pool Planner ─────────── */
function Planner({ region }) {
  const r = window.REGION_DATA[region];
  const [size, setSize] = useStateS(32);
  const [shape, setShape] = useStateS("Rectangle");
  const [climate, setClimate] = useStateS(region === "CA" ? "Cold" : "Warm");
  const [features, setFeatures] = useStateS(["Auto Cover", "Salt"]);

  useEffectS(() => {
    setClimate(region === "CA" ? "Cold" : "Warm");
  }, [region]);

  function toggleFeature(f) {
    setFeatures(features.includes(f) ? features.filter(x => x !== f) : [...features, f]);
  }

  const baseUSD = useMemoS(() => {
    let total = 6000 + (size - 20) * 250;
    if (climate === "Cold") total += 4800;
    if (climate === "Hot") total += 3200;
    if (features.includes("Auto Cover")) total += 8400;
    if (features.includes("Manual Cover")) total += 1200;
    if (features.includes("Salt")) total += 1450;
    if (features.includes("Robotic")) total += 1650;
    if (features.includes("Lights")) total += 960;
    return total;
  }, [size, climate, features]);

  const displaySize = region === "US" ? `${size} ft` : `${(size * 0.305).toFixed(1)} m`;

  return (
    <section className="section planner" id="planner">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="eyebrow">03 / Configurator</div>
            <h2 className="display">Plan your <em>pool</em><br />in 90 seconds.</h2>
          </div>
          <p>
            Tell us the shape, the climate, and the toys. We send back an itemized quote — priced in {r.currency}, shipped to your nearest hub, with the right certifications for your inspector.
          </p>
        </div>

        <div className="planner-card">
          <div className="planner-form">
            <div className="form-group">
              <label>Pool shape</label>
              <div className="options">
                {["Rectangle", "Kidney", "Freeform", "Lap", "Infinity"].map(s => (
                  <button key={s} className={shape === s ? "active" : ""} onClick={() => setShape(s)}>{s}</button>
                ))}
              </div>
            </div>

            <div className="form-group">
              <label>Long-side dimension</label>
              <div className="range-row">
                <span>{displaySize}</span>
                <span className="unit">{r.unitSize === "ft" ? "feet" : "metres"}</span>
              </div>
              <input
                type="range"
                min="16"
                max="60"
                step="2"
                value={size}
                onChange={e => setSize(parseInt(e.target.value, 10))}
              />
            </div>

            <div className="form-group">
              <label>Climate zone</label>
              <div className="options">
                {["Cold", "Temperate", "Warm", "Hot"].map(c => (
                  <button key={c} className={climate === c ? "active" : ""} onClick={() => setClimate(c)}>{c}</button>
                ))}
              </div>
            </div>

            <div className="form-group" style={{ marginBottom: 0 }}>
              <label>Equipment add-ons</label>
              <div className="options">
                {["Auto Cover", "Manual Cover", "Salt", "Robotic", "Lights"].map(f => (
                  <button key={f} className={features.includes(f) ? "active" : ""} onClick={() => toggleFeature(f)}>{f}</button>
                ))}
              </div>
            </div>
          </div>

          <div className="planner-summary">
            <div>
              <h3>Your Tidewell build</h3>
              <div className="sub">Indicative — final quote within one business day</div>

              <div className="line"><span className="name">{shape} pool · {displaySize}</span><span className="val">{window.formatPrice(6000 + (size - 20) * 250, region)}</span></div>
              <div className="line"><span className="name">{climate === "Cold" ? "Inverter heat pump" : climate === "Hot" ? "Solar heating array" : "Climate package"}</span><span className="val">{window.formatPrice(climate === "Cold" ? 4800 : climate === "Hot" ? 3200 : 0, region)}</span></div>
              {features.map(f => {
                const map = { "Auto Cover": 8400, "Manual Cover": 1200, "Salt": 1450, "Robotic": 1650, "Lights": 960 };
                return (
                  <div className="line" key={f}><span className="name">{f}</span><span className="val">{window.formatPrice(map[f], region)}</span></div>
                );
              })}
              <div className="line"><span className="name">Freight to {region === "US" ? "lower 48" : "Canada"}</span><span className="val">included</span></div>
            </div>

            <div>
              <div className="total">
                <div>
                  <div className="label">Estimated total</div>
                </div>
                <div className="amt">
                  {window.formatPrice(baseUSD, region)}
                  <span className="ccy">{r.currency}</span>
                </div>
              </div>
              <a href="#/contact" className="btn btn-light">
                Email me this quote
                <span className="arr"></span>
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─────────── Applications (homepage strip) ─────────── */
function ApplicationsStrip() {
  return (
    <section className="section applications">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="eyebrow">04 / Applications</div>
            <h2 className="display">Pools we've <em>shipped</em>.</h2>
          </div>
          <p>
            From Banff to Boston — every home is different. Browse recent Tidewell installs by climate, scale, and equipment loadout.
          </p>
        </div>

        <div className="app-carousel">
          {window.APPLICATIONS.map((a, i) => (
            <article className="app-card" key={a.name}>
              <div className={"app-img var-" + ((i % 4) + 1)}>
                <span className="loc">{a.loc}</span>
                <span className="ph">Install photo</span>
              </div>
              <h3>{a.name}</h3>
              <div className="meta">
                <span>{a.year}</span>
                <span>{a.type}</span>
              </div>
              <div className="meta" style={{ color: "var(--ink-2)" }}>
                <span>{a.equipment}</span>
              </div>
            </article>
          ))}
        </div>

        <div style={{ marginTop: 32 }}>
          <a href="#/applications" className="btn btn-ghost">All installations<span className="arr"></span></a>
        </div>
      </div>
    </section>
  );
}

/* ─────────── Resources ─────────── */
function Resources() {
  return (
    <section className="section" id="resources">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="eyebrow">05 / Resources</div>
            <h2 className="display">Field notes &amp; <em>guides</em>.</h2>
          </div>
          <p>
            Buying guides, engineering deep-dives and install playbooks — written by the people who actually answer the warranty phone.
          </p>
        </div>

        <div className="resources-grid">
          {window.RESOURCES.map((r, i) => (
            <article key={i} className={"res-card" + (r.feat ? " feature" : "")}>
              <div className="tag">{r.tag}</div>
              <h4>{r.title}</h4>
              <div className="date">{r.date}  ·  6 min read</div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─────────── Footer ─────────── */
function Footer({ region, setRegion }) {
  const r = window.REGION_DATA[region];
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-display">Tidewell&nbsp;<em>—</em></div>

        <div className="footer-grid">
          <div>
            <h5>Visit</h5>
            <p style={{ margin: 0, color: "oklch(85% 0.01 240)", maxWidth: "30ch" }}>
              {r.address}
            </p>
            <p style={{ marginTop: 14, color: "oklch(70% 0.01 240)", fontSize: 13 }}>
              {r.phoneLabel} · {r.phone}<br />
              hello@tidewell.{region === "CA" ? "ca" : "com"}
            </p>
            <div className="subscribe">
              <input type="email" placeholder="Email for spec sheets &amp; restocks" />
              <button>Subscribe →</button>
            </div>
          </div>

          <div>
            <h5>Products</h5>
            <ul>
              {window.PRODUCTS.slice(0, 6).map(p => <li key={p.slug}><a href={"#/products/" + p.slug}>{p.name}</a></li>)}
              <li><a href="#/products" style={{ color: "var(--bg)" }}>All categories →</a></li>
            </ul>
          </div>

          <div>
            <h5>Company</h5>
            <ul>
              <li><a href="#/about">About Tidewell</a></li>
              <li><a href="#/applications">Installations</a></li>
              <li><a href="#/">Dealer network</a></li>
              <li><a href="#/">Careers</a></li>
              <li><a href="#/">Press kit</a></li>
            </ul>
          </div>

          <div>
            <h5>Support</h5>
            <ul>
              <li><a href="#/">Warranty registration</a></li>
              <li><a href="#/">Spec sheets &amp; CAD</a></li>
              <li><a href="#/">Parts catalogue</a></li>
              <li><a href="#/contact">Find an installer</a></li>
              <li><a href="#/contact">Contact us</a></li>
            </ul>
          </div>
        </div>

        <div className="footer-bottom">
          <div>© 2026 Tidewell Pool Co.  ·  Designed in Toronto + Phoenix</div>
          <div className="legal">
            <a href="#/">Privacy</a>
            <a href="#/">Terms</a>
            <a href="#/" onClick={(e) => { e.preventDefault(); setRegion(region === "US" ? "CA" : "US"); }}>
              Region: {r.flag} {r.label}
            </a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Topbar, Header, Hero, Marquee, ProductGrid, ProductCard, Certs, Planner, ApplicationsStrip, Resources, Footer
});
