/* ============================================
   Shared components for Radlinger website
   ============================================ */

const { useState, useEffect, useRef } = React;

// ---------- NAV ----------
function Nav({ active = "home" }) {
  const [open, setOpen] = useState(false);
  const links = [
    { id: "home", label: "Start", href: "index.html" },
    { id: "leistungen", label: "Leistungen", href: "leistungen.html" },
    { id: "referenzen", label: "Referenzen", href: "referenzen.html" },
    { id: "ueber", label: "Über uns", href: "ueber-uns.html" },
    { id: "kontakt", label: "Kontakt", href: "kontakt.html" },
  ];
  return (
    <nav className="nav">
      <div className="container nav-inner">
        <a href="index.html" className="brand">
          <img src="logo.png" alt="Radlinger Maler- und Lackierermeister" style={{ height: 40, width: "auto" }} />
        </a>
        <div className="nav-links">
          {links.map(l => (
            <a key={l.id} href={l.href} className={active === l.id ? "active" : ""}>{l.label}</a>
          ))}
        </div>
        <a href="kontakt.html" className="nav-cta">Anfrage stellen</a>
        <button className="nav-burger" aria-label="Menü" onClick={() => setOpen(!open)}>
          <span></span><span></span><span></span>
        </button>
      </div>
      {open && (
        <div style={{ borderTop: "1px solid var(--line)", padding: "16px var(--pad)", display: "grid", gap: 12, background: "var(--bg)" }}>
          {links.map(l => (
            <a key={l.id} href={l.href} style={{ fontSize: 16, fontWeight: 500, padding: "8px 0" }}>{l.label}</a>
          ))}
        </div>
      )}
    </nav>
  );
}

// ---------- FOOTER ----------
function Footer() {
  return (
    <>
      <footer className="footer">
        <div className="container">
          <div className="foot-grid">
            <div>
              <div className="foot-brand">
                Radlinger
                <small>Malermeister · Fürstenzell</small>
              </div>
              <p style={{ maxWidth: 320, opacity: .75, fontSize: 14, lineHeight: 1.6 }}>
                Handwerkliche Malerarbeiten für Wohnräume, Fassaden und Lackierungen — in Fürstenzell und Umgebung.
              </p>
            </div>
            <div>
              <h4>Kontakt</h4>
              <ul>
                <li>Griesbacher Straße 21</li>
                <li>94081 Fürstenzell</li>
                <li style={{ marginTop: 12 }}><a href="tel:+4915167612488">01516 7612488</a></li>
                <li><a href="mailto:info@malermeister-radlinger.de">info@malermeister-radlinger.de</a></li>
              </ul>
            </div>
            <div>
              <h4>Navigation</h4>
              <ul>
                <li><a href="index.html">Start</a></li>
                <li><a href="leistungen.html">Leistungen</a></li>
                <li><a href="referenzen.html">Referenzen</a></li>
                <li><a href="ueber-uns.html">Über uns</a></li>
                <li><a href="kontakt.html">Kontakt</a></li>
                <li><a href="impressum.html">Impressum</a></li>
                <li><a href="datenschutz.html">Datenschutz</a></li>
              </ul>
            </div>
            <div>
              <h4>Öffnungszeiten</h4>
              <ul>
                <li>Mo – Fr · 7.30 – 17.00</li>
                <li>Sa · nach Vereinbarung</li>
                <li>So · geschlossen</li>
              </ul>
            </div>
          </div>
          <div className="foot-bottom">
            <span>© 2026 Malermeister Radlinger</span>
            <span>
              <a href="impressum.html" style={{ marginRight: '0.75rem' }}>Impressum</a>
              <a href="datenschutz.html">Datenschutz</a>
            </span>
          </div>
        </div>
      </footer>
      <div style={{
        position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 9999,
        background: '#1a1a2e', borderTop: '3px solid #e63946',
        padding: '0.75rem 1.5rem',
      }}>
        <div style={{ maxWidth: 1100, margin: '0 auto', display: 'flex', alignItems: 'center', gap: '1.25rem', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', flex: 1, minWidth: 0 }}>
            <span style={{ background: '#e63946', color: 'white', fontSize: '0.65rem', fontWeight: 800, letterSpacing: '0.12em', padding: '0.2rem 0.6rem', borderRadius: 4, flexShrink: 0 }}>DEMO</span>
            <span style={{ fontSize: '0.82rem', color: 'rgba(255,255,255,0.8)', lineHeight: 1.4 }}>
              <strong style={{ color: '#fff' }}>Demo-Website</strong> · Wird am <strong style={{ color: '#fff' }}>27.05.2026</strong> automatisch deaktiviert.
            </span>
          </div>
          <a href={`mailto:florianpilslservice@gmail.com`} style={{
            flexShrink: 0, background: '#e63946', color: 'white',
            padding: '0.45rem 1rem', borderRadius: 6, fontSize: '0.8rem',
            fontWeight: 700, textDecoration: 'none',
          }}>Jetzt kaufen →</a>
        </div>
      </div>
    </>
  );
}

// ---------- REVEAL ON SCROLL ----------
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ---------- IMAGE with fallback ----------
function ImgWithLabel({ src, label, ratio = "4/3", style, className }) {
  const [err, setErr] = useState(false);
  return (
    <div className={`img-ph ${className || ""}`} data-label={label} style={{ aspectRatio: ratio, ...(style || {}) }}>
      {!err && src && (
        <img
          src={src}
          alt={label}
          onError={() => setErr(true)}
          style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
          loading="lazy"
        />
      )}
    </div>
  );
}

// ---------- LIGHTBOX ----------
function Lightbox({ items, openIdx, onClose }) {
  const [idx, setIdx] = useState(openIdx ?? 0);
  useEffect(() => { setIdx(openIdx ?? 0); }, [openIdx]);
  useEffect(() => {
    if (openIdx == null) return;
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowRight") setIdx(i => (i + 1) % items.length);
      if (e.key === "ArrowLeft") setIdx(i => (i - 1 + items.length) % items.length);
    };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [openIdx, items.length, onClose]);

  if (openIdx == null) return null;
  const item = items[idx];
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, background: "rgba(20,16,10,0.92)", zIndex: 100,
      display: "grid", placeItems: "center", padding: 32, animation: "fadeIn .25s ease"
    }}>
      <button onClick={onClose} aria-label="Schließen" style={{
        position: "absolute", top: 24, right: 24, width: 44, height: 44,
        borderRadius: "50%", border: "1px solid rgba(255,255,255,0.3)", color: "#fff", fontSize: 18
      }}>✕</button>
      <button onClick={(e) => { e.stopPropagation(); setIdx(i => (i - 1 + items.length) % items.length); }}
        style={{ position: "absolute", left: 24, top: "50%", transform: "translateY(-50%)", width: 56, height: 56, borderRadius: "50%", border: "1px solid rgba(255,255,255,0.3)", color: "#fff", fontSize: 22 }}>‹</button>
      <button onClick={(e) => { e.stopPropagation(); setIdx(i => (i + 1) % items.length); }}
        style={{ position: "absolute", right: 24, top: "50%", transform: "translateY(-50%)", width: 56, height: 56, borderRadius: "50%", border: "1px solid rgba(255,255,255,0.3)", color: "#fff", fontSize: 22 }}>›</button>
      <div onClick={(e) => e.stopPropagation()} style={{ maxWidth: "min(1100px, 90vw)", maxHeight: "85vh", display: "grid", gap: 16 }}>
        <img src={item.src} alt={item.label} style={{ maxWidth: "100%", maxHeight: "75vh", objectFit: "contain", display: "block", margin: "0 auto" }} />
        <div style={{ color: "#f5f1ea", textAlign: "center" }}>
          <div style={{ fontFamily: "var(--serif)", fontSize: 24, fontStyle: "italic" }}>{item.label}</div>
          {item.caption && <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".15em", textTransform: "uppercase", opacity: .6, marginTop: 6 }}>{item.caption}</div>}
          <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".15em", opacity: .4, marginTop: 12 }}>
            {String(idx + 1).padStart(2, "0")} / {String(items.length).padStart(2, "0")}
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- SECTION HEAD ----------
function SectionHead({ num, eyebrow, title, lede, children }) {
  return (
    <div className="section-head reveal">
      <div className="num">{num}</div>
      <div className="title-block">
        {eyebrow && <div className="h-eyebrow">{eyebrow}</div>}
        <h2 className="h-section" dangerouslySetInnerHTML={{ __html: title }}></h2>
        {lede && <p className="lede">{lede}</p>}
        {children}
      </div>
    </div>
  );
}

// Expose globals
Object.assign(window, { Nav, Footer, useReveal, ImgWithLabel, Lightbox, SectionHead });
