/* global React */
const { useState, useEffect, useRef } = React;
const _DS = window.MickelsenAccentsDesignSystem_f85163;
const { Button, Badge, Card, StatBlock, Input, Textarea, Select, Checkbox, Alert, TradeTag, Divider } = _DS;
const D = window.MA_DATA;

/* ---------------------------------------------------------------- Icons
   lucide draws an icon by *replacing* this <i> with an <svg> of its own, which
   `refreshIcons` below tells it to do after every render. That swap happens
   behind React's back: the node React still holds a reference to is no longer
   in the document, so the moment React has to remove it — an icon that only
   renders while a gallery filter is selected, say — `removeChild` throws and
   takes the whole page down with it.

   The wrapper is what makes that impossible. React only ever removes or moves
   the <span>, a node it still owns, and whatever lucide has done inside goes
   with it. `display: contents` keeps the wrapper out of the box tree, so the
   icon sits in its parent's flex or grid exactly as it did before.

   The `key` is the other half. When `name` changes React must build a fresh
   wrapper rather than reuse this one: re-rendering the <i> in place would write
   the new name onto the detached node and the icon would never change. */
function Icon({ name, size = 22, color = "currentColor", stroke = 2, style }) {
  return (
    <span key={name} style={{ display: "contents" }}>
      <i data-lucide={name} style={{ width: size, height: size, color, strokeWidth: stroke, display: "inline-flex", flex: "none", ...style }} />
    </span>
  );
}
function refreshIcons() { if (window.lucide) window.lucide.createIcons(); }

/* ------------------------------------------------------------ CTA tracking
   Counts a click on one of the site's calls to action (analytics.js →
   POST /api/collect). Guarded rather than called directly: collection can be
   switched off with `window.MA_CONFIG = { analytics: false }`, in which case
   analytics.js returns before defining anything, and a call to action that
   throws instead of navigating would be a far worse bug than a missing count. */
function trackCta(action) {
  try {
    if (window.MA_ANALYTICS && window.MA_ANALYTICS.trackCta) window.MA_ANALYTICS.trackCta(action);
  } catch (_) { /* never let a counter break a link */ }
}

/* --------------------------------------------------------------- Router
   The routing itself is router.js; this is its React face. A route is a path:
   "/", "/services", "/learn/<slug>". */
function useRoute() {
  const [route, setRoute] = useState(window.MA_ROUTER.current());
  useEffect(() => {
    const on = () => setRoute(window.MA_ROUTER.current());
    window.addEventListener("ma:route", on);
    return () => window.removeEventListener("ma:route", on);
  }, []);
  return route;
}
function go(route) { window.MA_ROUTER.navigate(route); }

/* ------------------------------------------------------------- Gallery data
   The owner's uploaded project photos (gallery.js → GET /api/gallery). One
   fetch is shared by every component that calls this, so a page showing both
   the grid and a carousel still makes a single request.

   `loading` is distinguished from "loaded and empty" on purpose: a grid that
   renders its empty state for a moment and then fills in reads as a glitch. */
function useGallery() {
  const [state, setState] = useState({ loading: true, items: [], tags: [], labels: {}, failed: false });
  useEffect(() => {
    let alive = true;
    window.MA_GALLERY.load().then((data) => {
      if (!alive) return;
      // Items carry tag slugs; only the tag list knows how the owner spelled
      // them. Resolve once here so no caller has to hunt through both.
      const labels = {};
      data.tags.forEach((t) => { labels[t.slug] = t.label; });
      setState({ loading: false, items: data.items, tags: data.tags, labels, failed: Boolean(data.failed) });
    });
    return () => { alive = false; };
  }, []);
  return state;
}

/* The articles as the visitor should see them: nav-data.js with the owner's
   edits from /admin applied, and `visible` only on the ones they turned on
   (articles.js). Until the settings arrive every article is hidden — `loading`
   lets a page wait instead of treating "not loaded yet" as "nothing to show". */
function useArticles() {
  const A = window.MA_ARTICLES;
  const build = (data) => {
    const all = A.merge(D.ARTICLES, data ? data.overrides : {});
    return { loading: !data, all, visible: all.filter((a) => a.visible) };
  };
  const [state, setState] = useState(() => build(A.peek()));
  useEffect(() => {
    let alive = true;
    if (state.loading) A.load().then((data) => { if (alive) setState(build(data)); });
    return () => { alive = false; };
  }, []);
  return state;
}

/* The Articles menu, cut down to the articles that are actually shown (the
   cost guide counts as one — COST_GUIDE_SHOWN in nav-data.js). With none
   shown there is no menu at all: Articles is a plain link to the index, which
   says more are on the way. */
function learnNav(visible) {
  const shown = new Set(visible.map((a) => a.slug));
  if (shown.size === 0 && !D.COST_GUIDE_SHOWN) return { groups: [] };
  const groups = D.LEARN_GROUPS
    .map((g) => ({
      ...g,
      items: g.items.filter(([, route]) => {
        if (route === "/cost") return D.COST_GUIDE_SHOWN;
        const m = /^\/learn\/(.+)$/.exec(route);
        return !m || shown.has(m[1]);
      }),
    }))
    .filter((g) => g.items.some(([, route]) => route !== "/learn" && route !== "/contact"));
  return { groups };
}

/* A link to another page of the site, which never shows browser-blue. It is a
   plain anchor: router.js turns the click into a route change. */
function NavLink({ to, children, style, onClick }) {
  return (
    <a
      href={to}
      onClick={(e) => { if (onClick) onClick(e); }}
      style={{ borderBottom: "none", color: "inherit", textDecoration: "none", cursor: "pointer", ...style }}
    >
      {children}
    </a>
  );
}

/* ------------------------------------------------------------ Call label
   The number by itself leaves the visitor to work out what to do with it. The
   line above says it outright — and on a phone, tapping it dials.

   Two stacked lines rather than "Call Now (208) 468-0641" on one: the digits
   are what a person reads back to themselves, so they keep the full size, and
   the instruction sits above them in the same small tracked uppercase the rest
   of the site uses for eyebrows. It also keeps the control narrow enough to sit
   in a phone-width header next to the menu toggle.

   `Button` sets `lineHeight: 1` on itself, which would collapse the two lines
   into each other; the stack sets its own. */
function CallLabel({ align = "center", numberSize }) {
  return (
    <span style={{ display: "inline-flex", flexDirection: "column", alignItems: align, lineHeight: 1.15, gap: 2, textAlign: align === "center" ? "center" : "left" }}>
      <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: "0.16em", textTransform: "uppercase", opacity: 0.7 }}>Call Now</span>
      <span style={{ fontSize: numberSize, fontWeight: 600 }}>{D.PHONE.display}</span>
    </span>
  );
}

/* ---------------------------------------------------------------- Header */
const TOP_NAV = [
  { label: "Services", to: "/services", mega: true },
  { label: "Gallery", to: "/gallery" },
  { label: "Articles", to: "/learn", groups: "LEARN_GROUPS" },
  { label: "Commercial", to: "/commercial" },
  { label: "About", to: "/about" },
];

function SiteHeader({ showPreviewBanner = true }) {
  const learn = learnNav(useArticles().visible);
  const nav = TOP_NAV.map((n) => (n.groups === "LEARN_GROUPS" && !learn.groups.length ? { ...n, groups: null } : n));
  const [openMenu, setOpenMenu] = useState(null); // label of open dropdown
  const [mobileOpen, setMobileOpen] = useState(false);
  const closeAll = () => { setOpenMenu(null); setMobileOpen(false); };
  useEffect(refreshIcons);

  /* Tapping a link in the mobile menu closes it, but the phone's own back
     button changes the route without going through one — and a menu left open
     over the page it just navigated away from reads as a frozen site. */
  useEffect(() => {
    const close = () => { setOpenMenu(null); setMobileOpen(false); };
    window.addEventListener("ma:route", close);
    return () => window.removeEventListener("ma:route", close);
  }, []);

  return (
    <header
      onMouseLeave={() => setOpenMenu(null)}
      style={{ position: "sticky", top: 0, zIndex: 100, background: "rgba(251,248,242,0.94)", backdropFilter: "blur(8px)", borderBottom: "1px solid var(--border-hairline)" }}
    >
      <div style={{ maxWidth: "var(--container-xl)", margin: "0 auto", padding: "12px var(--gutter)", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
        {/* The logo already spells out "Mickelsen Accents Inc." and the trade
            line, so it carries the brand on its own — no text wordmark beside
            it. The JPEG is square but the artwork is a wide band across its
            middle, so it is cropped to that band (`object-fit: cover` on a
            100:52 box) rather than shown with its white margins, and
            `multiply` drops what white is left into the cream bar. */}
        <NavLink to="/" onClick={closeAll} aria-label="Mickelsen Accents, Inc. — home" style={{ display: "inline-flex", alignItems: "center", flex: "none" }}>
          <img className="ma-header-logo" src={`${window.MA_ROUTER.assetRoot}assets/mickelsen-logo.jpeg`} alt="Mickelsen Accents, Inc." style={{ height: 72, width: "auto", aspectRatio: "100 / 52", objectFit: "cover", objectPosition: "center", display: "block", mixBlendMode: "multiply" }} />
        </NavLink>

        <nav className="ma-desktop-nav" style={{ display: "flex", alignItems: "center", gap: 4 }}>
          {nav.map((n) => (
            <div key={n.label} onMouseEnter={() => setOpenMenu(n.mega || n.groups ? n.label : null)} style={{ position: "static" }}>
              <NavLink
                to={n.to}
                onClick={() => setOpenMenu(null)}
                style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "8px 12px", borderRadius: 4, fontSize: 14.5, fontWeight: 500, color: openMenu === n.label ? "var(--brick-600)" : "var(--stone-700)" }}
              >
                {n.label}
                {(n.mega || n.groups) && <Icon name="chevron-down" size={15} stroke={2.2} />}
              </NavLink>
            </div>
          ))}
          <Button
            variant="outline" size="sm" href={D.PHONE.href} onClick={() => trackCta("call")}
            aria-label={`Call now — ${D.PHONE.display}`}
            style={{ marginLeft: 8, color: "var(--stone-800)", paddingTop: 7, paddingBottom: 7 }}
            leadingIcon={<Icon name="phone" size={16} />}
          >
            <CallLabel align="flex-start" numberSize={14.5} />
          </Button>
          {/* Stretched to the row rather than given a matching padding: the call
              button is two lines tall now, and hard-coding a height here would
              drift the moment either label changes. */}
          <Button variant="primary" size="sm" href="/contact" onClick={() => trackCta("estimate")} style={{ marginLeft: 8, alignSelf: "stretch" }}>Request an Estimate</Button>
        </nav>

        {/* Below 1080px the nav above collapses into the hamburger — but the
            phone number is the one thing that shouldn't have to be opened to be
            found, and it is on a phone that tapping it actually dials. So it
            stays in the bar, next to the toggle, at every width. */}
        <a
          className="ma-mobile-call" href={D.PHONE.href} onClick={() => trackCta("call")}
          aria-label={`Call now — ${D.PHONE.display}`}
          style={{ display: "none", marginLeft: "auto", alignItems: "center", gap: 8, padding: "7px 13px", borderRadius: 4, background: "var(--brick-500)", color: "var(--stone-50)", fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 14.5, textDecoration: "none", whiteSpace: "nowrap" }}
        >
          <Icon name="phone" size={17} />
          <CallLabel align="flex-start" numberSize={14.5} />
        </a>

        <button className="ma-mobile-toggle" onClick={() => setMobileOpen(!mobileOpen)} aria-label="Menu" style={{ display: "none", border: "1px solid var(--border-default)", background: "transparent", borderRadius: 4, padding: 8, cursor: "pointer" }}>
          <Icon name={mobileOpen ? "x" : "menu"} />
        </button>
      </div>

      {/* Mega / dropdown panel */}
      {openMenu === "Services" && <ServicesMenu onNavigate={() => setOpenMenu(null)} />}
      {openMenu === "Articles" && learn.groups.length > 0 && <DropMenu groups={learn.groups} onNavigate={() => setOpenMenu(null)} />}

      {/* Mobile menu */}
      {mobileOpen && <MobileMenu items={nav} onNavigate={closeAll} />}

      {/* Last child of the sticky header, so it rides under the menu on every
          page and at every scroll position — and an open dropdown or mobile
          menu pushes it down rather than covering it. */}
      {showPreviewBanner && <AIPreviewBanner onNavigate={closeAll} />}
    </header>
  );
}

/* ---------------------------------------------------- AI preview banner
   The slim band under the menu that points every visitor at the AI preview
   page (/ai-preview). It lives inside the sticky header, so it has to stay
   one short line, so the sentence steps down with the screen — the full line on
   desktop, "See the work before we perform it." on tablets, and just "See it
   before we build." beside an "AI Preview" button on phones (the `.ma-banner-*`
   classes in index.html) — rather than a band that wraps and eats the screen. The router turns it off on the preview
   page itself, where a button to the page you are already on is noise. */
function AIPreviewBanner({ onNavigate }) {
  return (
    <div className="tex-stone" style={{ background: "var(--stone-900)", borderTop: "1px solid var(--stone-800)" }}>
      <div className="ma-banner" style={{ position: "relative", maxWidth: "var(--container-xl)", margin: "0 auto", padding: "8px var(--gutter)", display: "flex", alignItems: "center", justifyContent: "center", gap: 16 }}>
        <p style={{ margin: 0, display: "flex", alignItems: "center", gap: 9, minWidth: 0, color: "var(--stone-100)", fontSize: 14.5, lineHeight: 1.35, textWrap: "balance" }}>
          <Icon name="sparkles" size={17} color="var(--sand-300)" />
          <span className="ma-banner-text-long">See the work before we perform it — with a free AI preview of your home.</span>
          <span className="ma-banner-text-short" style={{ display: "none" }}>See the work before we perform it.</span>
          <span className="ma-banner-text-phone" style={{ display: "none" }}>See it before we build.</span>
        </p>
        {/* `ma-banner-cta` stretches this link over the whole band (index.html),
            so on a phone a thumb anywhere on the strip opens the preview —
            the button alone is too small a target to be the only one. */}
        <Button
          className="ma-banner-cta" variant="primary" size="sm" href="/ai-preview"
          onClick={() => { trackCta("preview"); if (onNavigate) onNavigate(); }}
          style={{ flex: "none", paddingTop: 6, paddingBottom: 6 }}
          trailingIcon={<Icon name="arrow-right" size={15} />}
        >
          <span className="ma-banner-btn-long">Get My Free AI Preview</span>
          <span className="ma-banner-btn-short" style={{ display: "none" }}>AI Preview</span>
        </Button>
      </div>
    </div>
  );
}

function ServicesMenu({ onNavigate }) {
  useEffect(refreshIcons);
  return (
    <div style={{ borderTop: "1px solid var(--border-hairline)", background: "var(--surface-raised)", boxShadow: "var(--shadow-lg)" }}>
      <div style={{ maxWidth: "var(--container-xl)", margin: "0 auto", padding: "22px var(--gutter) 26px", display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }}>
        {D.SERVICE_COLUMNS.map((col) => (
          <NavLink key={col.title} to={`/category/${col.slug}`} onClick={onNavigate}
            style={{ display: "block", padding: "16px 16px", border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", background: "var(--surface-raised)", transition: "border-color 150ms, box-shadow 150ms" }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--brick-300)"; e.currentTarget.style.boxShadow = "var(--shadow-sm)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--border-hairline)"; e.currentTarget.style.boxShadow = "none"; }}>
            <Icon name={col.icon} size={22} color="var(--brick-500)" />
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 16, color: "var(--text-strong)", margin: "10px 0 0" }}>{col.title}</div>
          </NavLink>
        ))}
      </div>
    </div>
  );
}

function DropMenu({ groups, onNavigate }) {
  return (
    <div style={{ borderTop: "1px solid var(--border-hairline)", background: "var(--surface-raised)", boxShadow: "var(--shadow-lg)" }}>
      <div style={{ maxWidth: "var(--container-md)", margin: "0 auto", padding: "24px var(--gutter) 28px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40 }}>
        {groups.map((g) => (
          <div key={g.title}>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--brick-500)", marginBottom: 12 }}>{g.title}</div>
            <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 9 }}>
              {g.items.map(([label, route]) => (
                <li key={label}>
                  <NavLink to={route} onClick={onNavigate}
                    style={{ fontSize: 14, color: "var(--stone-700)", display: "inline-flex", alignItems: "center", gap: 7 }}
                    onMouseEnter={(e) => (e.currentTarget.style.color = "var(--brick-600)")}
                  >{label.includes("All Articles") || label.includes("Consultation") ? <Icon name="arrow-right" size={14} color="var(--sand-500)" /> : null}{label}</NavLink>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </div>
  );
}

function MobileMenu({ items, onNavigate }) {
  return (
    <div style={{ borderTop: "1px solid var(--border-hairline)", background: "var(--surface-raised)", maxHeight: "70vh", overflowY: "auto", padding: "10px var(--gutter) 20px" }}>
      {items.map((n) => (
        <NavLink key={n.label} to={n.to} onClick={onNavigate} style={{ display: "block", padding: "12px 0", fontWeight: 600, fontSize: 16, borderBottom: "1px solid var(--border-hairline)", color: "var(--stone-800)" }}>{n.label}</NavLink>
      ))}
      <Button variant="primary" size="md" fullWidth href="/contact" onClick={() => { trackCta("estimate"); onNavigate(); }} style={{ marginTop: 16 }}>Request an Estimate</Button>
      <Button variant="outline" size="md" fullWidth href={D.PHONE.href} onClick={() => { trackCta("call"); onNavigate(); }} aria-label={`Call now — ${D.PHONE.display}`} style={{ marginTop: 10, color: "var(--stone-800)" }} leadingIcon={<Icon name="phone" size={18} />}><CallLabel numberSize={16} /></Button>
    </div>
  );
}

/* ==========================================================================
   CALLING CARD — the repeatable company block placed near the bottom of
   EVERY page, just below the closing call to action and above the footer.
   ========================================================================== */
function CallingCard() {
  useEffect(refreshIcons);
  const trust = [
    ["shield-check", "Licensed & Insured", D.REGISTRATION.display],
    ["award", "20+ Years in Trade", "Four generations"],
    ["hard-hat", "Done Right", "The first time"],
    ["badge-check", "Written Warranty", "In writing, every job"],
  ];
  return (
    <section className="tex-brick" style={{ position: "relative", borderTop: "1px solid var(--border-hairline)", borderBottom: "1px solid var(--border-hairline)", overflow: "hidden" }}>
      <div className="ma-sect" style={{ position: "relative", zIndex: 2, maxWidth: "var(--container-lg)", margin: "0 auto", padding: "56px var(--gutter)" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 48, alignItems: "center" }} className="ma-callcard-grid">
          <div>
            <TradeTag items={D.TRADES} />
            <h2 style={{ fontSize: "clamp(26px,3.4vw,38px)", margin: "14px 0 14px", maxWidth: 460 }}>The mason your neighbors already called</h2>
            <p style={{ fontSize: 17, color: "var(--text-body)", lineHeight: 1.6, maxWidth: 480, margin: 0 }}>
              Mickelsen Accents is a family-owned masonry contractor. We install masonry, stucco, and siding on new and existing homes. Whether it's one feature wall or a whole elevation, it's held to one standard: finished right the first time.
            </p>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            {trust.map(([ic, t, s]) => (
              <div key={t} style={{ background: "var(--surface-raised)", border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-lg)", padding: "18px 16px", boxShadow: "var(--shadow-sm)" }}>
                <Icon name={ic} size={24} color="var(--brick-500)" />
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 16, color: "var(--text-strong)", marginTop: 10 }}>{t}</div>
                <div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 2 }}>{s}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ==========================================================================
   CONTACT CTA — the quote call-to-action band, bottom of every page.
   ========================================================================== */
function ContactCTA() {
  useEffect(refreshIcons);
  return (
    <section id="contact" className="tex-stone" style={{ background: "var(--stone-900)" }}>
      <div className="ma-sect" style={{ maxWidth: "var(--container-lg)", margin: "0 auto", padding: "64px var(--gutter)", display: "flex", flexWrap: "wrap", gap: 32, alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ maxWidth: 560 }}>
          <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--sand-300)" }}>Free On-Site Estimate</span>
          <h2 style={{ color: "var(--stone-50)", fontSize: "clamp(30px,4vw,46px)", margin: "12px 0 12px", lineHeight: 1.05 }}>Send us your plans. We'll give you a real number.</h2>
          <p style={{ color: "var(--stone-300)", fontSize: 17, lineHeight: 1.55, margin: 0 }}>We walk the site with you, talk through the stone, and quote a fixed scope — no obligation, no pressure.</p>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 12, minWidth: "min(240px, 100%)" }}>
          <Button variant="primary" size="lg" href="/contact" onClick={() => trackCta("estimate")} leadingIcon={<Icon name="ruler" size={20} />}>Request an Estimate</Button>
          <Button variant="outline" size="lg" href={D.PHONE.href} onClick={() => trackCta("call")} aria-label={`Call now — ${D.PHONE.display}`} style={{ color: "var(--stone-50)", borderColor: "rgba(255,255,255,0.3)" }} leadingIcon={<Icon name="phone" size={19} />}><CallLabel numberSize={17} /></Button>
          <div style={{ fontSize: 13, color: "var(--stone-400)", textAlign: "center", marginTop: 2 }}>{D.HOURS.display}</div>
          <div style={{ fontSize: 12.5, color: "var(--stone-500)", textAlign: "center" }}>{D.HOURS.note}</div>
        </div>
      </div>
    </section>
  );
}

/* ==========================================================================
   AI PREVIEW CTA — the closing call-to-action on the Exterior Remodel page
   (app.jsx), and the whole of the standalone /ai-preview page that the
   banner under the menu links to. Every other page ends on ContactCTA.
   `standalone` makes the headline the page's <h1>, since on /ai-preview
   this section is the page.
   Offers a free, AI-generated preview of the visitor's masonry project.
   Collects name, email, phone, a photo of their home/space, and a project
   description, then POSTs multipart/form-data to the API. The server emails
   the lead — with the photo attached — to the address in LEAD_NOTIFY_EMAIL,
   and records it in the Firestore `leads` collection. The photo is kept in a
   private Cloud Storage prefix for the Customer Requests tab in /admin, which renders
   it with Gemini and emails the result back to the visitor.
   ========================================================================== */
const AI_PREVIEW_ENDPOINT =
  (window.MA_CONFIG && window.MA_CONFIG.apiBase) || "/api/ai-preview";
const AI_PREVIEW_MAX_BYTES = 10 * 1024 * 1024; // 10 MB — keep in sync with server

function AIPreviewCTA({ standalone = false }) {
  useEffect(refreshIcons);
  const Heading = standalone ? "h1" : "h2";
  const [status, setStatus] = useState("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = useState("");
  const [fileName, setFileName] = useState("");
  const [fileError, setFileError] = useState("");
  const fileRef = useRef(null);

  function onFileChange(e) {
    const f = e.target.files && e.target.files[0];
    if (!f) { setFileName(""); setFileError(""); return; }
    if (!f.type.startsWith("image/")) {
      setFileError("Please choose an image file (JPG, PNG, HEIC…)."); setFileName(""); e.target.value = ""; return;
    }
    if (f.size > AI_PREVIEW_MAX_BYTES) {
      setFileError("That image is over 10 MB — please pick a smaller one."); setFileName(""); e.target.value = ""; return;
    }
    setFileError(""); setFileName(f.name);
  }

  async function onSubmit(e) {
    e.preventDefault();
    if (status === "sending") return;
    const form = e.currentTarget;
    const file = fileRef.current && fileRef.current.files[0];
    if (!file) { setFileError("A photo of your space is required to build your preview."); return; }
    setStatus("sending"); setErrorMsg("");
    try {
      const payload = new FormData(form);
      // Carry the visitor's first-touch attribution (analytics.js) so the lead is
      // stored next to the traffic that produced it.
      if (window.MA_ANALYTICS) {
        try { payload.append("attribution", JSON.stringify(window.MA_ANALYTICS.attribution())); } catch (_) { /* optional */ }
      }
      const res = await fetch(AI_PREVIEW_ENDPOINT, { method: "POST", body: payload });
      if (!res.ok) {
        let msg = "Something went wrong sending your request. Please try again — or call us.";
        try { const j = await res.json(); if (j && j.error) msg = j.error; } catch (_) { /* non-JSON error */ }
        throw new Error(msg);
      }
      setStatus("sent");
      // The conversion itself is counted server-side, by the endpoint that stores
      // the lead (functions/leads.js increments the day's `leads` counter). A
      // beacon from here would be both redundant and weaker: it can be blocked,
      // dropped on navigation, or replayed to inflate the number.
    } catch (err) {
      setStatus("error");
      setErrorMsg(err && err.message ? err.message : "Network error. Please try again.");
    }
  }

  const dropzone = {
    display: "flex", alignItems: "center", gap: 12, width: "100%", cursor: "pointer",
    border: `1px dashed ${fileError ? "var(--clay-500)" : "var(--border-strong)"}`,
    borderRadius: "var(--radius-md)", padding: "14px 14px", background: "var(--surface-page)",
    color: fileName ? "var(--text-strong)" : "var(--text-muted)", fontSize: 14.5,
    transition: "border-color 150ms",
  };

  return (
    <section id="ai-preview" className="tex-stone" style={{ background: "var(--stone-900)" }}>
      <div className="ma-sect" style={{ maxWidth: "var(--container-lg)", margin: "0 auto", padding: "clamp(48px,7vw,72px) var(--gutter)" }}>
        <div className="ma-callcard-grid" style={{ display: "grid", gridTemplateColumns: "1.05fr 1fr", gap: 48, alignItems: "center" }}>
          {/* Pitch */}
          <div>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 11, fontWeight: 600, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--sand-300)" }}>
              <Icon name="sparkles" size={15} /> Free AI Preview
            </span>
            <Heading style={{ color: "var(--stone-50)", fontSize: "clamp(30px,4vw,46px)", margin: "12px 0 12px", lineHeight: 1.05, maxWidth: 520 }}>
              See your home in stone — before we lift a trowel.
            </Heading>
            <p style={{ color: "var(--stone-300)", fontSize: 17, lineHeight: 1.6, margin: "0 0 20px", maxWidth: 480 }}>
              Upload a photo of your house or space, tell us what you're picturing, and we'll send back a free AI-rendered preview of your project — no cost, no obligation.
            </p>
            <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 10 }}>
              {[
                ["image-plus", "Upload one photo — that's all we need to start."],
                ["wand-sparkles", "Get an AI preview of your home in real stone."],
                ["ruler", "Love it? We follow up with a real, fixed quote."],
              ].map(([ic, t]) => (
                <li key={t} style={{ display: "flex", alignItems: "center", gap: 11, color: "var(--stone-300)", fontSize: 15 }}>
                  <Icon name={ic} size={18} color="var(--sand-300)" /> {t}
                </li>
              ))}
            </ul>
          </div>

          {/* Form card */}
          <div className="ma-preview-card" style={{ background: "var(--surface-raised)", border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-xl)", padding: "26px 24px", boxShadow: "var(--shadow-lg)" }}>
            {status === "sent" ? (
              <Alert tone="success" title="Your preview is on its way">
                Thanks! We've received your photo and details. Our team will email your free AI preview shortly — usually within 1–3 business days.
              </Alert>
            ) : (
              <form onSubmit={onSubmit} noValidate>
                {status === "error" && (
                  <div style={{ marginBottom: 16 }}>
                    <Alert tone="danger" title="Couldn't send your request">{errorMsg}</Alert>
                  </div>
                )}
                <div className="ma-form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                  <Input name="name" label="Full name" placeholder="Jane Mason" autoComplete="name" required />
                  <Input name="phone" label="Phone" type="tel" placeholder="(208) 555-0123" autoComplete="tel" required />
                  <div style={{ gridColumn: "1 / -1" }}>
                    <Input name="email" label="Email" type="email" placeholder="you@email.com" autoComplete="email" required />
                  </div>
                  <div style={{ gridColumn: "1 / -1" }}>
                    <span style={{ display: "block", fontSize: "var(--text-sm)", fontWeight: "var(--weight-medium)", color: "var(--stone-700)", marginBottom: 6 }}>
                      Photo of your home or project
                    </span>
                    <label htmlFor="ai-preview-photo" style={dropzone}
                      onMouseEnter={(e) => { if (!fileError) e.currentTarget.style.borderColor = "var(--brick-500)"; }}
                      onMouseLeave={(e) => { if (!fileError) e.currentTarget.style.borderColor = "var(--border-strong)"; }}>
                      <Icon name={fileName ? "check-circle-2" : "image-plus"} size={20} color={fileName ? "var(--moss-500)" : "var(--brick-500)"} />
                      {/* `minWidth: 0` is what makes the ellipsis work at all: a flex
                          item's minimum size is its content by default, so without it
                          this nowrap line refuses to shrink and drags the whole
                          section past the edge of a phone screen instead of
                          truncating. */}
                      <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        {fileName || "Click to upload a photo (JPG, PNG · max 10 MB)"}
                      </span>
                      <input ref={fileRef} id="ai-preview-photo" name="photo" type="file" accept="image/*" required onChange={onFileChange} style={{ display: "none" }} />
                    </label>
                    {fileError && (
                      <span style={{ display: "block", fontSize: "var(--text-xs)", color: "var(--clay-500)", marginTop: 5 }}>{fileError}</span>
                    )}
                  </div>
                  <div style={{ gridColumn: "1 / -1" }}>
                    <Textarea name="description" label="What's the project?" rows={4} required
                      placeholder="Tell us what you're picturing — e.g. 'Refacing the front elevation in a warm ledgestone.' Include style, materials, and anything else we should know." />
                  </div>
                  <div style={{ gridColumn: "1 / -1" }}>
                    {/* Allowed to wrap: on a 320px phone the label and icon are
                        wider than the card, and a nowrap button spills out of it. */}
                    <Button variant="primary" size="lg" fullWidth type="submit" disabled={status === "sending"}
                      style={{ whiteSpace: "normal", textAlign: "center", lineHeight: 1.2 }}
                      trailingIcon={status === "sending" ? null : <Icon name="sparkles" size={20} />}>
                      {status === "sending" ? "Sending…" : "Get My Free AI Preview"}
                    </Button>
                  </div>
                  {/* The promise and the page that backs it up, in the one
                      place a visitor is deciding whether to hand over a phone
                      number. A privacy link in the footer is for compliance;
                      this one is for the person hesitating over the button. */}
                  <p style={{ gridColumn: "1 / -1", margin: 0, fontSize: 12.5, color: "var(--text-muted)", textAlign: "center" }}>
                    We only use your details to send your preview and follow up. No spam, ever.{" "}
                    <NavLink to="/privacy" style={{ color: "var(--text-muted)", borderBottom: "1px solid var(--border-default)" }}>How we handle your information</NavLink>.
                  </p>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------------------------------------------------------- Footer */
function SiteFooter() {
  useEffect(refreshIcons);
  const cols = [
    ["Services", ["Masonry Projects", "Siding", "Stucco", "Exterior Remodel", "Tuckpointing & Repair"]],
    ["Explore", ["Gallery", "Articles", ...(D.COST_GUIDE_SHOWN ? ["Cost Guide"] : []), "Commercial & Residential"]],
    ["Company", ["About & Our Craft", "Reviews", "Careers"]],
  ];
  return (
    <footer style={{ background: "var(--stone-900)", color: "var(--stone-300)", borderTop: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ maxWidth: "var(--container-lg)", margin: "0 auto", padding: "52px var(--gutter) 36px" }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 44, justifyContent: "space-between", marginBottom: 36 }}>
          <div style={{ maxWidth: 300 }}>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 25, color: "var(--stone-50)", letterSpacing: "-0.02em" }}>Mickelsen<span style={{ color: "var(--sand-300)" }}>.</span></span>
            <p style={{ fontSize: 14, lineHeight: 1.6, marginTop: 12 }}>Family-owned masonry contractor serving the Treasure Valley. Brick, block, stone, and stucco — built to last.</p>
            <div style={{ marginTop: 16 }}><TradeTag items={D.TRADES} inverse size="sm" /></div>
          </div>
          <div style={{ display: "flex", gap: 52, flexWrap: "wrap" }}>
            {cols.map(([t, items]) => (
              <div key={t}>
                <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--sand-300)", marginBottom: 14 }}>{t}</div>
                <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 9 }}>
                  {items.map((i) => <li key={i} style={{ fontSize: 14 }}>{i}</li>)}
                </ul>
              </div>
            ))}
            {/* The shop's details, as real links: on a phone the number dials
                and the email opens a draft. Same data the contact page prints. */}
            <div>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--sand-300)", marginBottom: 14 }}>Contact</div>
              <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 9, fontSize: 14 }}>
                <li><a href={D.PHONE.href} onClick={() => trackCta("call")} style={{ color: "var(--stone-200)", borderBottom: "none", textDecoration: "none" }}>{D.PHONE.display}</a></li>
                <li><a href={`mailto:${D.EMAIL}`} style={{ color: "var(--stone-200)", borderBottom: "none", textDecoration: "none", overflowWrap: "anywhere" }}>{D.EMAIL}</a></li>
                <li>{D.ADDRESS.display}</li>
                <li>{D.HOURS.display}</li>
                <li style={{ color: "var(--stone-400)", fontSize: 13 }}>{D.HOURS.note}</li>
              </ul>
            </div>
          </div>
        </div>
        <div style={{ borderTop: "1px solid rgba(255,255,255,0.12)", paddingTop: 20, display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8, fontSize: 13, color: "var(--stone-400)" }}>
          <span>© 2026 Mickelsen Accents, Inc. · {D.REGISTRATION.display}</span>
          {/* The one real link in this footer — the other columns above are
              still plain labels. A privacy policy nobody can reach is a
              document, not a disclosure, and ad platforms look for it here. */}
          <span style={{ display: "flex", gap: 8 }}>
            <NavLink to="/privacy" style={{ color: "var(--stone-300)", borderBottom: "1px solid rgba(255,255,255,0.25)" }}>Privacy Policy</NavLink>
            <span aria-hidden="true">·</span>
            <span>Licensed &amp; insured · {D.ADDRESS.city}, Idaho</span>
          </span>
        </div>
      </div>
    </footer>
  );
}

/* ------------------------------------------------------ Real gallery photo
   The counterpart to `Photo` (the tinted placeholder in pages-a.jsx): same
   frame, same corner radius, but an actual uploaded image inside it.

   Everything shown here is owner-entered, so `title` is safe as alt text — but
   it's still the caption that carries meaning, and an empty alt on a decorative
   thumbnail is better than a filename read aloud. */
function GalleryPhoto({ item, h = 200, style, cover = true }) {
  return (
    <div style={{ position: "relative", height: h, background: "var(--stone-200)", borderRadius: "var(--radius-lg)", overflow: "hidden", ...style }}>
      <img
        src={item.imageUrl}
        alt={item.title || ""}
        loading="lazy"
        decoding="async"
        style={{ width: "100%", height: "100%", objectFit: cover ? "cover" : "contain", display: "block" }}
      />
    </div>
  );
}

/* ---------------------------------------------------- Shared page header */
/* `photo` takes the props of DATA.photo(key), and gets two different treatments.
   On a wide screen it sits behind the title under the same left-weighted scrim
   the home hero uses: the heading side stays dark enough to read, the masonry on
   the right stays visible.

   On a phone that reading fails — the title and lede stack into one dark block
   of text and a dimmed photo behind them breaks nothing up. So below 640px the
   background and its scrim are hidden and the same shot renders in the flow
   instead, between the title and the lede, where it gives the eye somewhere to
   land before the paragraph starts. Both <img>s carry the same src, so this is
   one network fetch, and only ever one of them is displayed — which also keeps
   a screen reader from meeting the alt text twice.

   `photo.position` (a CSS object-position) overrides the default vertical crop
   for a shot whose subject doesn't sit near the middle.

   Without a photo the header falls back to the flat tint and stone texture, so a
   page that has no photo to give still renders exactly as it did before. */
function PageHeader({ eyebrow, title, lede, tint = "stone-900", photo }) {
  const src = photo && photo.src;
  return (
    <section className="tex-stone" style={{ position: "relative", overflow: "hidden", background: `var(--${tint})` }}>
      {src && (
        <img
          className="ma-pagehead-bg"
          src={src}
          alt={photo.alt || ""}
          fetchpriority="high"
          decoding="async"
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: photo.position || "center 55%" }}
        />
      )}
      {src && <div aria-hidden="true" className="ma-pagehead-scrim" style={{ position: "absolute", inset: 0, background: "linear-gradient(90deg, rgba(28,26,23,0.93) 0%, rgba(28,26,23,0.80) 48%, rgba(28,26,23,0.42) 100%)" }} />}
      <div className="ma-pagehead" style={{ position: "relative", maxWidth: "var(--container-lg)", margin: "0 auto", padding: "68px var(--gutter) 60px" }}>
        {eyebrow && <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--sand-300)" }}>{eyebrow}</span>}
        <h1 style={{ color: "var(--stone-50)", fontSize: "clamp(34px,5vw,60px)", lineHeight: 1.03, letterSpacing: "-0.02em", margin: "14px 0 0", maxWidth: 780 }}>{title}</h1>
        {src && <img className="ma-pagehead-inline" src={src} alt={photo.alt || ""} decoding="async" />}
        {lede && <p style={{ color: "var(--stone-300)", fontSize: 19, lineHeight: 1.55, maxWidth: 620, margin: "20px 0 0" }}>{lede}</p>}
      </div>
    </section>
  );
}

/* Section heading used inside page bodies */
function SectionHead({ eyebrow, title, lede, center }) {
  return (
    <div style={{ textAlign: center ? "center" : "left", marginBottom: 36, maxWidth: center ? 640 : "none", marginLeft: center ? "auto" : 0, marginRight: center ? "auto" : 0 }}>
      {eyebrow && <span className="eyebrow">{eyebrow}</span>}
      <h2 style={{ fontSize: "clamp(28px,3.6vw,42px)", margin: "10px 0 0" }}>{title}</h2>
      {lede && <p style={{ fontSize: 18, color: "var(--text-muted)", margin: "12px 0 0", lineHeight: 1.55 }}>{lede}</p>}
    </div>
  );
}

/* Whole-elevation upsell block placed on aspect pages */
function UpsellBlock() {
  useEffect(refreshIcons);
  return (
    <div style={{ background: "var(--surface-raised)", border: "1px solid var(--border-default)", borderLeft: "4px solid var(--brick-500)", borderRadius: "var(--radius-lg)", padding: "24px 26px", display: "flex", alignItems: "center", gap: 20, flexWrap: "wrap" }}>
      <Icon name="sparkles" size={26} color="var(--brick-500)" />
      <p style={{ margin: 0, flex: 1, minWidth: "min(260px, 100%)", fontSize: 16.5, color: "var(--text-body)", lineHeight: 1.5 }}>
        Most of our clients start with one feature and finish the whole elevation.
      </p>
      {/* Buttons are nowrap by default so a short label never breaks mid-phrase.
          This one is a sentence, and on a narrow phone an unbreakable sentence is
          wider than the screen — so it wraps rather than pushing the page sideways. */}
      <Button variant="outline" href="/gallery" style={{ whiteSpace: "normal", textAlign: "left" }} trailingIcon={<Icon name="arrow-right" size={18} />}>See the full transformation</Button>
    </div>
  );
}

Object.assign(window, {
  MA: {
    Icon, refreshIcons, trackCta, useRoute, go, NavLink, useGallery, useArticles, GalleryPhoto, CallLabel,
    SiteHeader, CallingCard, ContactCTA, AIPreviewCTA, SiteFooter, PageHeader, SectionHead, UpsellBlock,
    Button, Badge, Card, StatBlock, Input, Textarea, Select, Checkbox, Alert, TradeTag, Divider,
  },
});
