/* global React */
const { useState, useEffect, createContext, useContext, useCallback } = React;

/* ============================================
   ROUTER
   ============================================ */
const RouteContext = createContext({ path: "/", go: () => {} });
function useRouter() { return useContext(RouteContext); }

function RouterProvider({ children }) {
  const [path, setPath] = useState(() => (window.location.hash.replace(/^#/, "") || "/"));
  useEffect(() => {
    const on = () => setPath(window.location.hash.replace(/^#/, "") || "/");
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);
  const go = useCallback((p) => {
    window.location.hash = p;
    window.scrollTo({ top: 0, behavior: "instant" });
  }, []);
  return <RouteContext.Provider value={{ path, go }}>{children}</RouteContext.Provider>;
}

function Link({ to, children, className, onClick, ...rest }) {
  const { go } = useRouter();
  return (
    <a
      href={"#" + to}
      className={className}
      onClick={(e) => {
        if (e.metaKey || e.ctrlKey || e.shiftKey) return;
        e.preventDefault();
        if (onClick) onClick(e);
        go(to);
      }}
      {...rest}
    >
      {children}
    </a>
  );
}

/* ============================================
   CONSTANTS
   ============================================ */
const PHONE_DISPLAY = "07966 847028";
const PHONE_TEL = "tel:+447966847028";
const EMAIL = "Info@hensonengineering.co.uk";

const NAV = [
  { to: "/", label: "Home" },
  { to: "/services", label: "Services" },
  { to: "/gallery", label: "Gallery" },
  { to: "/about", label: "About" },
  { to: "/contact", label: "Contact" },
];

/* ============================================
   PLACEHOLDER (Unsplash-backed image, striped fallback)
   ============================================ */
const IMG_BASE = "https://source.unsplash.com";
function imgUrl(keywords, w = 1600, h = 1100) {
  return `${IMG_BASE}/featured/${w}x${h}/?${encodeURIComponent(keywords)}`;
}

function Placeholder({ label, img, w = 1600, h = 1100, paper, className = "", style }) {
  const src = img ? imgUrl(img, w, h) : null;
  return (
    <div
      className={`simg ${paper ? "simg-paper" : ""} ${src ? "has-img" : ""} ${className}`}
      data-label={label || ""}
      style={style}
    >
      {src && (
        <img
          src={src}
          alt={label || ""}
          loading="lazy"
          draggable="false"
          onError={(e) => { e.currentTarget.style.display = "none"; }}
        />
      )}
    </div>
  );
}

/* ============================================
   UTILITY BAR
   ============================================ */
function UtilityBar() {
  return (
    <div className="h-utility">
      <div className="container">
        <div className="left">
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
            <span className="dot" />
            <span className="open-long">Workshop open · Mon–Fri 08:00–17:00</span>
            <span className="open-short" style={{ display: "none" }}>Open · Mon–Fri</span>
          </span>
        </div>
        <div className="right">
          <a className="email-show" href={`mailto:${EMAIL}`}>{EMAIL}</a>
          <a href={PHONE_TEL}>{PHONE_DISPLAY}</a>
        </div>
      </div>
    </div>
  );
}

/* ============================================
   HEADER
   ============================================ */
function Header() {
  const { path } = useRouter();
  const [open, setOpen] = useState(false);
  useEffect(() => { setOpen(false); }, [path]);
  const isActive = (to) => to === "/" ? path === "/" : path.startsWith(to);
  return (
    <header className="site-header" data-screen-label="Header">
      <div className="container">
        <Link to="/" className="brand" aria-label="Henson Engineering — home">
          <img src="logo-henson.png" className="brand-logo" alt="Henson Engineering" />
          <div className="brand-divider" />
          <div className="brand-name">Slowley Farm · Somerset · 1962</div>
        </Link>
        <nav className="nav">
          {NAV.map(n => (
            <Link key={n.to} to={n.to} className={isActive(n.to) ? "active" : ""}>{n.label}</Link>
          ))}
        </nav>
        <div style={{ display: "flex", gap: 16, alignItems: "center" }}>
          <a className="tel-line" href={PHONE_TEL}>{PHONE_DISPLAY}</a>
          <button className="nav-toggle" aria-label="Menu" onClick={() => setOpen(o => !o)}>
            <span />
          </button>
        </div>
      </div>
      <div className={`mobile-nav ${open ? "open" : ""}`}>
        {NAV.map(n => <Link key={n.to} to={n.to}>{n.label}</Link>)}
      </div>
    </header>
  );
}

/* ============================================
   STICKY MOBILE CALL
   ============================================ */
function StickyCall() {
  return (
    <a className="sticky-call" href={PHONE_TEL}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.73 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.36 1.85.6 2.81.73A2 2 0 0 1 22 16.92z"/></svg>
      <span>Call Richard</span>
      <span className="num">{PHONE_DISPLAY}</span>
    </a>
  );
}

function FloatingBanner() {
  return (
    <a className="floating-banner" href={PHONE_TEL}>
      <span>On the job — call Richard direct —</span>
      <span className="num">{PHONE_DISPLAY}</span>
    </a>
  );
}

/* ============================================
   FOOTER
   ============================================ */
function Footer() {
  return (
    <footer className="footer" data-screen-label="Footer">
      <div>© Henson Engineering Ltd · 2026 · Slowley Farm · Luxborough · TA23 0SB</div>
      <div style={{ display: "flex", gap: 18, flexWrap: "wrap" }}>
        <span>VAT 314 8821 06</span>
        <span>Co. 03847291</span>
        <a href="https://htsteel.co.uk" target="_blank" rel="noreferrer">HT Steel ↗</a>
      </div>
    </footer>
  );
}

/* ============================================
   HT Steel cross-link
   ============================================ */
function HTSteelBand() {
  return (
    <section className="htsteel-band" data-screen-label="HT Steel cross-link">
      <div className="mark">HT</div>
      <div>
        <h3>Sister company — for structural steel, see HT Steel.</h3>
        <p>HT Steel handles the heavy end of the business: beams, frames, architectural metalwork and larger commercial steel contracts. Same family, different yard.</p>
      </div>
      <a className="link" href="https://htsteel.co.uk" target="_blank" rel="noreferrer">
        htsteel.co.uk ↗
      </a>
    </section>
  );
}

/* ============================================
   CTA card (service detail)
   ============================================ */
function CTACard({ title }) {
  return (
    <div className="svc-cta-card">
      <div>
        <div className="ttl">{title}</div>
        <div className="sub">Call Richard direct on <span className="num">{PHONE_DISPLAY}</span></div>
      </div>
      <a className="btn btn-accent" href={PHONE_TEL}>Tap to call →</a>
    </div>
  );
}

Object.assign(window, {
  useRouter, RouterProvider, Link, Placeholder,
  UtilityBar, Header, StickyCall, FloatingBanner, Footer, HTSteelBand, CTACard,
  PHONE_DISPLAY, PHONE_TEL, EMAIL, NAV,
});
