/* global React */
/* Page views — part A. Depends on window.MA (shell) + window.MA_DATA. */
const M = window.MA;
const DATA = window.MA_DATA;
const { Icon, Button, Card, Badge, StatBlock, PageHeader, SectionHead, UpsellBlock, refreshIcons, trackCta, useGallery, GalleryPhoto } = M;
const { useEffect: _useEffect } = React;

const WRAP = { maxWidth: "var(--container-lg)", margin: "0 auto", padding: "clamp(44px, 7vw, 72px) var(--gutter)" };

/* ---------------------------------------------------------------------------
   A strip of recent work, used on the home page and on every service detail
   page. Real uploads win; the tinted placeholders in nav-data.js only show on a
   site whose gallery is still empty, so a fresh install never renders a blank
   row where the proof is supposed to be.
   --------------------------------------------------------------------------- */
function RecentWork({ count = 6, h = 200 }) {
  const gal = useGallery();
  const items = gal.items.slice(0, count);
  if (items.length) {
    return (
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(min(280px,100%),1fr))", gap: 18 }}>
        {items.map((item) => (
          <M.NavLink key={item.id} to="/gallery">
            <figure style={{ margin: 0 }}>
              <GalleryPhoto item={item} h={h} />
              <figcaption style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, padding: "12px 2px 0" }}>
                <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 17, color: "var(--text-strong)" }}>{item.title}</span>
                <span style={{ fontSize: 13, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{gal.labels[item.tags[0]] || ""}</span>
              </figcaption>
            </figure>
          </M.NavLink>
        ))}
      </div>
    );
  }
  // Still loading: hold the space rather than flashing placeholders that are
  // about to be replaced by the owner's actual photos.
  if (gal.loading) return <div style={{ minHeight: h + 30 }} />;
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(min(280px,100%),1fr))", gap: 18 }}>
      {DATA.PROJECTS.slice(0, count).map(([name, cat, stone, tint]) => (
        <figure key={name} style={{ margin: 0 }}>
          <Photo tint={tint} h={h} cat={cat} />
          <figcaption style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 2px 0" }}>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 17, color: "var(--text-strong)" }}>{name}</span>
            <span style={{ fontSize: 13, color: "var(--text-muted)" }}>{stone}</span>
          </figcaption>
        </figure>
      ))}
    </div>
  );
}

/* A project photo from assets/photos, or — with no `src` — the texture-tinted
   placeholder it replaces. The tint stays underneath either way, so a slow image
   fades in over the brand color rather than over a white hole. */
function Photo({ tint = "brick-500", h = 200, label, cat, src, alt = "", style }) {
  return (
    <div className={src ? undefined : "tex-brick"} style={{ position: "relative", height: h, background: `var(--${tint})`, borderRadius: "var(--radius-lg)", overflow: "hidden", display: "flex", alignItems: "flex-start", padding: 12, ...style }}>
      {src && <img src={src} alt={alt} loading="lazy" decoding="async" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", display: "block" }} />}
      {cat && <Badge tone="solid" style={{ position: "relative", background: "rgba(28,26,23,0.55)", borderColor: "transparent" }}>{cat}</Badge>}
      {label && <span style={{ position: "absolute", left: 14, bottom: 12, color: "#fff", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 18, textShadow: "0 1px 4px rgba(0,0,0,.4)" }}>{label}</span>}
    </div>
  );
}

/* ============================================================= HOME ==== */
function HomePage() {
  _useEffect(refreshIcons);
  const stats = [["20", "+", "Years in Trade"], ["5,000", "+", "Jobs Completed"], ["4", "", "Generations"], ["2006", "", "Founded"]];
  const svc = DATA.SERVICE_COLUMNS;
  return (
    <div>
      {/* Hero */}
      {/* The photo sits under a left-weighted scrim: the headline and buttons
          need the dark side to stay legible, and the stonework on the right is
          what the visitor should see past them. */}
      <section id="top" style={{ position: "relative", overflow: "hidden", background: "var(--stone-900)" }}>
        <img {...DATA.photo(DATA.HERO_PHOTO)} fetchpriority="high" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 38%" }} />
        {/* Lighter on the right than it used to be: the dusk sky and the lit
            entry are the point of this shot, and the headline only needs the
            left half dark. */}
        <div aria-hidden="true" style={{ position: "absolute", inset: 0, background: "linear-gradient(90deg, rgba(28,26,23,0.90) 0%, rgba(28,26,23,0.72) 45%, rgba(28,26,23,0.22) 100%)" }} />
        <div className="ma-hero" style={{ position: "relative", maxWidth: "var(--container-lg)", margin: "0 auto", padding: "92px var(--gutter) 100px" }}>
          <div style={{ maxWidth: 740 }}>
            <M.TradeTag items={DATA.TRADES} inverse size="md" />
            <h1 style={{ color: "var(--stone-50)", fontSize: "clamp(46px,6.4vw,86px)", fontWeight: 700, lineHeight: 1.0, letterSpacing: "-0.02em", margin: "18px 0 22px" }}>
              Masonry built to<br/>last a lifetime.
            </h1>
            <p style={{ color: "var(--stone-300)", fontSize: 21, lineHeight: 1.5, maxWidth: 580, margin: "0 0 34px" }}>
              Four generations of masons laying brick, block, stone, and stucco to one standard — finished right the first time.
            </p>
            <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
              <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="/gallery" style={{ color: "var(--stone-50)", borderColor: "rgba(255,255,255,0.3)" }} leadingIcon={<Icon name="images" size={20} />}>See Our Work</Button>
            </div>
          </div>
        </div>
      </section>

      {/* Trust bar */}
      <section style={{ background: "var(--surface-raised)", borderBottom: "1px solid var(--border-hairline)" }}>
        <div style={{ maxWidth: "var(--container-lg)", margin: "0 auto", padding: "34px var(--gutter)", display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 24 }} className="ma-trust-grid">
          {stats.map(([v, s, l]) => <StatBlock key={l} value={v} suffix={s} label={l} />)}
        </div>
      </section>

      {/* Services preview */}
      <section style={WRAP}>
        <SectionHead eyebrow="What We Do" title="The whole exterior, finished right" lede="One standard for every scope, so the finished elevation reads as one design from footing to finish." />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(min(240px,100%),1fr))", gap: 20 }}>
          {svc.map((col) => (
            <M.NavLink key={col.title} to="/services">
              <Card accent interactive padding="lg" style={{ height: "100%" }}>
                <div style={{ width: 46, height: 46, borderRadius: 6, background: "var(--brick-50)", display: "grid", placeItems: "center", marginBottom: 16 }}>
                  <Icon name={col.icon} size={24} color="var(--brick-600)" />
                </div>
                <h3 style={{ fontSize: 21, margin: "0 0 8px" }}>{col.title}</h3>
                <p style={{ fontSize: 15, color: "var(--text-body)", margin: "0 0 14px", lineHeight: 1.55 }}>{(col.card || col.items.slice(0, 3).map((i) => i[0])).join(" · ")} & more.</p>
                <span style={{ fontSize: 14, fontWeight: 600, color: "var(--brick-600)", display: "inline-flex", alignItems: "center", gap: 6 }}>Explore <Icon name="arrow-right" size={16} /></span>
              </Card>
            </M.NavLink>
          ))}
        </div>
        <div style={{ textAlign: "center", marginTop: 32 }}>
          <Button variant="ink" href="/services">See all services</Button>
        </div>
      </section>

      {/* Gallery preview */}
      <section style={WRAP}>
        <SectionHead eyebrow="Our Work" title="Recent projects" />
        <RecentWork count={6} h={200} />
        <div style={{ textAlign: "center", marginTop: 32 }}><Button variant="outline" href="/gallery">View the full gallery</Button></div>
      </section>
    </div>
  );
}

/* ========================================================= SERVICES ==== */
function ServicesPage() {
  _useEffect(refreshIcons);
  return (
    <div>
      {/* The index header wants the elevation that shows the most trades at
          once — siding, stone chimney, stone wainscot, timber and trim — because
          that is exactly what "every scope, one standard" means. */}
      <PageHeader eyebrow="Services" title="Every scope, one standard" lede="Stone is our craft. Siding, stucco, and the rest of the elevation are held to the same standard, so the whole exterior is finished right the first time." photo={DATA.photo("farmhouse-stone-chimney")} />
      <div style={WRAP}>
        <div style={{ display: "flex", flexDirection: "column", gap: 52 }}>
          {DATA.SERVICE_COLUMNS.map((col) => (
            <div key={col.title}>
              <M.NavLink to={`/category/${col.slug}`} style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
                <div style={{ width: 44, height: 44, borderRadius: 6, background: "var(--brick-50)", display: "grid", placeItems: "center" }}>
                  <Icon name={col.icon} size={22} color="var(--brick-600)" />
                </div>
                <div>
                  <h2 style={{ fontSize: 26, margin: 0 }}>{col.title}</h2>
                  {col.note && <div style={{ fontSize: 13, fontStyle: "italic", color: "var(--sand-500)", fontWeight: 500 }}>{col.note}</div>}
                </div>
              </M.NavLink>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(min(280px,100%),1fr))", gap: 12 }}>
                {col.items.map(([label]) => (
                  <M.NavLink key={label} to={`/category/${col.slug}`}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, background: "var(--surface-raised)", border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", padding: "14px 16px", boxShadow: "var(--shadow-xs)", 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 = "var(--shadow-xs)"; }}>
                      <span style={{ fontSize: 15, fontWeight: 500, color: "var(--text-strong)" }}>{label}</span>
                      <Icon name="arrow-up-right" size={17} color="var(--stone-400)" />
                    </div>
                  </M.NavLink>
                ))}
              </div>
            </div>
          ))}

          {/* The rest of the owner's service list: the scopes that come with a
              job rather than having pages of their own. */}
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
              <div style={{ width: 44, height: 44, borderRadius: 6, background: "var(--brick-50)", display: "grid", placeItems: "center" }}>
                <Icon name="truck" size={22} color="var(--brick-600)" />
              </div>
              <h2 style={{ fontSize: 26, margin: 0 }}>Also Part of the Job</h2>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(min(280px,100%),1fr))", gap: 12 }}>
              {DATA.SUPPORT_SERVICES.map(([label, blurb]) => (
                <div key={label} style={{ background: "var(--surface-raised)", border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", padding: "14px 16px", boxShadow: "var(--shadow-xs)" }}>
                  <div style={{ fontSize: 15, fontWeight: 500, color: "var(--text-strong)" }}>{label}</div>
                  <p style={{ fontSize: 13.5, color: "var(--text-muted)", margin: "4px 0 0", lineHeight: 1.5 }}>{blurb}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ===================================================== SIDEBAR CARD ====
   The card under the photo on category and service detail pages. On the
   Exterior Remodel page it asks for the estimate outright. Everywhere else it
   points up to Exterior Remodel instead: someone reading about one trade is
   usually a stone line away from needing the rest of the elevation,
   and the page's closing band still offers the plain estimate. */
function SidebarCard({ remodel }) {
  if (remodel) {
    return (
      <Card padding="md" style={{ marginTop: 16 }}>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 18, marginBottom: 6 }}>Start with a free estimate</div>
        <p style={{ fontSize: 14, color: "var(--text-muted)", margin: "0 0 14px", lineHeight: 1.5 }}>We'll walk the site and quote a fixed scope — no obligation.</p>
        <Button variant="primary" fullWidth href="/contact" onClick={() => trackCta("estimate")}>Request an Estimate</Button>
      </Card>
    );
  }
  return (
    <Card padding="md" style={{ marginTop: 16 }}>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 18, marginBottom: 6 }}>Doing more than one?</div>
      <p style={{ fontSize: 14, color: "var(--text-muted)", margin: "0 0 14px", lineHeight: 1.5 }}>Stone, siding, stucco, and the landscaping around them: plan the whole exterior as one remodel, designed together and finished right the first time.</p>
      <Button variant="primary" fullWidth href={`/category/${DATA.REMODEL_SLUG}`} style={{ whiteSpace: "normal" }} trailingIcon={<Icon name="arrow-right" size={18} />}>Explore Exterior Remodels</Button>
    </Card>
  );
}

/* ==================================================== SERVICE DETAIL ==== */
/* Title for a service slug that has no hand-written entry in SERVICE_CONTENT.
   Joining words stay lowercase so "stone-and-stucco" reads as a phrase rather
   than a filename with the hyphens taken out. */
const MINOR_WORDS = new Set(["and", "or", "with", "vs", "the", "a", "to"]);
function humanize(slug) {
  return slug
    .split("-")
    .map((w, i) => (i && MINOR_WORDS.has(w) ? w : w[0].toUpperCase() + w.slice(1)))
    .join(" ");
}
/* The sidebar photo for a service: its own if it has one, otherwise the photo
   of the category it's tagged with, then the masonry one. */
function servicePhoto(slug, tag) {
  const own = DATA.SERVICE_PHOTOS[slug];
  if (own) return DATA.photo(own);
  const parent = DATA.SERVICE_COLUMNS.find((col) => col.title === tag);
  return DATA.photo((parent || DATA.SERVICE_COLUMNS[0]).photo);
}
function ServiceDetailPage({ slug }) {
  _useEffect(refreshIcons);
  const c = DATA.SERVICE_CONTENT[slug];
  const title = c ? c.title : humanize(slug);
  const tag = c ? c.tag : "Stone Masonry";
  const lede = c ? c.lede : `${title} from a family contractor that looks at every job and asks if it's good enough for our own home.`;
  const body = c ? c.body : `We approach every ${title.toLowerCase()} job the same way: assess the wall, choose the right stone, and flash it properly so it sheds water for decades. Tell us about your project and we'll walk the site with you.`;
  const bullets = c ? c.bullets : ["Finished right the first time", "Proper drainage plane & flashing", "Stone matched to your home", "Clean, protected job site"];
  return (
    <div>
      <PageHeader eyebrow={tag} title={title} lede={lede} photo={servicePhoto(slug, tag)} />
      <div style={WRAP}>
        <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 44, alignItems: "start" }} className="ma-detail-grid">
          <div>
            <p style={{ fontSize: 18, lineHeight: 1.65, color: "var(--text-body)", marginTop: 0 }}>{body}</p>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, margin: "24px 0 8px" }}>
              {bullets.map((b) => (
                <div key={b} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                  <Icon name="check" size={18} color="var(--moss-500)" stroke={2.6} style={{ marginTop: 2 }} />
                  <span style={{ fontSize: 14.5, color: "var(--text-body)", lineHeight: 1.45 }}>{b}</span>
                </div>
              ))}
            </div>
          </div>
          {/* No sidebar photo here: the same shot now runs full-bleed behind
              the page title, and showing it twice on one screen just reads as
              a mistake. The category badge it carried is the header eyebrow. */}
          <div>
            <SidebarCard />
          </div>
        </div>
        <div style={{ marginTop: 44 }}><UpsellBlock /></div>
        <div style={{ marginTop: 52 }}>
          <SectionHead eyebrow="Proof" title="Related work" />
          <RecentWork count={3} h={180} />
        </div>
      </div>
    </div>
  );
}

/* ==================================================== CATEGORY PAGE ====
   One consolidated page per top-level service column, with a short detail
   for every sub-category. */
function CategoryPage({ slug }) {
  _useEffect(refreshIcons);
  const col = DATA.SERVICE_COLUMNS.find((c) => c.slug === slug) || DATA.SERVICE_COLUMNS[0];
  return (
    <div>
      <PageHeader eyebrow="Services" title={col.title} lede={col.lede} photo={DATA.photo(col.photo)} />
      <div style={WRAP}>
        {/* SEO / overview block — above the services, under the title & subtitle */}
        {col.seo && (
          <div style={{ marginBottom: 44, paddingBottom: 36, borderBottom: "1px solid var(--border-hairline)", maxWidth: 900 }}>
            <p style={{ fontSize: 17, lineHeight: 1.75, color: "var(--text-body)", margin: 0, textWrap: "pretty" }}>{col.seo}</p>
          </div>
        )}
        {col.note && (
          <div style={{ display: "inline-flex", alignItems: "center", gap: 8, marginBottom: 24, padding: "8px 14px", background: "var(--sand-100)", border: "1px solid var(--sand-300)", borderRadius: "var(--radius-md)" }}>
            <Icon name="layout-grid" size={16} color="var(--sand-500)" />
            <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--sand-500)", fontStyle: "italic" }}>{col.note}</span>
          </div>
        )}
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 44, alignItems: "start" }} className="ma-detail-grid">
          {/* Sub-category detail list */}
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {col.items.map(([label, blurb], i) => (
              <div key={label} style={{ display: "flex", gap: 14, padding: "18px 0", borderTop: i ? "1px solid var(--border-hairline)" : "none" }}>
                <div style={{ width: 34, height: 34, flex: "none", borderRadius: 6, background: "var(--brick-50)", display: "grid", placeItems: "center", marginTop: 2 }}>
                  <Icon name={col.icon} size={16} color="var(--brick-600)" />
                </div>
                <div>
                  <h3 style={{ fontSize: 18, margin: "0 0 4px" }}>{label}</h3>
                  <p style={{ fontSize: 14.5, color: "var(--text-body)", margin: 0, lineHeight: 1.5 }}>{blurb}</p>
                </div>
              </div>
            ))}
          </div>
          {/* Sticky estimate card. The category photo that used to sit above it
              is now the header background, and one page should not show the
              same shot twice. */}
          <div>
            <SidebarCard remodel={col.slug === DATA.REMODEL_SLUG} />
          </div>
        </div>
        <div style={{ marginTop: 40 }}><UpsellBlock /></div>
      </div>
    </div>
  );
}

Object.assign(window, { MA_PAGES_A: { HomePage, ServicesPage, ServiceDetailPage, CategoryPage, Photo, RecentWork } });
