// ui.jsx — shared atoms + Header + Footer
(function () {
  const { useState, useEffect, useRef } = React;
  const Icon = window.Icon;
  const D = window.DATA;

  /* ---------- Logo ---------- */
  function Logo({ light, size = 40, onClick }) {
    const logoUrl = (window.INFOTECH && window.INFOTECH.logo) || "";
    const mark = logoUrl ? (
      <span style={{ width: size, height: size, borderRadius: 13, flex: "0 0 auto", overflow: "hidden",
        background: "#fff", display: "grid", placeItems: "center", boxShadow: "0 6px 16px rgba(10,63,90,.18)" }}>
        <img src={logoUrl} alt="INFOTECH logo" style={{ width: "100%", height: "100%", objectFit: "contain" }} />
      </span>
    ) : (
      <span style={{
        width: size, height: size, borderRadius: 13, flex: "0 0 auto",
        background: "linear-gradient(135deg, var(--accent) 0%, var(--accent-600) 100%)",
        display: "grid", placeItems: "center", boxShadow: "0 6px 16px rgba(248,181,24,.4)",
        position: "relative",
      }}>
        <svg width={size * .56} height={size * .56} viewBox="0 0 24 24" fill="none" stroke="#0a3f5a" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
          <path d="M5 6.5A1.5 1.5 0 0 1 6.5 5h11A1.5 1.5 0 0 1 19 6.5V15H5z" />
          <path d="M3 18h18l-1 2H4z" />
        </svg>
      </span>
    );
    return (
      <a href="#home" onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 12 }} aria-label="INFOTECH home">
        {mark}
        <span style={{ display: "grid", lineHeight: 1 }}>
          <span style={{ fontWeight: 800, fontSize: 19, letterSpacing: "-.02em", color: light ? "#fff" : "var(--brand)" }}>
            INFO<span style={{ color: "var(--accent)" }}>TECH</span>
          </span>
          <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: ".16em", textTransform: "uppercase", color: light ? "rgba(255,255,255,.6)" : "var(--ink-3)", marginTop: 3 }}>
            Institute of Computer Education
          </span>
        </span>
      </a>
    );
  }

  /* ---------- Placeholder image ---------- */
  function Placeholder({ label, icon = "image", style, className, ratio }) {
    const r = ratio ? { aspectRatio: ratio } : null;
    return (
      <div className={"ph " + (className || "")} style={{ ...r, ...style }}>
        <div className="ph-inner">
          <Icon name={icon} />
          {label && <span className="ph-label">{label}</span>}
        </div>
      </div>
    );
  }

  /* ---------- Stars ---------- */
  function Stars({ n = 5, size = 16 }) {
    return (
      <span style={{ display: "inline-flex", gap: 2, color: "var(--accent)" }}>
        {[1, 2, 3, 4, 5].map((i) => (
          <Icon key={i} name="star" size={size} fill={i <= n} style={{ color: i <= n ? "var(--accent)" : "var(--line)" }} />
        ))}
      </span>
    );
  }

  /* ---------- Scroll reveal ---------- */
  function useReveal() {
    const ref = useRef(null);
    useEffect(() => {
      const el = ref.current;
      if (!el) return;
      const io = new IntersectionObserver((entries) => {
        entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in-view"); io.unobserve(e.target); } });
      }, { threshold: 0.12 });
      io.observe(el);
      return () => io.disconnect();
    }, []);
    return ref;
  }

  /* ---------- Count-up ---------- */
  function CountUp({ value }) {
    const ref = useRef(null);
    const [shown, setShown] = useState(false);
    useEffect(() => {
      const el = ref.current; if (!el) return;
      const io = new IntersectionObserver((e) => { if (e[0].isIntersecting) { setShown(true); io.disconnect(); } }, { threshold: .4 });
      io.observe(el); return () => io.disconnect();
    }, []);
    const m = String(value).match(/^([\d,]+)(.*)$/);
    const [disp, setDisp] = useState(m ? "0" + (m[2] || "") : value);
    useEffect(() => {
      if (!shown || !m) { if (!m) setDisp(value); return; }
      const target = parseInt(m[1].replace(/,/g, ""), 10); const suffix = m[2] || "";
      let raf; const start = performance.now(); const dur = 1300;
      const tick = (now) => {
        const p = Math.min(1, (now - start) / dur); const e = 1 - Math.pow(1 - p, 3);
        const cur = Math.round(target * e);
        setDisp(cur.toLocaleString() + suffix);
        if (p < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf);
    }, [shown]);
    return <span ref={ref}>{disp}</span>;
  }

  /* ---------- Header ---------- */
  function Header({ route, navigate }) {
    const [scrolled, setScrolled] = useState(false);
    const [open, setOpen] = useState(false);
    useEffect(() => {
      const onScroll = () => setScrolled(window.scrollY > 12);
      onScroll(); window.addEventListener("scroll", onScroll, { passive: true });
      return () => window.removeEventListener("scroll", onScroll);
    }, []);
    useEffect(() => { setOpen(false); }, [route]);
    useEffect(() => { document.body.style.overflow = open ? "hidden" : ""; }, [open]);

    const go = (e, key) => { e.preventDefault(); navigate(key); };
    const active = (k) => route === k || (k === "courses" && route === "course");

    return (
      <header style={{
        position: "sticky", top: 0, zIndex: 100, transition: "all .25s ease",
        background: scrolled ? "rgba(255,255,255,.88)" : "rgba(255,255,255,.0)",
        backdropFilter: scrolled ? "saturate(180%) blur(14px)" : "none",
        WebkitBackdropFilter: scrolled ? "saturate(180%) blur(14px)" : "none",
        borderBottom: scrolled ? "1px solid var(--line-2)" : "1px solid transparent",
        boxShadow: scrolled ? "0 4px 24px rgba(10,63,90,.06)" : "none",
      }}>
        <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 76, gap: 20 }}>
          <Logo onClick={(e) => go(e, "home")} />

          <nav className="desk-nav" style={{ display: "flex", alignItems: "center", gap: 4 }}>
            {D.NAV.filter(n => n.key !== "verify").map((n) => (
              <a key={n.key} href={"#" + n.key} onClick={(e) => go(e, n.key)} className="nav-link"
                 style={{
                   padding: "9px 14px", borderRadius: 999, fontWeight: 600, fontSize: ".94rem",
                   color: active(n.key) ? "var(--brand)" : "var(--ink-2)",
                   background: active(n.key) ? "rgba(10,63,90,.07)" : "transparent",
                   transition: "all .15s ease", whiteSpace: "nowrap",
                 }}>
                {n.label}
              </a>
            ))}
          </nav>

          <div className="desk-nav" style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <a href="#login" onClick={(e) => go(e, "login")} className="btn btn-outline btn-sm">
              <Icon name="user" size={16} /> Login
            </a>
            <a href="#verify" onClick={(e) => go(e, "verify")} className="btn btn-accent btn-sm">
              <Icon name="shield" size={16} /> Verify
            </a>
          </div>

          <button className="burger" onClick={() => setOpen(!open)} aria-label="Menu"
            style={{ display: "none", background: "var(--surface)", border: "1px solid var(--line)", width: 46, height: 46, borderRadius: 13, placeItems: "center", color: "var(--brand)" }}>
            <Icon name={open ? "close" : "menu"} size={22} />
          </button>
        </div>

        {/* mobile drawer */}
        <div className="mobile-drawer" style={{
          position: "fixed", inset: "76px 0 0 0", zIndex: 99,
          background: "var(--cream)", padding: 24,
          transform: open ? "translateX(0)" : "translateX(100%)",
          transition: "transform .3s cubic-bezier(.2,.7,.2,1)", display: "none",
          flexDirection: "column", gap: 6, overflowY: "auto",
        }}>
          {D.NAV.map((n) => (
            <a key={n.key} href={"#" + n.key} onClick={(e) => go(e, n.key)}
               style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
                 padding: "16px 18px", borderRadius: 16, fontWeight: 700, fontSize: "1.05rem",
                 background: active(n.key) ? "var(--surface)" : "transparent",
                 color: active(n.key) ? "var(--brand)" : "var(--ink)",
                 boxShadow: active(n.key) ? "var(--sh-sm)" : "none" }}>
              {n.label} <Icon name="chevronRight" size={18} style={{ color: "var(--ink-3)" }} />
            </a>
          ))}
          <div style={{ display: "flex", gap: 10, marginTop: 14 }}>
            <a href="#login" onClick={(e) => go(e, "login")} className="btn btn-outline" style={{ flex: 1 }}>
              <Icon name="user" size={18} /> Student Login
            </a>
          </div>
          <a href={"tel:" + D.INSTITUTE.phoneHref} className="btn btn-brand" style={{ marginTop: 4 }}>
            <Icon name="phone" size={18} /> {D.INSTITUTE.phone}
          </a>
        </div>
      </header>
    );
  }

  /* ---------- Footer ---------- */
  function Footer({ navigate }) {
    const I = D.INSTITUTE;
    const go = (e, k) => { e.preventDefault(); navigate(k); };
    const socials = [["facebook", I.facebook || "#"], ["instagram", I.instagram || "#"], ["linkedin", I.linkedin || "#"], ["youtube", I.youtube || "#"]];
    const quick = [["about", "About Us"], ["courses", "Courses"], ["gallery", "Gallery"], ["testimonials", "Testimonials"], ["verify", "Verify Certificate"], ["contact", "Contact"]];
    const topCourses = D.COURSES.filter(c => c.featured).concat(D.COURSES.filter(c => !c.featured)).slice(0, 6);
    return (
      <footer style={{ background: "var(--brand-ink)", color: "rgba(255,255,255,.72)", paddingTop: 72 }}>
        <div className="wrap">
          <div className="footer-grid" style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 1fr 1.3fr", gap: 48, paddingBottom: 56 }}>
            <div>
              <Logo light onClick={(e) => go(e, "home")} />
              <p style={{ marginTop: 20, fontSize: ".96rem", maxWidth: 320 }}>{I.tagline}. Professional, affordable computer education in the heart of Lalamusa.</p>
              <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
                {socials.map(([s, h]) => (
                  <a key={s} href={h} aria-label={s} style={{
                    width: 42, height: 42, borderRadius: 12, display: "grid", placeItems: "center",
                    background: "rgba(255,255,255,.08)", color: "#fff", transition: "all .15s ease",
                  }} onMouseEnter={(e) => { e.currentTarget.style.background = "var(--accent)"; e.currentTarget.style.color = "var(--brand-ink)"; }}
                     onMouseLeave={(e) => { e.currentTarget.style.background = "rgba(255,255,255,.08)"; e.currentTarget.style.color = "#fff"; }}>
                    <Icon name={s} size={19} />
                  </a>
                ))}
              </div>
            </div>

            <div>
              <h4 style={{ color: "#fff", fontSize: "1.02rem", marginBottom: 18 }}>Quick Links</h4>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 12 }}>
                {quick.map(([k, l]) => (
                  <li key={k}><a href={"#" + k} onClick={(e) => go(e, k)} className="foot-link" style={{ fontSize: ".95rem" }}>{l}</a></li>
                ))}
              </ul>
            </div>

            <div>
              <h4 style={{ color: "#fff", fontSize: "1.02rem", marginBottom: 18 }}>Courses</h4>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 12 }}>
                {topCourses.map((c) => (
                  <li key={c.slug}><a href={"#course/" + c.slug} onClick={(e) => { e.preventDefault(); navigate("course", c.slug); }} className="foot-link" style={{ fontSize: ".95rem" }}>{c.title}</a></li>
                ))}
              </ul>
            </div>

            <div>
              <h4 style={{ color: "#fff", fontSize: "1.02rem", marginBottom: 18 }}>Get in Touch</h4>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 16 }}>
                <li style={{ display: "flex", gap: 12 }}><Icon name="pin" size={19} style={{ color: "var(--accent)", flex: "0 0 auto", marginTop: 2 }} /><span style={{ fontSize: ".92rem" }}>{I.address}</span></li>
                <li style={{ display: "flex", gap: 12, alignItems: "center" }}><Icon name="phone" size={19} style={{ color: "var(--accent)", flex: "0 0 auto" }} /><a href={"tel:" + I.phoneHref} className="foot-link" style={{ fontSize: ".95rem" }}>{I.phone}</a></li>
                <li style={{ display: "flex", gap: 12, alignItems: "center" }}><Icon name="mail" size={19} style={{ color: "var(--accent)", flex: "0 0 auto" }} /><a href={"mailto:" + I.email} className="foot-link" style={{ fontSize: ".95rem" }}>{I.email}</a></li>
                <li style={{ display: "flex", gap: 12, alignItems: "center" }}><Icon name="clock" size={19} style={{ color: "var(--accent)", flex: "0 0 auto" }} /><span style={{ fontSize: ".92rem" }}>{I.hours}</span></li>
              </ul>
            </div>
          </div>

          <div style={{ borderTop: "1px solid rgba(255,255,255,.12)", padding: "24px 0 30px", display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 12, fontSize: ".86rem" }}>
            <span>© {new Date().getFullYear()} {I.full}. All rights reserved.</span>
            <span style={{ display: "flex", gap: 22 }}>
              <a href="#" className="foot-link">Privacy Policy</a>
              <a href="#" className="foot-link">Terms of Use</a>
            </span>
          </div>
        </div>
      </footer>
    );
  }

  /* ---------- WhatsApp float ---------- */
  function FloatActions() {
    return (
      <a href={"https://wa.me/" + D.INSTITUTE.phoneHref.replace("+", "")} target="_blank" rel="noreferrer"
        style={{ position: "fixed", right: 22, bottom: 22, zIndex: 80, width: 58, height: 58, borderRadius: "50%",
          background: "#25D366", color: "#fff", display: "grid", placeItems: "center",
          boxShadow: "0 10px 28px rgba(37,211,102,.5)" }} aria-label="WhatsApp">
        <Icon name="whatsapp" size={30} fill={true} />
      </a>
    );
  }

  Object.assign(window, { Logo, Placeholder, Stars, useReveal, CountUp, Header, Footer, FloatActions });
})();
