/* ============ Shared UI: icons, Logo, Placeholder, Nav, Footer ============ */
const { useState, useEffect, useRef, useMemo } = React;
const D = window.KL_DATA;

/* ---------- lead tracking helpers ---------- */
function useBooked() {
  const [info, setInfo] = useState(() => {
    try { return JSON.parse(localStorage.getItem("kl_booked") || "null"); } catch { return null; }
  });
  useEffect(() => {
    const sync = () => {
      try { setInfo(JSON.parse(localStorage.getItem("kl_booked") || "null")); } catch { setInfo(null); }
    };
    window.addEventListener("kl_booked_change", sync);
    window.addEventListener("storage", sync);
    return () => {
      window.removeEventListener("kl_booked_change", sync);
      window.removeEventListener("storage", sync);
    };
  }, []);
  return info;
}
function setBooked(data) {
  if (data) {
    // append to leads log (all bookings tracked)
    let leads = [];
    try { leads = JSON.parse(localStorage.getItem("kl_leads") || "[]"); } catch {}
    leads.push(data);
    localStorage.setItem("kl_leads", JSON.stringify(leads));
    localStorage.setItem("kl_booked", JSON.stringify(data));
  } else {
    localStorage.removeItem("kl_booked");
  }
  window.dispatchEvent(new Event("kl_booked_change"));
}

/* ---------- tiny inline icons (stroke, currentColor) ---------- */
const Ic = {
  phone: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 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.9.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z"/></svg>,
  check: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 6 9 17l-5-5"/></svg>,
  arrow: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 6l6 6-6 6"/></svg>,
  home: (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 11l9-8 9 8M5 9.5V20a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9.5"/></svg>,
  star: (p) => <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" {...p}><path d="m12 2 3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>,
  plus: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" {...p}><path d="M12 5v14M5 12h14"/></svg>,
  minus: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" {...p}><path d="M5 12h14"/></svg>,
  chevron: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="m6 9 6 6 6-6"/></svg>,
  mail: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 6L2 7"/></svg>,
  pin: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/></svg>,
  shield: (p) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/><path d="m9 12 2 2 4-4"/></svg>,
  clock: (p) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>,
  spark: (p) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M18.4 5.6l-2.8 2.8M8.4 15.6l-2.8 2.8"/></svg>,
  euro: (p) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M18 7a7 7 0 1 0 0 10M4 11h9M4 15h7"/></svg>,
  wallet: (p) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 7a2 2 0 0 1 2-2h13a1 1 0 0 1 1 1v2"/><path d="M3 7v10a2 2 0 0 0 2 2h14a1 1 0 0 0 1-1v-3"/><path d="M21 11h-5a2 2 0 0 0 0 4h5v-4Z"/></svg>,
  cal: (p) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>,
  window: (p) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M12 3v18M3 12h18"/></svg>,
  fb: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M14 9h3l.5-3.5H14V3.8c0-1 .3-1.7 1.7-1.7H17V-.8C16.6-.9 15.6-1 14.4-1 12 -1 10.3.5 10.3 3.4V5.5H7.5V9h2.8v9H14V9Z" transform="translate(0 3)"/></svg>,
  ig: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg>,
  google: (p) => <svg width="17" height="17" viewBox="0 0 24 24" {...p}><path fill="#4285F4" d="M22.5 12.2c0-.7-.1-1.4-.2-2H12v3.9h5.9a5 5 0 0 1-2.2 3.3v2.7h3.6c2.1-1.9 3.2-4.7 3.2-7.9Z"/><path fill="#34A853" d="M12 23c2.9 0 5.4-1 7.2-2.6l-3.6-2.7c-1 .7-2.3 1.1-3.6 1.1-2.8 0-5.2-1.9-6-4.4H2.3v2.8A11 11 0 0 0 12 23Z"/><path fill="#FBBC05" d="M6 14.4a6.6 6.6 0 0 1 0-4.2V7.4H2.3a11 11 0 0 0 0 9.8L6 14.4Z"/><path fill="#EA4335" d="M12 5.4c1.6 0 3 .5 4.1 1.6l3.1-3.1A11 11 0 0 0 2.3 7.4L6 10.2c.8-2.5 3.2-4.4 6-4.4Z"/></svg>,
};

function Logo({ light, sub = true }) {
  if (light) {
    /* footer: dark bg — icon tile + white text */
    return (
      <div className="logo">
        <img src="app/logo-icon.png" alt="Lasinen" style={{height:38,width:38,borderRadius:10,display:"block"}}/>
        <span style={{ display: "grid", gap: 2 }}>
          <span className="logo__word" style={{ color: "#fff" }}>Lasinen</span>
          {sub && <span className="logo__sub">Ikkunanpesu · Oulu</span>}
        </span>
      </div>
    );
  }
  /* nav / default: full horizontal logo image */
  return (
    <img src="app/logo-cropped.png" alt="Lasinen — Ikkunanpesu" style={{height:44,width:"auto",display:"block"}}/>
  );
}

function Placeholder({ label, h = 320, brand, style, className = "" }) {
  return (
    <div className={`ph ${brand ? "ph--brand" : ""} ${className}`} style={{ height: h, ...style }}>
      <span className="ph__tag">{label}</span>
    </div>
  );
}

/* count-up number that animates from 0 → value when scrolled into view */
function CountUp({ value, decimals = 0, prefix = "", suffix = "", duration = 1400 }) {
  const ref = useRef(null);
  const [disp, setDisp] = useState(0);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) { setDisp(value); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const t0 = performance.now();
          let timer;
          const step = () => {
            const p = Math.min(1, (performance.now() - t0) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setDisp(value * eased);
            if (p < 1) timer = setTimeout(step, 32); else setDisp(value);
          };
          step();
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [value, duration]);
  const fmt = (n) => n.toLocaleString("fi-FI", { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  return <span ref={ref}>{prefix}{fmt(disp)}{suffix}</span>;
}

/* ---------------- NAV ---------------- */
function Nav({ route, go }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll); onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  // lock body scroll + close on Esc while the mobile menu is open
  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = prev; window.removeEventListener("keydown", onKey); };
  }, [open]);
  const links = [
    ["etusivu", "Etusivu"],
    ["ikkunanpesu", "Ikkunanpesu"],
    ["hintalaskuri", "Hintalaskuri"],
    ["meista", "Meistä"],
    ["yhteystiedot", "Yhteystiedot"],
  ];
  const nav = (id) => { setOpen(false); go(id); };
  return (
    <header className={`nav ${scrolled ? "scrolled" : ""} ${open ? "nav--open" : ""}`}>
      <div className="wrap nav__inner">
        <a href="#/" onClick={(e)=>{e.preventDefault();nav("etusivu");}}><Logo /></a>
        <nav className="nav__links">
          {links.map(([id, label]) => (
            <a key={id+"-"+(route===id)} href={"#/"+id} onClick={(e)=>{e.preventDefault();go(id);}}
               className={`nav__link ${route===id ? "is-current" : ""}`}>
               {id==="etusivu" && <Ic.home style={{marginRight:6, verticalAlign:"-2px"}}/>}{label}</a>
          ))}
        </nav>
        <div className="nav__cta">
          <button className="btn btn--primary nav__ctaBtn" onClick={()=>go("hintalaskuri")}>Laske hinta</button>
          <button className={`nav__burger ${open ? "is-open" : ""}`} aria-label={open ? "Sulje valikko" : "Avaa valikko"}
            aria-expanded={open} onClick={()=>setOpen(o=>!o)}>
            <span/><span/><span/>
          </button>
        </div>
      </div>

      {/* mobile menu */}
      <div className={`navm ${open ? "navm--open" : ""}`} aria-hidden={!open}>
        <button className="navm__scrim" aria-label="Sulje valikko" tabIndex={open?0:-1} onClick={()=>setOpen(false)}/>
        <div className="navm__panel">
          <nav className="navm__links">
            {links.map(([id, label]) => (
              <a key={id} href={"#/"+id} tabIndex={open?0:-1}
                 onClick={(e)=>{e.preventDefault();nav(id);}}
                 className={`navm__link ${route===id ? "is-current" : ""}`}>
                {id==="etusivu" && <Ic.home style={{flex:"none"}}/>}
                <span>{label}</span>
                {route===id && <Ic.check style={{marginLeft:"auto",width:18,height:18}}/>}
              </a>
            ))}
          </nav>
          <div className="navm__foot">
            <button className="btn btn--primary btn--block btn--lg" tabIndex={open?0:-1} onClick={()=>nav("hintalaskuri")}>
              <Ic.euro style={{width:19,height:19}}/> Laske hinta
            </button>
            <a href="#/yhteystiedot" className="btn btn--ghost btn--block" tabIndex={open?0:-1} onClick={(e)=>{e.preventDefault();nav("yhteystiedot");}}>Yhteystiedot</a>
          </div>
        </div>
      </div>
    </header>
  );
}

/* ---------------- FOOTER ---------------- */
function Footer({ go }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer__grid">
          <div>
            <Logo light />
            <p style={{ marginTop: 18, fontSize: 14.5, maxWidth: 280, color: "#a9b8cc" }}>
              Ammattimaista ikkunanpesua Oulun alueella. Kirkkaat näkymät, reilut hinnat ja kotitalousvähennys — kahden nuoren yrittäjän voimin.
            </p>
            <div className="soc" style={{ marginTop: 22 }}>
              <a href="#" aria-label="Facebook"><Ic.fb/></a>
              <a href="#" aria-label="Instagram"><Ic.ig/></a>
            </div>
          </div>
          <div>
            <h4>Sivut</h4>
            <div className="footer__list">
              <a href="#/" onClick={(e)=>{e.preventDefault();go("etusivu");}}>Etusivu</a>
              <a href="#/ikkunanpesu" onClick={(e)=>{e.preventDefault();go("ikkunanpesu");}}>Ikkunanpesu</a>
              <a href="#/hintalaskuri" onClick={(e)=>{e.preventDefault();go("hintalaskuri");}}>Hintalaskuri</a>
              <a href="#/meista" onClick={(e)=>{e.preventDefault();go("meista");}}>Meistä</a>
              <a href="#/yhteystiedot" onClick={(e)=>{e.preventDefault();go("yhteystiedot");}}>Yhteystiedot</a>
            </div>
          </div>
          <div>
            <h4>Yhteystiedot</h4>
            <div className="footer__list">
              <span style={{display:"flex",gap:10}}><Ic.pin style={{flex:"none",marginTop:2}}/> {D.area}</span>
              <span style={{ color:"#8da0b8" }}>Y-tunnukset: {D.people.map(p=>p.ytunnus).join(" · ")}</span>
            </div>
          </div>
          <div>
            <h4>Yrittäjät</h4>
            <div className="footer__list">
              {D.people.map((p)=>(
                <div key={p.email} style={{display:"flex",flexDirection:"column",gap:2}}>
                  <b style={{color:"#fff",fontFamily:"var(--head)",fontWeight:700,fontSize:14.5}}>{p.name}</b>
                  <span style={{color:"#a9b8cc"}}>Yrittäjä · Oulun alue</span>
                </div>
              ))}
              <button className="btn btn--white" style={{marginTop:8, alignSelf:"start"}} onClick={()=>go("hintalaskuri")}>Laske hinta <Ic.arrow/></button>
            </div>
          </div>
        </div>
        <div className="footer__bottom">
          <span>© 2026 Lasinen · Oulu</span>
          <span>Tietosuoja · Käyttöehdot</span>
          <a href="/liidit.html" style={{fontSize:12,color:"#7a9abb",border:"1px solid #2a3f55",borderRadius:6,padding:"3px 10px",letterSpacing:".04em"}}>admin</a>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Ic, Logo, Placeholder, CountUp, Nav, Footer });
