// pw-page.jsx — renders any page from window.PW_DATA.
const { useState: uS, useEffect: uE, useRef: uR } = React;
const D = window.PW_DATA, M = window.PW_MENU;

const CTA_HREF = "booking.html";   // the original contact page — booking calendar + phone/email

// WebP with a JPEG fallback and a 2x source, matching how the assets ship.
function Pic({ base, className, style, eager }) {
  if (!base) return null;
  return (
    <picture>
      <source type="image/webp" srcSet={`${base}.webp 1x, ${base}@2x.webp 2x`}/>
      <img src={`${base}.jpg`} srcSet={`${base}.jpg 1x, ${base}@2x.jpg 2x`}
           alt="" aria-hidden="true" loading={eager ? "eager" : "lazy"} decoding="async"
           className={className} style={style}/>
    </picture>
  );
}

// Look up a section's artwork by the opening words of its heading.
function sectionArt(art, heading) {
  const map = art.sections; if (!map || !heading) return null;
  const h = heading.toLowerCase();
  const key = Object.keys(map).find(k => h.startsWith(k));
  if (!key) return null;
  const e = map[key];
  return {
    layout: e.layout,
    img: e.img ? art.S + e.img : null,
    cards: (e.cards || []).map(c => art.S + c),
  };
}

/* ── section renderers ─────────────────────────────────────────── */

function SecHead({ h, paras, light }) {
  if (!h && !(paras || []).length) return null;
  return (
    <div className="sec-head reveal">
      {h && <h2 className="h2">{h}</h2>}
      {(paras || []).map((p, i) => <p className="lead" key={i}>{p}</p>)}
    </div>
  );
}

function CtaRow({ ctas }) {
  if (!ctas || !ctas.length) return null;
  return (
    <div className="process-cta reveal">
      <a href={CTA_HREF} className="btn btn-primary btn-arr">{ctas[0]} <Arr/></a>
    </div>
  );
}

function BulletSec({ s, light, img }) {
  if (img) {
    return (
      <>
        <SecHead h={s.h} paras={s.paras}/>
        <div className="pw-bullets-split reveal">
          <div className="pw-bullets-art">{img.pic ? <Pic base={img.pic}/> : <img src={img} alt="" loading="lazy"/>}</div>
          <div className="pw-bullets pw-bullets-1col">
            {s.items.map((it, i) => (
              <div className="pw-bullet" key={i}>
                <span className="pw-bullet-tick"><Tick/></span>
                <p>{it.t && <b>{it.t}. </b>}{it.d}</p>
              </div>
            ))}
          </div>
        </div>
        <CtaRow ctas={s.ctas}/>
      </>
    );
  }
  return (
    <>
      <SecHead h={s.h} paras={s.paras}/>
      <div className="pw-bullets reveal">
        {s.items.map((it, i) => (
          <div className="pw-bullet" key={i}>
            <span className="pw-bullet-tick"><Tick c={light ? "var(--teal-3)" : "var(--teal)"}/></span>
            <p>{it.t && <b>{it.t}. </b>}{it.d}</p>
          </div>
        ))}
      </div>
      <CtaRow ctas={s.ctas}/>
    </>
  );
}

function CardSec({ s, art = {}, pics = [] }) {
  const imgs = pics.length ? pics : (art.cardImages || []), icons = art.cardIcons || [];
  return (
    <>
      <SecHead h={s.h} paras={s.paras}/>
      <div className="pw-cards reveal">
        {s.cards.map((c, i) => (
          <div className="pw-card" key={i}>
            {imgs.length > 0 && (
              imgs[i]
                ? <div className="pw-card-art">{pics.length
                    ? <Pic base={imgs[i]}/>
                    : <img src={imgs[i]} alt="" loading="lazy"/>}</div>
                : <div className="pw-card-art pw-card-art-alt"><PwIcon name={icons[i]} size={40}/></div>
            )}
            {icons[i] && !(imgs.length && !imgs[i]) && <div className="svc-icon"><PwIcon name={icons[i]} size={22}/></div>}
            <div className="pw-card-num">{String(i + 1).padStart(2, "0")}</div>
            <h3 className="h3">{c.t}</h3>
            {c.d && <p>{c.d}</p>}
            {!!(c.items || []).length && (
              <ul className="pw-card-list">
                {c.items.map((x, j) => <li key={j}><span><Tick/></span>{x}</li>)}
              </ul>
            )}
          </div>
        ))}
      </div>
      <CtaRow ctas={s.ctas}/>
    </>
  );
}

function ProcessSec({ s, band }) {
  return (
    <>
      <SecHead h={s.h} paras={s.paras}/>
      {band && <div className="pw-proc-band reveal"><Pic base={band} eager/></div>}
      <div className="pw-proc reveal">
        {s.steps.map((st, i) => (
          <div className="process-step" key={i}>
            <div className="pw-step-head">
              <div className="process-num">{i + 1}</div>
              <span className="pw-step-icon"><PwIcon name={(window.PW_PROCESS_ICONS || [])[i]} size={22}/></span>
            </div>
            <h4>{st.t}</h4>
            <p>{st.d}</p>
          </div>
        ))}
      </div>
      <CtaRow ctas={s.ctas}/>
    </>
  );
}

function FaqSec({ s }) {
  const [open, setOpen] = uS(0);
  return (
    <>
      <SecHead h={s.h === "FAQ" ? "Questions, Answered Straight." : s.h} paras={s.paras}/>
      <div className="faq-list reveal">
        {s.faq.map((it, i) => (
          <div key={i} className={`faq-item ${open === i ? "open" : ""}`} onClick={() => setOpen(open === i ? -1 : i)}>
            <div className="faq-row">
              <h4 className="faq-q">{it.q}</h4>
              <button className="faq-toggle" aria-label="Toggle answer">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M7 2v10M2 7h10" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
              </button>
            </div>
            <div className="faq-a">{it.a}</div>
          </div>
        ))}
      </div>
      <CtaRow ctas={s.ctas}/>
    </>
  );
}

function TextSec({ s }) {
  return (
    <div className="cta-banner reveal">
      {s.h && <h2 className="h2">{s.h}</h2>}
      {s.paras.map((p, i) => <p className="lead" key={i}>{p}</p>)}
      {!!s.ctas.length && (
        <div className="cta-banner-actions">
          <a href={CTA_HREF} className="btn btn-primary btn-arr">{s.ctas[0]} <Arr/></a>
          <a href="mailto:info@purnaweb.ca" className="btn btn-ghost">info@purnaweb.ca</a>
        </div>
      )}
    </div>
  );
}

/* ── generic page shell ────────────────────────────────────────── */

/* ── Google Ads landing-page hero ──────────────────────────────────
   Built to assets/02-Services/google-ads/HERO-SPEC.md: full-bleed art,
   headline left, lead form right, scrim stops taken verbatim from the spec.
   The image is the LCP element, so it is preloaded and never lazy-loaded. */
// ── Google-flavoured marks ────────────────────────────────────────────────
// Google's palette rather than their logomark: a four-colour search ring reads
// unmistakably "Google" without reproducing a trademark we have no licence to.
// Swap in the official Google Ads SVG here if brand permission is in hand.
const G_BLUE = "#4285F4", G_RED = "#EA4335", G_YELLOW = "#FBBC04", G_GREEN = "#34A853";

const GoogleAdsMark = ({ size = 30 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
    <path d="M10 4.2A5.8 5.8 0 0115.8 10"   stroke={G_BLUE}   strokeWidth="2.3" strokeLinecap="round"/>
    <path d="M15.8 10A5.8 5.8 0 0110 15.8"  stroke={G_GREEN}  strokeWidth="2.3" strokeLinecap="round"/>
    <path d="M10 15.8A5.8 5.8 0 014.2 10"   stroke={G_YELLOW} strokeWidth="2.3" strokeLinecap="round"/>
    <path d="M4.2 10A5.8 5.8 0 0110 4.2"    stroke={G_RED}    strokeWidth="2.3" strokeLinecap="round"/>
    <path d="M14.6 14.1l6.9 3.2-3 1.1-1.1 3z" fill={G_BLUE}/>
  </svg>
);

// performance trend — the "audit an existing account" cue
const TrendMark = ({ size = 26 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true"
       stroke="#FFFFFF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M4 4v15.5h16"/>
    <path d="M7.5 15l3.5-4 3 2.4L19 8"/>
    <path d="M15.4 8H19v3.6"/>
  </svg>
);

const WhatsAppMark = ({ size = 19 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M17.47 14.38c-.3-.15-1.76-.87-2.03-.97-.27-.1-.47-.15-.67.15-.2.3-.77.97-.94 1.16-.17.2-.35.22-.64.08-.3-.15-1.26-.47-2.4-1.48-.88-.79-1.48-1.76-1.65-2.06-.17-.3-.02-.46.13-.6.14-.14.3-.35.44-.52.15-.18.2-.3.3-.5.1-.2.05-.37-.02-.52-.08-.15-.67-1.61-.92-2.21-.24-.58-.49-.5-.67-.51h-.57c-.2 0-.52.07-.8.37-.27.3-1.03 1.02-1.03 2.48 0 1.46 1.06 2.87 1.21 3.07.15.2 2.1 3.2 5.08 4.49.71.3 1.26.49 1.69.62.71.23 1.36.2 1.87.12.57-.09 1.76-.72 2-1.41.25-.7.25-1.29.18-1.42-.08-.12-.27-.2-.57-.34z"/>
    <path d="M12.05 21.79h-.01a9.87 9.87 0 01-5.03-1.38l-.36-.21-3.74.98 1-3.65-.24-.37a9.86 9.86 0 01-1.51-5.26C2.16 6.44 6.6 2 12.05 2c2.64 0 5.12 1.03 6.99 2.9a9.83 9.83 0 012.89 6.99c0 5.45-4.43 9.9-9.88 9.9zM20.46 3.49A11.82 11.82 0 0012.05 0C5.5 0 .16 5.34.16 11.89c0 2.1.55 4.14 1.59 5.95L.06 24l6.3-1.65a11.88 11.88 0 005.69 1.45c6.55 0 11.89-5.34 11.89-11.9 0-3.17-1.24-6.16-3.48-8.41z"/>
  </svg>
);

// "Already Running Google Ads?" card plus the call / WhatsApp row beneath it.
function LpHeroPlan({ plan }) {
  return (
    <>
      <div className="pw-lp-plan">
        <div className="pw-lp-plan-icon"><TrendMark size={26}/></div>
        <div>
          <h2 className="pw-lp-plan-h">{plan.h}</h2>
          <p className="pw-lp-plan-d">{plan.d}</p>
          <a href={plan.ctaHref} className="pw-lp-plan-cta">{plan.cta} <Arr/></a>
        </div>
      </div>
      <div className="pw-lp-quick">
        <span className="pw-lp-quick-label">{plan.quickLabel}</span>
        <a href={`tel:${plan.tel}`} className="pw-lp-quick-link is-call">
          <PwIcon name="ui/phone" size={18}/>{plan.telLabel}
        </a>
        <span className="pw-lp-quick-sep" aria-hidden="true"/>
        <a href={plan.whatsapp} target="_blank" rel="noopener noreferrer" className="pw-lp-quick-link is-wa">
          <WhatsAppMark size={18}/>{plan.whatsappLabel}
        </a>
      </div>
    </>
  );
}

// LeadConnector (GoHighLevel) inline form. The embed script resizes the iframe
// over postMessage, so it has to load *after* React has put the iframe in the
// DOM — a plain <script> in the page shell would run too early.
function LpHeroEmbed({ embed }) {
  const wrap = uR(null);
  uE(() => {
    if (!embed.script) return;
    const sel = `script[src="${embed.script}"]`;
    if (document.querySelector(sel)) {
      // already loaded on this page — nudge it to rescan for our iframe
      window.dispatchEvent(new Event("resize"));
      return;
    }
    const s = document.createElement("script");
    s.src = embed.script;
    s.async = true;
    document.body.appendChild(s);
  }, [embed.script]);

  return (
    <div className="pw-lp-form pw-lp-form-embed" ref={wrap}
         style={{ "--form-floor": `${embed.floor || 415}px`,
                  "--form-floor-1col": `${embed.floor1 || embed.floor || 700}px` }}>
      <iframe
        src={embed.src}
        title={embed.name}
        id={`inline-${embed.formId}`}
        style={{ width: "100%", height: embed.height || 594, border: "none", borderRadius: 15, display: "block" }}
        scrolling="no"
        data-layout="{'id':'INLINE'}"
        data-trigger-type="alwaysShow"
        data-trigger-value=""
        data-activation-type="alwaysActivated"
        data-activation-value=""
        data-deactivation-type="neverDeactivate"
        data-deactivation-value=""
        data-form-name={embed.name}
        data-height={embed.height || 594}
        data-layout-iframe-id={`inline-${embed.formId}`}
        data-form-id={embed.formId}
      />
    </div>
  );
}

function LpHeroForm() {
  const [sent, setSent] = uS(false);
  const submit = (e) => {
    e.preventDefault();
    if (!e.target.checkValidity()) { e.target.reportValidity(); return; }
    setSent(true);
    // TODO: wire to LeadConnector/CRM.
  };
  if (sent) {
    return (
      <div className="pw-lp-form">
        <div className="pw-sent"><Tick c="#146C34"/><div>Thanks — we've got it. We'll send your free audit shortly.</div></div>
      </div>
    );
  }
  return (
    <div className="pw-lp-form">
      <h2 className="pw-lp-form-h">Get Your Free Google Ads Audit</h2>
      <form onSubmit={submit} noValidate>
        <div className="field"><label>Name</label><input type="text" name="name" required placeholder="Your name"/></div>
        <div className="field"><label>Email</label><input type="email" name="email" required placeholder="you@business.com"/></div>
        <div className="field"><label>Phone</label><input type="tel" name="phone" required placeholder="(705) 000-0000"/></div>
        <div className="field">
          <label>Monthly ad spend</label>
          <select name="spend" defaultValue="" required>
            <option value="" disabled>Select a range</option>
            <option>Not running ads yet</option>
            <option>Under $1,000 / month</option>
            <option>$1,000 – $3,000 / month</option>
            <option>$3,000 – $10,000 / month</option>
            <option>$10,000+ / month</option>
          </select>
        </div>
        <button type="submit" className="btn btn-arr pw-lp-btn">Claim My Free Audit <Arr/></button>
        <p className="pw-lp-micro">No spam. No sales pressure.</p>
      </form>
    </div>
  );
}

// Foot-of-page audit form — the target of the hero card's CTA.
function AuditFormSec({ embed }) {
  return (
    <section className="sec sec-navy pw-audit-sec" id="audit-form">
      <div className="container">
        <div className="sec-head reveal">
          <span className="pw-audit-mark"><GoogleAdsMark size={34}/></span>
          <h2 className="h2">{embed.h} <span className="accent">Get a Free Audit.</span></h2>
          <p className="lead">{embed.sub}</p>
        </div>
        <div className="pw-audit-form reveal">
          <LpHeroEmbed embed={embed}/>
        </div>
      </div>
    </section>
  );
}

function LpHero({ hero, art }) {
  const a = art.heroLp;
  const TRUST = ["No long-term contracts", "Direct access to your account team", "Free audit, no obligation"];
  return (
    <section className="pw-lp-hero">
      <picture>
        <source media="(max-width: 880px)" type="image/webp"
                srcSet={`${a.mobile}.webp 1x, ${a.mobile}@2x.webp 2x`}/>
        <source media="(max-width: 880px)" type="image/jpeg"
                srcSet={`${a.mobile}.jpg 1x, ${a.mobile}@2x.jpg 2x`}/>
        <source type="image/webp" srcSet={`${a.base}.webp 1x, ${a.base}@2x.webp 2x`}/>
        <img className="pw-lp-hero-bg" src={`${a.base}.jpg`} alt="" role="presentation"
             fetchpriority="high" decoding="async"/>
      </picture>
      <div className="pw-lp-scrim" aria-hidden="true"/>
      <div className="container">
        {/* Two columns, with the form spanning both rows so its top edge starts
            level with the H1 rather than below the headline block. */}
        <div className="pw-lp-inner">
          <div className="pw-lp-head">
            <h1 className="h1 pw-lp-h1">{hero.h1}</h1>
            {hero.paras.map((p, i) => <p className="pw-lp-sub" key={i}>{p}</p>)}
          </div>
          <div className="pw-lp-aside">
            {art.heroPlan ? <LpHeroPlan plan={art.heroPlan}/> : (
              <ul className="pw-lp-trust">
                {TRUST.map(t => (
                  <li key={t}><span><PwIcon name="ui/check-circle" size={18}/></span>{t}</li>
                ))}
              </ul>
            )}
          </div>
          <div className="pw-lp-formcol">
            {art.heroFormEmbed && art.heroFormEmbed.title &&
              <h2 className="pw-lp-form-title">{art.heroFormEmbed.title}</h2>}
            {art.heroFormEmbed ? <LpHeroEmbed embed={art.heroFormEmbed}/> : <LpHeroForm/>}
          </div>
        </div>
      </div>
    </section>
  );
}

function PwHero({ hero, slug, children }) {
  const art = (window.PW_ASSETS || {})[slug] || {};
  return (
    <section className={art.hero ? "hero pw-hero pw-hero-art" : "hero pw-hero"}>
      {art.hero ? (
        <img className="pw-hero-bg" src={art.hero} alt="" aria-hidden="true"/>
      ) : (
        <video className="hero-bg-video" autoPlay loop muted playsInline preload="auto" aria-hidden="true">
          <source src="images/header-bg/ai-bg-video.mp4" type="video/mp4"/>
        </video>
      )}
      <div className="hero-bg-overlay" aria-hidden="true"/>
      <div className="container">
        <div className={children ? "hero-grid" : "hero-grid pw-hero-solo"}>
          <div>
            <h1 className="h1" style={{ margin: "14px 0 24px" }}>{hero.h1}</h1>
            {hero.paras.map((p, i) => <p className="lead" key={i} style={{ marginBottom: 16 }}>{p}</p>)}
            <div className="hero-cta" style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 12 }}>
              <a href={CTA_HREF} className="btn btn-primary btn-arr">{hero.cta || "Get Free Strategy Session"} <Arr/></a>
              <a href="tel:+17052420221" className="btn btn-ghost">(705) 242-0221</a>
            </div>
          </div>
          {children && <div>{children}</div>}
        </div>
      </div>
    </section>
  );
}

// A section is rendered on grey when it sits between two white ones, so the page
// alternates without two identical backgrounds ever touching.
function Sections({ sections, art = {} }) {
  let grey = false, firstBullets = true;
  return sections.map((s, i) => {
    if (s.kind === "text" && s.ctas.length) {
      return <section className="sec" key={i}><div className="container"><TextSec s={s}/></div></section>;
    }
    grey = !grey;
    const sa = sectionArt(art, s.h);
    const bandBg = sa && sa.layout === "bandbg" ? sa.img : null;
    const cls = (grey ? "sec sec-grey" : "sec") + (bandBg ? " pw-band-bg" : "");
    const inner =
      s.kind === "cards"   ? <CardSec s={s} art={art} pics={sa ? sa.cards : []}/> :
      s.kind === "process" ? <ProcessSec s={s} band={sa && sa.layout === "band" ? sa.img : null}/> :
      s.kind === "faq"     ? <FaqSec s={s}/> :
      s.kind === "bullets" ? (() => {
                                const split = sa && sa.layout === "split" ? { pic: sa.img } : null;
                                const use = split || (firstBullets && (art.why || art.split));
                                firstBullets = false;
                                return <BulletSec s={s} img={use || null}/>; })() :
                             <><SecHead h={s.h} paras={s.paras}/><CtaRow ctas={s.ctas}/></>;
    return (
      <section className={cls} key={i}>
        {bandBg && <Pic base={bandBg} className="pw-band-bg-img" eager/>}
        <div className="container">{inner}</div>
      </section>
    );
  });
}

function FinalCta({ img }) {
  return (
    <section className="sec">
      <div className="container">
        <div className={img ? "cta-banner pw-cta-art reveal" : "cta-banner reveal"}>
          {img && <img className="pw-cta-bg" src={img} alt="" aria-hidden="true" loading="lazy"/>}
          <h2 className="h2">Ready to Grow Your <span className="accent">Business?</span></h2>
          <p className="lead">Let's talk about where you are, where you want to go, and exactly how we can help you get there — no pressure, no obligation.</p>
          <div className="cta-banner-actions">
            <a href={CTA_HREF} className="btn btn-primary btn-arr">Get Free Strategy Session <Arr/></a>
            <a href="mailto:info@purnaweb.ca" className="btn btn-ghost">info@purnaweb.ca</a>
          </div>
        </div>
      </div>
    </section>
  );
}

function InnerPage({ slug }) {
  const p = D[slug];
  const art = (window.PW_ASSETS || {})[slug] || {};
  const others = p.type === "industry" ? M.industries : M.services;
  const here = `pw-${p.type}-${p.slug}.html`;
  return (
    <>
      <PwNav active={p.type === "industry" ? "industries" : "services"}/>
      {art.heroLp ? <LpHero hero={p.hero} art={art}/> : <PwHero hero={p.hero} slug={slug}/>}
      <Sections sections={p.sections} art={art}/>
      {art.auditFormEmbed && <AuditFormSec embed={art.auditFormEmbed}/>}
      <section className="sec sec-grey">
        <div className="container">
          <div className="sec-head reveal">
            <h2 className="h2">{p.type === "industry" ? "Other industries we serve" : "Explore more services"}</h2>
          </div>
          <div className="pw-chips reveal">
            {others.filter(o => o.h !== here).map(o => (
              <a className="pw-chip" href={o.h} key={o.h}>{o.l}<Arr/></a>
            ))}
          </div>
        </div>
      </section>
      <FinalCta img={art.cta}/>
      <PwFooter/>
    </>
  );
}

Object.assign(window, { InnerPage, PwHero, Sections, FinalCta, SecHead, CtaRow, TextSec, CTA_HREF });
