/* global React */
// ============================================
// A_LIZ HAIRDRESSER — Layout components
// ============================================

const { useState, useEffect, useRef, useCallback } = React;
const { LANGS, pick } = window.AL_DATA;

const WHATSAPP_NUMBER = "905388745166";
const WA_LINK = `https://wa.me/${WHATSAPP_NUMBER}`;
const WA_LINK_INNER = `https://wa.me/${WHATSAPP_NUMBER}`;
// ========== LANGUAGE CONTEXT ==========
const LangContext = React.createContext({ lang: "tr", setLang: () => {} });

function LangProvider({ children }) {
  const [lang, setLangState] = useState(() => {
    return localStorage.getItem("aliz_lang") || "tr";
  });
  const setLang = useCallback((l) => {
    setLangState(l);
    localStorage.setItem("aliz_lang", l);
    const langDef = LANGS.find((x) => x.code === l);
    document.documentElement.lang = l;
    document.documentElement.dir = langDef && langDef.rtl ? "rtl" : "ltr";
  }, []);
  useEffect(() => {
    const langDef = LANGS.find((x) => x.code === lang);
    document.documentElement.lang = lang;
    document.documentElement.dir = langDef && langDef.rtl ? "rtl" : "ltr";
  }, [lang]);
  return <LangContext.Provider value={{ lang, setLang }}>{children}</LangContext.Provider>;
}

const useLang = () => React.useContext(LangContext);
const useT = () => {
  const { lang } = useLang();
  return useCallback((key) => pick(key, lang), [lang]);
};

// ========== BRAND LOCKUP (crisp typographic logo) ==========
function BrandLock({ variant = "dark" }) {
  return (
    <span className={`brandlock brandlock-${variant}`}>
      <span className="bl-al">AL</span>
      <span className="bl-divider"></span>
      <span className="brandword">
        <span className="bw-name">A<span className="bw-us">_</span>Liz</span>
        <span className="bw-sub">Hairdresser · İstanbul</span>
      </span>
    </span>
  );
}

// Flag swatch (renders the SVG flag from LANGS)
function Flag({ lang: code, size = 18 }) {
  const def = LANGS.find((l) => l.code === code);
  if (!def || !def.flag) return null;
  return (
    <span
      className="flag"
      style={{ width: size + "px", height: Math.round(size * 0.66) + "px" }}
      dangerouslySetInnerHTML={{ __html: def.flag }}
    />
  );
}

// ========== ROUTER (History API — clean URLs) ==========
const VALID_ROUTES = ['home','services','gallery','about','contact','appointment','privacy','terms','cookies'];
const RouteContext = React.createContext({ route: "home", go: () => {} });

function RouteProvider({ children }) {
  const getRoute = () => {
    const path = window.location.pathname.replace(/^\//, '').replace(/\/$/, '');
    const r = path || 'home';
    return VALID_ROUTES.includes(r) ? r : 'home';
  };
  const [route, setRoute] = useState(getRoute);
  useEffect(() => {
    const handle = () => {
      setRoute(getRoute());
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("popstate", handle);
    return () => window.removeEventListener("popstate", handle);
  }, []);
  const go = useCallback((r) => {
    const path = r === 'home' ? '/' : '/' + r;
    window.history.pushState({}, '', path);
    setRoute(r);
    window.scrollTo({ top: 0, behavior: "instant" });
  }, []);
  window.AL_NAV = go;
  return <RouteContext.Provider value={{ route, go }}>{children}</RouteContext.Provider>;
}

const useRoute = () => React.useContext(RouteContext);

// ========== REVEAL HOOK ==========
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const el = ref.current;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -40px 0px" }
    );
    el.querySelectorAll(".reveal, .reveal-watch").forEach((n) => io.observe(n));
    return () => io.disconnect();
  }, []);
  return ref;
}

// ========== 3D TILT HOOK ==========
function useTilt(opts = {}) {
  const { max = 8, scale = 1.02, perspective = 1000 } = opts;
  const ref = useRef(null);
  // Skip tilt on touch/mobile for performance
  const isTouch = typeof window !== 'undefined' && ('ontouchstart' in window || window.matchMedia('(hover: none)').matches);
  if (isTouch) return ref;
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let rect;
    const onEnter = () => { rect = el.getBoundingClientRect(); };
    const onMove = (e) => {
      if (!rect) rect = el.getBoundingClientRect();
      const x = (e.clientX - rect.left) / rect.width - 0.5;
      const y = (e.clientY - rect.top) / rect.height - 0.5;
      el.style.transform = `perspective(${perspective}px) rotateX(${-y * max}deg) rotateY(${x * max}deg) scale(${scale})`;
      el.style.setProperty("--mx", `${(x + 0.5) * 100}%`);
      el.style.setProperty("--my", `${(y + 0.5) * 100}%`);
    };
    const onLeave = () => {
      el.style.transform = `perspective(${perspective}px) rotateX(0) rotateY(0) scale(1)`;
    };
    el.addEventListener("mouseenter", onEnter);
    el.addEventListener("mousemove", onMove);
    el.addEventListener("mouseleave", onLeave);
    return () => {
      el.removeEventListener("mouseenter", onEnter);
      el.removeEventListener("mousemove", onMove);
      el.removeEventListener("mouseleave", onLeave);
    };
  }, [max, scale, perspective]);
  return ref;
}

// ========== COUNT-UP HOOK ==========
function useCountUp(target, duration = 1600) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (!e.isIntersecting) return;
        io.unobserve(el);
        const start = performance.now();
        const tick = (now) => {
          const p = Math.min(1, (now - start) / duration);
          const eased = 1 - Math.pow(1 - p, 3);
          setVal(target * eased);
          if (p < 1) requestAnimationFrame(tick);
          else setVal(target);
        };
        requestAnimationFrame(tick);
      });
    }, { threshold: 0.1, rootMargin: '0px 0px -40px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, [target, duration]);
  return [val, ref];
}

// ========== ICONS ==========
const Icon = {
  Arrow: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <line x1="5" y1="12" x2="19" y2="12" />
      <polyline points="12 5 19 12 12 19" />
    </svg>
  ),
  Wa: () => (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <path d="M17.6 14.4c-.3-.1-1.8-.9-2-1-.3-.1-.5-.1-.7.2-.2.3-.8 1-1 1.2-.2.2-.4.3-.6.1-1.5-.7-2.5-1.3-3.5-3-.3-.5.3-.4.8-1.4.1-.2 0-.4 0-.6 0-.1-.7-1.7-.9-2.3-.3-.7-.5-.6-.7-.6h-.6c-.2 0-.5.1-.7.4-.3.3-1 .9-1 2.3 0 1.3 1 2.6 1.1 2.8.1.2 2 3.1 4.9 4.4.7.3 1.2.5 1.6.6.7.2 1.3.2 1.8.1.5-.1 1.8-.7 2-1.4.3-.7.3-1.2.2-1.4-.1-.1-.3-.2-.6-.3z" />
      <path d="M12 0C5.4 0 0 5.4 0 12c0 2.1.6 4.2 1.6 6L0 24l6.3-1.6c1.7.9 3.7 1.4 5.7 1.4 6.6 0 12-5.4 12-12S18.6 0 12 0zm0 21.8c-1.8 0-3.6-.5-5.1-1.4l-.4-.2-3.7 1 1-3.6-.2-.4c-1-1.6-1.5-3.4-1.5-5.2 0-5.4 4.5-9.9 9.9-9.9s9.9 4.4 9.9 9.9-4.5 9.8-9.9 9.8z" />
    </svg>
  ),
  Phone: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.9.72 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0122 16.92z" />
    </svg>
  ),
  Globe: () => (
    <svg className="globe" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <circle cx="12" cy="12" r="9" />
      <path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18" />
    </svg>
  ),
  Star: () => (
    <svg viewBox="0 0 24 24"><path d="M12 2l3.1 6.3 6.9 1-5 4.9 1.2 6.8L12 17.8 5.8 21l1.2-6.8-5-4.9 6.9-1z" /></svg>
  ),
  Instagram: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <rect x="2" y="2" width="20" height="20" rx="5" />
      <path d="M16 11.4A4 4 0 1112.6 8 4 4 0 0116 11.4z" />
      <line x1="17.5" y1="6.5" x2="17.5" y2="6.5" strokeWidth="2" />
    </svg>
  ),
  TikTok: () => (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <path d="M19.6 6.3a4.8 4.8 0 01-3-.9 4.7 4.7 0 01-1.7-2.6V2.5h-3.4v13.2a2.8 2.8 0 01-5.1 1.6 2.8 2.8 0 014-3.7v-3.5a6.3 6.3 0 105.9 6.4V9.3a8 8 0 003.3.7v-3.7z" />
    </svg>
  ),
  Facebook: () => (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <path d="M14 5.5a2 2 0 012-2h2v-3h-3a5 5 0 00-5 5v3H6v3.5h4V22h3.5V12h3l.5-3.5H13.5V6.5z" />
    </svg>
  ),
  YouTube: () => (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <path d="M22.5 6.5a3 3 0 00-2.1-2.1C18.5 4 12 4 12 4s-6.5 0-8.4.4A3 3 0 001.5 6.5C1.1 8.4 1.1 12 1.1 12s0 3.6.4 5.5a3 3 0 002.1 2.1C5.5 20 12 20 12 20s6.5 0 8.4-.4a3 3 0 002.1-2.1c.4-1.9.4-5.5.4-5.5s0-3.6-.4-5.5zM10 15.5v-7l5.5 3.5L10 15.5z" />
    </svg>
  ),
  Mail: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
      <polyline points="22,6 12,13 2,6" />
    </svg>
  ),
  Pin: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z" />
      <circle cx="12" cy="10" r="3" />
    </svg>
  ),
  Clock: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <circle cx="12" cy="12" r="10" />
      <polyline points="12,6 12,12 16,14" />
    </svg>
  ),
};

// ========== ANNOUNCEMENT BAR ==========
function Announcement() {
  const { lang } = useLang();
  const [visible, setVisible] = useState(true);
  const trackRef = useRef(null);
  const animRef = useRef(null);

  useEffect(() => {
    document.body.classList.toggle("has-announce", visible);
    return () => document.body.classList.remove("has-announce");
  }, [visible]);

  // rAF loop — CSS cascade'i tamamen atlar, inline style kullanır
  useEffect(() => {
    if (!visible || !trackRef.current) return;
    const el = trackRef.current;
    // Tüm mevcut animasyonları iptal et
    if (el.getAnimations) el.getAnimations().forEach(a => a.cancel());
    el.style.transform = '';

    let offset = 0;
    let lastTs = null;
    let paused = false;
    let raf;

    const step = (ts) => {
      if (lastTs !== null && !paused) {
        const dt = Math.min(ts - lastTs, 50); // max 50ms adım
        const total = el.scrollWidth / 2;
        if (total > 0) {
          offset -= (total / 30000) * dt;
          if (offset < -total) offset += total;
          el.style.cssText = `transform: translateX(${offset}px) !important;`;
        }
      }
      lastTs = ts;
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);

    const pause = () => { paused = true; };
    const play  = () => { paused = false; lastTs = null; };
    el.addEventListener('mouseenter', pause);
    el.addEventListener('mouseleave', play);

    return () => {
      cancelAnimationFrame(raf);
      el.removeEventListener('mouseenter', pause);
      el.removeEventListener('mouseleave', play);
      el.style.transform = '';
    };
  }, [visible]);

  if (!visible) return null;

  const items = {
    tr: [
      { pre: "✦ Özel Teklif", msg: "Ayak Masajı", tag: "sadece", price: "10 €" },
      { pre: "◆ Yaz Sezonu", msg: "Kampanya fiyatları için bizimle iletişime geçin", tag: "", price: "" },
    ],
    en: [
      { pre: "✦ Special Offer", msg: "Foot Massage", tag: "only", price: "10 €" },
      { pre: "◆ Summer Season", msg: "Contact us for campaign prices", tag: "", price: "" },
    ],
    de: [
      { pre: "✦ Sonderangebot", msg: "Fußmassage", tag: "nur", price: "10 €" },
      { pre: "◆ Sommersaison", msg: "Kontaktieren Sie uns für Aktionspreise", tag: "", price: "" },
    ],
    fr: [
      { pre: "✦ Offre Spéciale", msg: "Massage des Pieds", tag: "seulement", price: "10 €" },
      { pre: "◆ Saison Estivale", msg: "Contactez-nous pour les tarifs promotionnels", tag: "", price: "" },
    ],
    ar: [
      { pre: "✦ عرض خاص", msg: "مساج القدم", tag: "فقط", price: "10 €" },
      { pre: "◆ موسم الصيف", msg: "تواصل معنا للأسعار الترويجية", tag: "", price: "" },
    ],
    ru: [
      { pre: "✦ Спецпредложение", msg: "Массаж ног", tag: "всего", price: "10 €" },
      { pre: "◆ Летний сезон", msg: "Свяжитесь с нами для уточнения акционных цен", tag: "", price: "" },
    ],
    it: [
      { pre: "✦ Offerta Speciale", msg: "Massaggio ai Piedi", tag: "solo", price: "10 €" },
      { pre: "◆ Stagione Estiva", msg: "Contattateci per i prezzi promozionali", tag: "", price: "" },
    ],
    es: [
      { pre: "✦ Oferta Especial", msg: "Masaje de Pies", tag: "solo", price: "10 €" },
      { pre: "◆ Temporada Verano", msg: "Contáctenos para precios de campaña", tag: "", price: "" },
    ],
  };

  const list = items[lang] || items.tr;
  // Build one segment — repeated 4x for seamless loop
  const Segment = () => (
    <span className="ann-segment">
      {list.map((c, i) => (
        <span key={i} className="ann-item">
          <span className="announce-eyebrow">{c.pre}</span>
          <span className="announce-divider">·</span>
          <span className="announce-msg">{c.msg}</span>
          {c.price && (
            <span className="announce-price-wrap">
              {c.tag && <span className="announce-tag">{c.tag}</span>}
              <span className="announce-price">{c.price}</span>
            </span>
          )}
          <span className="ann-sep">✦</span>
        </span>
      ))}
    </span>
  );

  return (
    <div className="announce-bar">
      <div className="announce-marquee">
        <div className="announce-track" ref={trackRef}>
          <Segment /><Segment /><Segment /><Segment />
        </div>
      </div>
      <button className="announce-close" onClick={() => setVisible(false)} aria-label="Kapat">✕</button>
    </div>
  );
}

// ========== NAV ==========
function Nav() {
  const { route, go } = useRoute();
  const { lang, setLang } = useLang();
  const t = useT();
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [langOpen, setLangOpen] = useState(false);
  const langRef = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const onClick = (e) => {
      if (langRef.current && !langRef.current.contains(e.target)) setLangOpen(false);
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  const links = [
    ["home", "nav_home"],
    ["services", "nav_services"],
    ["gallery", "nav_gallery"],
    ["about", "nav_about"],
    ["appointment", "nav_appointment"],
    ["contact", "nav_contact"],
  ];

  const onNav = (key) => { setOpen(false); go(key); };
  const currentLang = LANGS.find((l) => l.code === lang) || LANGS[0];

  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`} data-screen-label="Nav">
      <div className="shell nav-inner">

        {/* LEFT: Logo only */}
        <a className="nav-logo" onClick={() => onNav("home")}>
          <img src="assets/logo-final.png" alt="A_LizHairdresser İstanbul" className="nav-logo-img" style={{ height: '108px' }} />
        </a>

        {/* CENTER: Desktop nav links */}
        <div className="nav-links-desktop">
          {links.map(([key, tk]) => (
            <a key={key} className={`nav-link ${route === key ? "active" : ""}`} onClick={() => onNav(key)}>
              {t(tk)}
            </a>
          ))}
        </div>

        {/* RIGHT: search + lang + tel (desktop) | lang + search + hamburger (mobile) */}
        <div className="nav-right-group">
          {/* Tel — left of lang */}
          <a className="nav-tel-btn" href="tel:+905388745166" aria-label={t("cta_call")}>
            <Icon.Phone />
          </a>

          {/* Lang — far right */}
          <div className="lang-switch" ref={langRef}>
            <button className="lang-trigger" onClick={(e) => { e.stopPropagation(); setLangOpen(!langOpen); }}>
              <Flag lang={currentLang.code} size={18} />
              <span>{currentLang.short}</span>
              <span className="chev" />
            </button>
            <div className={`lang-menu ${langOpen ? "open" : ""}`}>
              {LANGS.map((l) => (
                <button key={l.code} className={`lang-item ${l.code === lang ? "active" : ""}`}
                  onClick={() => { setLang(l.code); setLangOpen(false); }}>
                  <Flag lang={l.code} size={20} />
                  <span className="lang-name">{l.label}</span>
                  <span className="code">{l.short}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Hamburger (mobile only) */}
          <button className={`nav-toggle ${open ? "open" : ""}`} aria-label="menu" onClick={() => setOpen(!open)}>
            <span></span><span></span><span></span>
          </button>
        </div>

        {/* Mobile drawer */}
        <div className={`nav-drawer ${open ? "open" : ""}`}>
          {links.map(([key, tk]) => (
            <a key={key} className={`nav-link ${route === key ? "active" : ""}`} onClick={() => onNav(key)}>
              {t(tk)}
            </a>
          ))}
        </div>
      </div>
    </nav>
  );
}
// ========== WHATSAPP FAB ==========
function WhatsAppFab() {
  const t = useT();
  return (
    <a className="whatsapp-fab" href={WA_LINK} target="_blank" rel="noopener" aria-label="WhatsApp">
      <Icon.Wa />
      <span className="whatsapp-tooltip">{t("cta_book")} · WhatsApp</span>
    </a>
  );
}

// ========== FOOTER ==========
function Footer() {
  const t = useT();
  const { go } = useRoute();
  const year = new Date().getFullYear();
  return (
    <footer className="footer">
      <div className="shell">
        <div className="footer-grid">
          <div className="footer-col footer-brand">
            <img src="assets/logo-final.png" alt="A_LizHairdresser İstanbul" className="footer-logo-img" />
            <p className="lede">{t("hero_lede")}</p>
            <a className="ig-follow-btn" href="https://www.instagram.com/a_lizhairdresser" target="_blank" rel="noopener">
              <span className="ig-follow-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                  <rect x="2" y="2" width="20" height="20" rx="5.5" />
                  <path d="M16 11.4A4 4 0 1112.6 8 4 4 0 0116 11.4z" />
                  <circle cx="17.5" cy="6.5" r="1" fill="currentColor" />
                </svg>
              </span>
              <span className="ig-follow-text">
                <span className="ig-follow-handle">@a_lizhairdresser</span>
                <span className="ig-follow-cta">Instagram'da Takip Et</span>
              </span>
            </a>
          </div>
          <div className="footer-col">
            <h4>{t("ft_about")}</h4>
            <ul>
              <li><a onClick={() => go("about")}>{t("nav_about")}</a></li>
              <li><a onClick={() => go("services")}>{t("nav_services")}</a></li>
              <li><a onClick={() => go("gallery")}>{t("nav_gallery")}</a></li>
              <li><a onClick={() => go("contact")}>{t("nav_contact")}</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>{t("ft_social")}</h4>
            <ul>
              <li><a href="https://wa.me/905388745166" target="_blank" rel="noopener">WhatsApp</a></li>
              <li><a href="https://www.instagram.com/a_lizhairdresser" target="_blank" rel="noopener">Instagram</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>{t("ft_legal")}</h4>
            <ul>
              <li><a onClick={() => go("privacy")}>{t("ft_kvkk")}</a></li>
              <li><a onClick={() => go("terms")}>{t("ft_terms")}</a></li>
              <li><a onClick={() => go("cookies")}>{t("ft_cookies")}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© {year} A_LizHairdresser — {t("ft_rights")}</div>
          <div className="footer-credit">
            <span>İstanbul · Fatih · Divanyolu Cad. No.50</span>
            <span className="footer-sep">·</span>
            <span className="footer-design">Design by <a href="#" onClick={(e) => e.preventDefault()}>sz-13</a></span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ========== CTA STRIP ==========
function CtaStrip() {
  const t = useT();
  const { go } = useRoute();
  return (
    <section className="cta-strip">
      <div className="shell">
        <div className="eyebrow centered">{t("cta_eyebrow")}</div>
        <h2 className="display display-lg">{t("cta_title")}</h2>
        <p className="lede" style={{ color: "rgba(255,255,255,0.9)", margin: "0 auto 32px", maxWidth: "44ch" }}>{t("cta_lede")}</p>
        <a className="btn btn-primary" onClick={() => go('appointment')}>
          <span><Icon.Wa /> {t("cta_book")} · {t("cta_whatsapp")}</span>
        </a>
      </div>
    </section>
  );
}

// ========== SEO HOOK ==========
const SEO_DATA = {
  home:        { en: { title: 'A_Liz Hairdresser — Luxury Hair Salon in Sultanahmet, Istanbul', desc: 'Premium hair salon in the heart of Sultanahmet, Istanbul. Expert cuts, colour, balayage, keratin & bridal hair. Walk-in & WhatsApp booking. Open daily 10:00–24:00.' },
                 tr: { title: 'A_Liz Hairdresser — Sultanahmet\'in Lüks Kuaförü, İstanbul', desc: 'Sultanahmet\'in kalbinde premium kuaför salonu. Saç kesimi, renklendirme, balayage, keratin & gelin saçı. WhatsApp ile anında randevu. Her gün 10:00–24:00.' } },
  services:    { en: { title: 'Hair & Beauty Services | A_Liz Hairdresser Istanbul', desc: 'Explore 14 premium hair and beauty services at A_Liz Hairdresser Sultanahmet: cuts, colour, balayage, keratin, makeup, nail care, foot massage and more.' },
                 tr: { title: 'Hizmetlerimiz | A_Liz Hairdresser İstanbul', desc: 'A_Liz Hairdresser\'da 14 premium saç ve güzellik hizmeti: kesim, renklendirme, balayage, keratin, makyaj, tırnak bakımı, ayak masajı ve daha fazlası.' } },
  gallery:     { en: { title: 'Gallery | A_Liz Hairdresser Istanbul', desc: 'Browse our gallery of hair transformations at A_Liz Hairdresser, Sultanahmet, Istanbul. Before & after shots from our expert stylists.' },
                 tr: { title: 'Galeri | A_Liz Hairdresser İstanbul', desc: 'A_Liz Hairdresser\'ın saç dönüşüm galerisine göz atın. Uzman stilistlerimizden öncesi & sonrası çekimler.' } },
  about:       { en: { title: 'About Us | A_Liz Hairdresser Istanbul', desc: 'Learn about A_Liz Hairdresser — a luxury hair and beauty salon in Sultanahmet, Istanbul, serving guests in 8 languages with world-class brands.' },
                 tr: { title: 'Hakkımızda | A_Liz Hairdresser İstanbul', desc: 'A_Liz Hairdresser hakkında — Sultanahmet\'te 8 dilde hizmet veren, dünya markaları kullanan lüks kuaför ve güzellik salonu.' } },
  contact:     { en: { title: 'Contact & Location | A_Liz Hairdresser Istanbul', desc: 'Find A_Liz Hairdresser at Divanyolu Cad. No.50, Sultanahmet, Istanbul. Contact us via WhatsApp, phone or visit us. Open daily 10:00–24:00.' },
                 tr: { title: 'İletişim & Konum | A_Liz Hairdresser İstanbul', desc: 'A_Liz Hairdresser\'ı Divanyolu Cad. No.50, Sultanahmet, İstanbul\'da bulun. WhatsApp, telefon veya ziyaret ile iletişime geçin. Her gün 10:00–24:00.' } },
  appointment: { en: { title: 'Book an Appointment | A_Liz Hairdresser Istanbul', desc: 'Book your appointment at A_Liz Hairdresser Sultanahmet easily online. Choose your date, time and services. Confirmation via WhatsApp.' },
                 tr: { title: 'Randevu Al | A_Liz Hairdresser İstanbul', desc: 'A_Liz Hairdresser\'da randevunuzu kolayca alın. Tarih, saat ve hizmet seçin. WhatsApp ile onay.' } },
};

function usePageSEO(route) {
  const { lang } = useLang();
  useEffect(() => {
    const seo = SEO_DATA[route] || SEO_DATA.home;
    const d = seo[lang] || seo.en;
    document.title = d.title;
    const metaDesc = document.querySelector('meta[name="description"]');
    if (metaDesc) metaDesc.setAttribute('content', d.desc);
    const ogTitle = document.querySelector('meta[property="og:title"]');
    if (ogTitle) ogTitle.setAttribute('content', d.title);
    const ogDesc = document.querySelector('meta[property="og:description"]');
    if (ogDesc) ogDesc.setAttribute('content', d.desc);
    const ogUrl = document.querySelector('meta[property="og:url"]');
    if (ogUrl) ogUrl.setAttribute('content', 'https://www.alizhairdresser.com' + (route === 'home' ? '/' : '/' + route));
    const canonical = document.querySelector('link[rel="canonical"]');
    if (canonical) canonical.setAttribute('href', 'https://www.alizhairdresser.com' + (route === 'home' ? '/' : '/' + route));
    return () => {
      document.title = 'A_Liz Hairdresser — Sultanahmet · Istanbul';
    };
  }, [route, lang]);
}

Object.assign(window, { LangProvider, RouteProvider, useLang, useT, useRoute, useReveal, useTilt, useCountUp, Icon, Nav, WhatsAppFab, Footer, CtaStrip, WA_LINK, Announcement, usePageSEO });

// ========== LOADING CURTAIN ==========
function LoadingCurtain() {
  const [stage, setStage] = useState(0); // 0=initial, 1=logo-in, 2=lift, 3=gone
  useEffect(() => {
    if (sessionStorage.getItem("aliz_curtain_shown") === "1") {
      setStage(3);
      return;
    }
    const t1 = setTimeout(() => setStage(1), 80);
    const t2 = setTimeout(() => setStage(2), 1400);
    const t3 = setTimeout(() => {
      setStage(3);
      sessionStorage.setItem("aliz_curtain_shown", "1");
    }, 2200);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, []);
  if (stage === 3) return null;
  const curtainCls = stage === 0 ? 'curtain' : stage === 1 ? 'curtain logo-in' : 'curtain logo-in lift';
  return (
    <div className={curtainCls}>
      <div className="curtain-panel" />
      <div className="curtain-content">
        <img src="assets/logo-cream.png" alt="A_Liz" className="curtain-logo" />
        <div className="curtain-line" />
        <span className="curtain-city">DİVANYOLU · ISTANBUL</span>
      </div>
    </div>
  );
}

// ========== CUSTOM CURSOR ==========
function CustomCursor() {
  const dotRef = useRef(null);
  const ringRef = useRef(null);
  useEffect(() => {
    if (window.matchMedia("(pointer: coarse)").matches) return; // skip on touch
    const dot = dotRef.current;
    const ring = ringRef.current;
    let mx = 0, my = 0, rx = 0, ry = 0;
    const move = (e) => {
      mx = e.clientX; my = e.clientY;
      dot.style.transform = `translate(${mx}px, ${my}px)`;
    };
    let raf;
    const loop = () => {
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      ring.style.transform = `translate(${rx}px, ${ry}px)`;
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);

    const onOver = (e) => {
      const t = e.target;
      const link = t.closest("a, button, .service-card, .ig-tile, .ba-slider, .gal-item, .faq-trigger, [role=button]");
      if (link) {
        ring.classList.add("hover");
        if (link.closest(".btn-primary")) ring.classList.add("rose");
      } else {
        ring.classList.remove("hover");
        ring.classList.remove("rose");
      }
    };
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseover", onOver);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseover", onOver);
    };
  }, []);
  return (
    <>
      <div className="cursor-dot" ref={dotRef} />
      <div className="cursor-ring" ref={ringRef} />
    </>
  );
}

// ========== MAGNETIC BUTTON ==========
function useMagnetic(strength = 0.3) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const onMove = (e) => {
      const rect = el.getBoundingClientRect();
      const x = e.clientX - (rect.left + rect.width / 2);
      const y = e.clientY - (rect.top + rect.height / 2);
      el.style.transform = `translate(${x * strength}px, ${y * strength}px)`;
    };
    const onLeave = () => { el.style.transform = "translate(0,0)"; };
    el.addEventListener("mousemove", onMove);
    el.addEventListener("mouseleave", onLeave);
    return () => {
      el.removeEventListener("mousemove", onMove);
      el.removeEventListener("mouseleave", onLeave);
    };
  }, [strength]);
  return ref;
}

// ========== SPLIT-TEXT HEADING ==========
function SplitHeading({ text, className = "" }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.2 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  const words = String(text).split(" ");
  return (
    <h2 className={`split-heading display ${className}`} ref={ref}>
      {words.map((w, i) => (
        <span className="sh-word" key={i}>
          <span className="sh-inner" style={{ transitionDelay: `${i * 80}ms` }}>
            {w}{i < words.length - 1 ? "\u00A0" : ""}
          </span>
        </span>
      ))}
    </h2>
  );
}

// ========== BRAND WORDMARK LOGOS ==========
// Typographic recreations — each evokes the brand's distinct DNA in monochrome
function BrandLogo({ name }) {
  switch (name) {
    case "schwarzkopf":
      return (
        <span className="brand brand-sk">
          <svg viewBox="0 0 24 24" className="brand-glyph" aria-hidden="true">
            <path d="M12 1.5 L13.5 10.5 L22.5 12 L13.5 13.5 L12 22.5 L10.5 13.5 L1.5 12 L10.5 10.5 Z" fill="currentColor" />
          </svg>
          <span>Schwarzkopf</span>
        </span>
      );
    case "loreal":
      return (
        <span className="brand brand-loreal">
          <span className="loreal-main">L'ORÉAL</span>
          <span className="loreal-sub">PROFESSIONNEL · PARIS</span>
        </span>
      );
    case "olaplex":
      return <span className="brand brand-olaplex">OLAPLEX<sup>®</sup></span>;
    case "kerastase":
      return (
        <span className="brand brand-kerastase">
          <span className="kt-name">KÉRASTASE</span>
          <span className="kt-sub">PARIS</span>
        </span>
      );
    case "wella":
      return (
        <span className="brand brand-wella">
          <span>WELLA</span>
          <span className="wella-sub">PROFESSIONALS</span>
        </span>
      );
    case "rallis":
      return (
        <span className="brand brand-rallis">
          <em>Rallis</em>
          <span className="rallis-sub">Professional</span>
        </span>
      );

    // Press
    case "vogue":   return <span className="brand brand-vogue">VOGUE</span>;
    case "elle":    return <span className="brand brand-elle">ELLE</span>;
    case "marie":
      return (
        <span className="brand brand-marie">
          <span>MARIE CLAIRE</span>
        </span>
      );
    case "cosmo":
      return <span className="brand brand-cosmo"><em>Cosmopolitan</em><span className="cosmo-sub">TÜRKİYE</span></span>;
    case "timeout":
      return (
        <span className="brand brand-timeout">
          <span className="to-pill">Time Out</span>
          <span className="to-sub">ISTANBUL</span>
        </span>
      );
    case "harpers":
      return (
        <span className="brand brand-harpers">
          <span className="hb-name">HARPER'S BAZAAR</span>
          <span className="hb-sub">ARABIA</span>
        </span>
      );
    default:
      return <span>{name}</span>;
  }
}

// ========== OFFER POPUP (circular badge) ==========
function OfferPopup() {
  const t = useT();
  const { lang } = useLang();
  const [shown, setShown] = useState(false);
  const [collapsed, setCollapsed] = useState(false);
  const [closed, setClosed] = useState(() => sessionStorage.getItem("aliz_offer_closed") === "1");

  const messages = {
    tr: "Merhaba, sezon önerisi ayak masajı (€10) için randevu almak istiyorum.",
    en: "Hello, I'd like to book the seasonal foot massage (€10).",
    ar: "مرحباً، أود حجز جلسة تدليك القدمين الموسمية (€10).",
    ru: "Здравствуйте, хочу записаться на сезонный массаж стоп (€10).",
    it: "Ciao, vorrei prenotare il massaggio plantare stagionale (€10).",
    de: "Hallo, ich möchte die Saison-Fußmassage (€10) buchen.",
    fr: "Bonjour, je souhaite réserver le massage des pieds (€10).",
    es: "Hola, quisiera reservar el masaje de pies (€10).",
  };
  const titles = {
    tr: "Ayak Masajı", en: "Foot Massage", ar: "تدليك القدمين",
    ru: "Массаж стоп", it: "Massaggio Plantare", de: "Fußmassage",
    fr: "Massage des Pieds", es: "Masaje de Pies",
  };
  const offerLink = "https://wa.me/905388745166";

  // Show with delay + auto-collapse after 5s
  useEffect(() => {
    if (closed) return;
    const t1 = setTimeout(() => setShown(true), 3800);
    const t2 = setTimeout(() => setCollapsed(true), 9500); // 9.5s total = 5.7s after appearing
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [closed]);

  const close = (e) => {
    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }
    setShown(false);
    sessionStorage.setItem("aliz_offer_closed", "1");
    setTimeout(() => setClosed(true), 600);
  };

  const expand = (e) => {
    if (collapsed) {
      e.preventDefault();
      e.stopPropagation();
      setCollapsed(false);
      // re-collapse after 5s of full view
      setTimeout(() => setCollapsed(true), 5500);
    }
  };

  if (closed) return null;

  return (
    <div className="offer-badge-wrap">
      <div
        className={`offer-badge ${shown ? "show" : ""} ${collapsed ? "collapsed" : ""}`}
        onClick={expand}
      >
        <div className="offer-badge-ring" />
        <a
          className="offer-badge-link"
          href={offerLink}
          target="_blank"
          rel="noopener"
          onClick={(e) => { if (collapsed) { e.preventDefault(); expand(e); } }}
        >
          <img src="assets/offer-illustration.png" alt="" className="offer-badge-bg" />
          <div className="offer-badge-content">
            <span className="offer-badge-eyebrow">✦ SEZON ✦</span>
            <span className="offer-badge-title">{titles[lang] || titles.tr}</span>
            <span className="offer-badge-price">€10</span>
            <span className="offer-badge-wa"><Icon.Wa /> WhatsApp</span>
          </div>
        </a>
        <button
          className="offer-badge-close"
          onClick={close}
          onMouseDown={(e) => e.stopPropagation()}
          aria-label="close"
          type="button"
        >×</button>
      </div>
    </div>
  );
}

// ========== SCROLL PROGRESS ==========
function ScrollProgress() {
  const [pct, setPct] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      const d = document.documentElement;
      const scrolled = d.scrollTop || document.body.scrollTop;
      const total = d.scrollHeight - d.clientHeight;
      setPct(total > 0 ? (scrolled / total) * 100 : 0);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return <div className="scroll-progress" style={{ '--pct': pct + '%' }} />;
}

Object.assign(window, { LoadingCurtain, CustomCursor, useMagnetic, SplitHeading, BrandLogo, OfferPopup, CookieConsent, ScrollProgress });
// ========== COOKIE CONSENT (KVKK) ==========
function CookieConsent() {
  const { lang } = useLang();
  const t = useT();
  const [status, setStatus] = useState(() => {
    return localStorage.getItem('cookie_consent') || null;
  });
  const [showSettings, setShowSettings] = useState(false);
  const [analytics, setAnalytics] = useState(true);
  const [marketing, setMarketing] = useState(false);

  // Add body class while banner visible so page bottom isn't covered
  useEffect(() => {
    document.body.classList.toggle('has-cookie-banner', !status);
    return () => document.body.classList.remove('has-cookie-banner');
  }, [status]);

  // Re-render when lang changes — state updates automatically via useT
  const accept = () => {
    localStorage.setItem('cookie_consent', 'all');
    localStorage.setItem('cookie_consent_date', new Date().toISOString());
    setStatus('all');
    setShowSettings(false);
  };
  const necessary = () => {
    localStorage.setItem('cookie_consent', 'necessary');
    localStorage.setItem('cookie_consent_date', new Date().toISOString());
    setStatus('necessary');
    setShowSettings(false);
  };
  const saveSettings = () => {
    const val = analytics || marketing ? (analytics && marketing ? 'all' : 'partial') : 'necessary';
    localStorage.setItem('cookie_consent', val);
    localStorage.setItem('cookie_consent_date', new Date().toISOString());
    setStatus(val);
    setShowSettings(false);
  };

  if (status) return null;

  return (
    <div className={"cookie-banner" + (showSettings ? " settings-open" : "")}>
      {/* Main bar */}
      {!showSettings && (
        <div className="cookie-bar">
          <div className="cookie-bar-left">
            <span className="cookie-shield" aria-hidden="true">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                <path d="M9 12l2 2 4-4" strokeWidth="2"/>
              </svg>
            </span>
            <div className="cookie-text">
              <span className="cookie-title">{t("cookie_title")}</span>
              <span className="cookie-desc">{t("cookie_desc")}</span>
            </div>
          </div>
          <div className="cookie-bar-actions">
            <button className="cookie-btn cookie-btn-necessary" onClick={necessary}>
              {t("cookie_necessary")}
            </button>
            <button className="cookie-btn cookie-btn-accept" onClick={accept}>
              {t("cookie_accept")}
            </button>
            <button className="cookie-btn cookie-btn-settings" onClick={() => setShowSettings(true)}>
              {t("cookie_settings")}
            </button>
          </div>
        </div>
      )}

      {/* Settings panel */}
      {showSettings && (
        <div className="cookie-settings-panel">
          <div className="cookie-settings-head">
            <span className="cookie-title">{t("cookie_settings")}</span>
            <button className="cookie-settings-close" onClick={() => setShowSettings(false)}>✕</button>
          </div>
          <div className="cookie-settings-body">
            <div className="cookie-category">
              <div className="cookie-cat-info">
                <span className="cookie-cat-name">{t("cookie_category_necessary")}</span>
                <span className="cookie-cat-desc">
                  {lang === "tr" ? "Sitenin temel işlevleri için zorunludur. Devre dışı bırakılamaz." :
                   lang === "de" ? "Für die grundlegenden Funktionen der Website erforderlich. Nicht deaktivierbar." :
                   lang === "fr" ? "Nécessaires au bon fonctionnement du site. Non désactivables." :
                   lang === "ar" ? "ضرورية للوظائف الأساسية للموقع. لا يمكن تعطيلها." :
                   lang === "ru" ? "Необходимы для базовых функций сайта. Нельзя отключить." :
                   "Required for basic site functionality. Cannot be disabled."}
                </span>
              </div>
              <span className="cookie-always-on">{t("cookie_always_on")}</span>
            </div>
            <div className="cookie-category">
              <div className="cookie-cat-info">
                <span className="cookie-cat-name">{t("cookie_category_analytics")}</span>
                <span className="cookie-cat-desc">
                  {lang === "tr" ? "Ziyaretçi sayısı ve sayfa performansı ölçümü için kullanılır." :
                   lang === "de" ? "Dient zur Messung von Besucherzahlen und Seitenleistung." :
                   lang === "fr" ? "Utilisés pour mesurer le nombre de visiteurs et la performance du site." :
                   lang === "ar" ? "تُستخدم لقياس عدد الزوار وأداء الصفحة." :
                   lang === "ru" ? "Используются для измерения количества посетителей и производительности." :
                   "Used to measure visitor numbers and page performance."}
                </span>
              </div>
              <label className="cookie-toggle">
                <input type="checkbox" checked={analytics} onChange={e => setAnalytics(e.target.checked)} />
                <span className="cookie-toggle-track"></span>
              </label>
            </div>
            <div className="cookie-category">
              <div className="cookie-cat-info">
                <span className="cookie-cat-name">{t("cookie_category_marketing")}</span>
                <span className="cookie-cat-desc">
                  {lang === "tr" ? "Kişiselleştirilmiş içerik ve reklam gösterimi için kullanılır." :
                   lang === "de" ? "Für personalisierte Inhalte und Werbung verwendet." :
                   lang === "fr" ? "Utilisés pour le contenu personnalisé et les publicités." :
                   lang === "ar" ? "تُستخدم لعرض المحتوى والإعلانات المخصصة." :
                   lang === "ru" ? "Используются для персонализированного контента и рекламы." :
                   "Used for personalised content and advertising."}
                </span>
              </div>
              <label className="cookie-toggle">
                <input type="checkbox" checked={marketing} onChange={e => setMarketing(e.target.checked)} />
                <span className="cookie-toggle-track"></span>
              </label>
            </div>
          </div>
          <div className="cookie-settings-foot">
            <span className="cookie-kvkk-link" onClick={() => { window.AL_NAV && window.AL_NAV('privacy'); setStatus('navigated'); }}>
              {t("cookie_kvkk")} →
            </span>
            <div className="cookie-settings-btns">
              <button className="cookie-btn cookie-btn-necessary" onClick={necessary}>{t("cookie_necessary")}</button>
              <button className="cookie-btn cookie-btn-accept" onClick={saveSettings}>{t("cookie_accept")}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}


