/* global React */
/* Patch Me Up — shared building blocks
   Exposed to window so other Babel scripts can read them. */
const { useState, useEffect, useRef } = React;

/* ─────────── Hash router ─────────── */
function useRoute() {
  const get = () => (window.location.hash || "#/").replace(/^#/, "") || "/";
  const [route, setRoute] = useState(get);
  useEffect(() => {
    const onHash = () => { setRoute(get()); window.scrollTo({ top: 0, behavior: "instant" }); };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
}
function nav(to) {
  if (typeof to === "string" && to.startsWith("#")) to = to.slice(1);
  window.location.hash = to;
}

/* ─────────── Icon (uses inline sprite) ─────────── */
function Icon({ name, size = 22, className = "", style = {} }) {
  return (
    <svg
      className={"icon " + className}
      style={{ width: size, height: size, flexShrink: 0, ...style }}
      viewBox="0 0 24 24"
      aria-hidden="true"
    >
      <use href={`#${name}`} />
    </svg>
  );
}

/* ─────────── Logo ─────────── */
function LogoMark({ size = 36 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 64 64" aria-label="Patch Me Up">
      <rect x="3" y="3" width="58" height="58" rx="14" fill="#174E5D"></rect>
      <path
        d="M44.5 32a12.5 12.5 0 1 1-7.3-11.36"
        fill="none"
        stroke="#F7F3EA"
        strokeWidth="4.5"
        strokeLinecap="round"
      ></path>
      <circle cx="42.6" cy="22.4" r="3.6" fill="#EBCB66"></circle>
    </svg>
  );
}

function NavLogo({ size = 32, color = "var(--pmu-teal)", subColor = "var(--fg-muted)" }) {
  return (
    <a className="nav-logo" onClick={(e) => { e.preventDefault(); nav("/"); }} href="#/">
      <LogoMark size={size} />
      <div className="col">
        <span className="word" style={{ color }}>Patch Me Up</span>
        <span className="sub" style={{ color: subColor }}>WALL &amp; CEILING REPAIR</span>
      </div>
    </a>
  );
}

/* ─────────── Button ─────────── */
function Button({ children, kind = "primary", size = "md", to, href, onClick, type = "button", style = {}, ...rest }) {
  const cls =
    "btn " +
    (kind === "primary"   ? "btn-primary"   :
     kind === "action"    ? "btn-action"    :
     kind === "secondary" ? "btn-secondary" :
     kind === "ghost"     ? "btn-ghost"     :
     kind === "on-dark"   ? "btn-on-dark"   : "btn-primary") +
    (size === "lg" ? " btn-lg" : size === "sm" ? " btn-sm" : "");
  const handle = (e) => {
    if (onClick) onClick(e);
    if (to && !e.defaultPrevented) { e.preventDefault(); nav(to); }
  };
  if (href) return <a className={cls} href={href} style={style} {...rest}>{children}</a>;
  return <button type={type} className={cls} onClick={handle} style={style} {...rest}>{children}</button>;
}

/* ─────────── Eyebrow chip ─────────── */
function Eyebrow({ icon = "loop", dark = false, children }) {
  return (
    <span className={"eyebrow" + (dark ? " is-dark" : "")}>
      {icon && <Icon name={icon} size={14} />}
      {children}
    </span>
  );
}

/* ─────────── Section header ─────────── */
function SectionHead({ eyebrow, eyebrowIcon = "loop", dark = false, title, sub, children }) {
  return (
    <div className="section-head">
      {eyebrow && <Eyebrow icon={eyebrowIcon} dark={dark}>{eyebrow}</Eyebrow>}
      <h2>{title}</h2>
      {sub && <p>{sub}</p>}
      {children}
    </div>
  );
}

/* ─────────── Nav ─────────── */
function Nav() {
  const route = useRoute();
  const [open, setOpen] = useState(false);
  const isActive = (path) =>
    (path === "/" && route === "/") ||
    (path !== "/" && route.startsWith(path));

  const link = (path, label) => (
    <a
      key={path}
      onClick={(e) => { e.preventDefault(); setOpen(false); nav(path); }}
      href={"#" + path}
      className={isActive(path) ? "is-active" : ""}
    >{label}</a>
  );

  return (
    <header className="nav">
      <NavLogo size={34} />
      <nav className="nav-links">
        {link("/services", "Services")}
        {link("/repair/post-trade", "After Trade Work")}
        {link("/partners", "Partners")}
        {link("/proof", "Proof Gallery")}
        {link("/how-it-works", "How It Works")}
      </nav>
      <div className="nav-cta">
        <a className="nav-phone" href="tel:6025550148">
          <Icon name="phone" size={14} />
          (602) 555‑0148
        </a>
        <Button kind="action" size="sm" to="/send-photos">
          <Icon name="camera" size={16} />
          Send Photos
        </Button>
        <button
          className="btn btn-ghost btn-sm nav-mobile-toggle"
          aria-label="Menu"
          onClick={() => setOpen(o => !o)}
          style={{ padding: 8 }}
        >
          <Icon name={open ? "x" : "menu"} size={22} />
        </button>
      </div>
      {open && (
        <div style={{
          position: "absolute", top: "100%", left: 0, right: 0,
          background: "var(--pmu-paper)", borderBottom: "1px solid var(--border)",
          padding: "16px 20px", display: "flex", flexDirection: "column", gap: 14, zIndex: 60
        }}>
          {link("/services", "Services")}
          {link("/repair/post-trade", "After Trade Work")}
          {link("/partners", "Partners")}
          {link("/proof", "Proof Gallery")}
          {link("/how-it-works", "How It Works")}
          <a href="tel:6025550148" style={{ color: "var(--pmu-teal)", fontWeight: 700 }}>(602) 555‑0148</a>
        </div>
      )}
    </header>
  );
}

/* ─────────── Footer ─────────── */
function Footer() {
  const link = (p, l) => (
    <a key={p} onClick={(e) => { e.preventDefault(); nav(p); }} href={"#" + p}>{l}</a>
  );
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-grid">
          <div>
            <NavLogo size={42} color="var(--pmu-wall)" subColor="var(--pmu-sand-soft)" />
            <p className="sub-tag">Wall repair that closes the loop.</p>
          </div>

          <div className="footer-col col gap-2">
            <div className="t-proof">SERVICES</div>
            {link("/services", "All services")}
            {link("/repair/post-trade", "Post‑trade repair")}
            {link("/repair/ceiling", "Ceiling repair")}
            {link("/repair/pre-listing", "Pre‑listing repair")}
            {link("/repair/rental-turn", "Rental turn repair")}
            {link("/repair/failed-diy", "Failed DIY rescue")}
          </div>

          <div className="footer-col col gap-2">
            <div className="t-proof">COMPANY</div>
            {link("/partners", "Trade partners")}
            {link("/proof", "Proof gallery")}
            {link("/how-it-works", "How it works")}
            {link("/pricing", "Pricing guidance")}
            {link("/send-photos", "Send photos")}
          </div>

          <div className="footer-col col gap-2">
            <div className="t-proof">CONTACT</div>
            <p>(602) 555‑0148<br/>hello@patchmeup.co<br/>Mon–Sat · 7a–7p</p>
            <div className="t-proof" style={{ marginTop: 14 }}>SERVICE AREA</div>
            <p>Phoenix · Scottsdale · Tempe · Mesa · Chandler · Gilbert · Glendale</p>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Patch Me Up · An Uncommon Companies brand</span>
          <span className="t-proof">CLOSE&nbsp;THE&nbsp;LOOP</span>
        </div>
      </div>
    </footer>
  );
}

/* ─────────── Before/after frame ─────────── */
function BAFrame({ src, label, after = false }) {
  return (
    <div className="ba-frame">
      <span className={"ba-tag" + (after ? " after" : "")}>{label}</span>
      <img src={src} alt="" />
    </div>
  );
}

/* ─────────── Proof Card (used in proof gallery & landing pages) ─────────── */
function ProofCard({ data, onClick }) {
  return (
    <article className="proof-card">
      <div className="imgs">
        <BAFrame src="ds/photo-before.svg" label="Before" />
        <BAFrame src="ds/photo-after.svg" label="After" after />
      </div>
      <div className="body">
        <div className="meta-line">
          <span className="badge badge-info"><span className="dot"></span>{data.repairType}</span>
          <span className="badge badge-proof"><span className="dot"></span>Closed</span>
        </div>
        <h4>{data.situation}</h4>
        <p className="note">{data.note}</p>
        <div className="foot">
          <span className="job-id">#{data.jobId} · {data.timeframe}</span>
          <button className="similar" onClick={() => nav("/send-photos")}>
            Have a similar repair? <Icon name="arrow-right" size={14} />
          </button>
        </div>
      </div>
    </article>
  );
}

/* ─────────── Expose globals ─────────── */
Object.assign(window, {
  useRoute, nav,
  Icon, LogoMark, NavLogo,
  Button, Eyebrow, SectionHead,
  Nav, Footer, BAFrame, ProofCard,
});
