// ============================================================
// Aroos Damascus — shared React components
// ============================================================
const { useState, useEffect, useMemo, useCallback, useRef, createContext, useContext } = React;

// ---------- I18n + Lang context ----------
const LangCtx = createContext({ lang: "en", setLang: () => {} });
const useLang = () => useContext(LangCtx);

// Helper to pick the right side of a bilingual record
const pick = (rec, lang) => (rec && typeof rec === "object" && rec[lang] != null) ? rec[lang] : rec;

// ---------- SVG icons ----------
const RubElHizb = ({ className, style }) => (
  // Eight-pointed star = two overlapping squares rotated 45° (square + square only — within rules)
  <svg className={className} style={style} viewBox="-50 -50 100 100" fill="none" stroke="currentColor" strokeWidth="2.5">
    <rect x="-32" y="-32" width="64" height="64" />
    <rect x="-32" y="-32" width="64" height="64" transform="rotate(45)" />
  </svg>
);

const TrayIcon = ({ className, style }) => (
  // Brass-tray illustration — circle + concentric ring + handles (allowed primitives)
  <svg className={className} style={style} viewBox="-50 -50 100 100" fill="none" stroke="currentColor" strokeWidth="2.5">
    <circle cx="0" cy="0" r="42" />
    <circle cx="0" cy="0" r="34" strokeDasharray="2 4" />
    <circle cx="0" cy="0" r="6" fill="currentColor" />
    <rect x="-48" y="-3" width="6" height="6" rx="2" />
    <rect x="42" y="-3" width="6" height="6" rx="2" />
  </svg>
);

const PhoneIcon = ({ className }) => (
  <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <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-6 19.79 19.79 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>
);

const WhatsAppIcon = ({ className }) => (
  <svg className={className} viewBox="0 0 24 24" fill="currentColor">
    <path d="M.057 24l1.687-6.163a11.867 11.867 0 0 1-1.587-5.946C.16 5.335 5.495 0 12.05 0a11.82 11.82 0 0 1 8.413 3.488 11.824 11.824 0 0 1 3.48 8.414c-.003 6.557-5.338 11.892-11.893 11.892a11.9 11.9 0 0 1-5.688-1.448L.057 24zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884a9.86 9.86 0 0 0 1.51 5.26l.36.57-1 3.65 3.74-.978zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.296-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.095 3.2 5.076 4.487.71.306 1.263.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413z"/>
  </svg>
);

const MapPinIcon = ({ className }) => (
  <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
    <circle cx="12" cy="10" r="3"/>
  </svg>
);

const ClockIcon = ({ className }) => (
  <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="10"/>
    <polyline points="12 6 12 12 16 14"/>
  </svg>
);

const MetroIcon = ({ className }) => (
  <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <rect x="4" y="3" width="16" height="13" rx="3"/>
    <path d="M4 11h16"/>
    <circle cx="8" cy="13.5" r="1"/>
    <circle cx="16" cy="13.5" r="1"/>
    <path d="M8 16l-2 4M16 16l2 4"/>
  </svg>
);

const CarIcon = ({ className }) => (
  <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 13l1.5-4.5A2 2 0 0 1 8.4 7h7.2a2 2 0 0 1 1.9 1.5L19 13"/>
    <rect x="3" y="13" width="18" height="6" rx="2"/>
    <circle cx="7.5" cy="17.5" r="1.5"/>
    <circle cx="16.5" cy="17.5" r="1.5"/>
  </svg>
);

const ArrowRight = ({ className }) => (
  <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" width="14" height="14">
    <line x1="5" y1="12" x2="19" y2="12"/>
    <polyline points="12 5 19 12 12 19"/>
  </svg>
);

const StarIcon = () => <span aria-hidden style={{ color: "var(--gold-antique)" }}>✦</span>;

// ---------- Dubai time helpers ----------
function dubaiTime() {
  // Asia/Dubai is UTC+4
  const now = new Date();
  const utcMs = now.getTime() + (now.getTimezoneOffset() * 60000);
  return new Date(utcMs + 4 * 3600000);
}
function isOpenAt(date, openH, closeH) {
  // openH..closeH where closeH may be next-day (e.g. open 7 close 3)
  const h = date.getHours() + date.getMinutes() / 60;
  if (closeH > openH) return h >= openH && h < closeH;
  // wraps midnight
  return h >= openH || h < closeH;
}
function minutesUntil(target, from) {
  let m = (target - (from.getHours() * 60 + from.getMinutes()));
  while (m < 0) m += 24 * 60;
  return m;
}

// ---------- Late-night badge ----------
function LateBadge({ override }) {
  const { lang } = useLang();
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 30000);
    return () => clearInterval(id);
  }, []);
  // override values: 'auto' | 'on' | 'off'
  const time = dubaiTime();
  const realOpen = isOpenAt(time, 7, 3); // 07:00 – 03:00
  const isOpen = override === "on" ? true : override === "off" ? false : realOpen;
  const closeTime = 3; // 03:00
  let mins = 0;
  if (isOpen) {
    const closeMin = closeTime * 60;
    const nowMin = time.getHours() * 60 + time.getMinutes();
    mins = closeMin - nowMin;
    if (mins <= 0) mins += 24 * 60;
  }
  const hrs = Math.floor(mins / 60);
  const mm = mins % 60;
  const labelOpen = lang === "en" ? "Grills running" : "المشاوي شغّالة";
  const labelCount = lang === "en" ? `another ${hrs}h ${mm}m` : `لمدّة ${hrs} س ${mm} د`;
  const labelClosed = lang === "en" ? "Closed · opens 07:00" : "مغلق · يفتح 07:00";

  return (
    <div className="late-badge">
      <span className="live-dot" />
      {isOpen ? (
        <>
          <span>{labelOpen}</span>
          <span className="countdown">· {labelCount}</span>
        </>
      ) : (
        <span>{labelClosed}</span>
      )}
    </div>
  );
}

// Compact "Open now" pill for branch cards
function BranchOpenPill({ branch }) {
  const { lang } = useLang();
  const time = dubaiTime();
  let open = isOpenAt(time, 7, 3);
  // crude per-branch refinement
  if (branch.id === "sheikh-zayed") open = isOpenAt(time, 8, 2);
  if (branch.id === "sharjah") {
    const dow = time.getDay(); // 0=Sun (Asia/Dubai week: Fri=5)
    if (dow === 5) {
      const h = time.getHours() + time.getMinutes() / 60;
      open = (h >= 7 && h < 11.5) || (h >= 13 || h < 4);
    } else {
      open = isOpenAt(time, 7, 3);
    }
  }
  return (
    <div className={`open-pill ${open ? "" : "closed"}`}>
      <span className="dot" />
      {open
        ? (lang === "en" ? "Open now" : "مفتوح الآن")
        : (lang === "en" ? "Closed" : "مغلق")}
    </div>
  );
}

// ---------- Nav ----------
function Nav({ route, setRoute }) {
  const { lang, setLang } = useLang();
  const [solid, setSolid] = useState(false);
  useEffect(() => {
    const onScroll = () => setSolid(window.scrollY > 20);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    ["home", COPY.nav.home],
    ["story", COPY.nav.story],
    ["menu", COPY.nav.menu],
    ["branches", COPY.nav.branches],
    ["late-night", COPY.nav.lateNight],
  ];

  return (
    <header className={`nav ${solid ? "solid" : ""}`}>
      <div className="container nav-inner">
        <a className="nav-brand" onClick={(e) => { e.preventDefault(); setRoute("home"); }}>
          <RubElHizb className="mark" />
          <div className="wordmark-stack">
            <span className="wordmark">Aroos Damascus</span>
            <span className="wordmark-ar">عروس دمشق</span>
          </div>
        </a>

        <nav className="nav-links">
          {links.map(([key, label]) => (
            <button
              key={key}
              className={`nav-link ${route === key ? "active" : ""}`}
              onClick={() => setRoute(key)}
            >
              {pick(label, lang)}
            </button>
          ))}
        </nav>

        <div className="nav-actions">
          <div className="lang-toggle">
            <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
            <button className={lang === "ar" ? "on" : ""} onClick={() => setLang("ar")}>ع</button>
          </div>
          <button className="btn primary" onClick={() => setRoute("reserve")}>
            {lang === "en" ? "Reserve" : pick(COPY.cta.reserve, lang)}
          </button>
        </div>
      </div>
    </header>
  );
}

// ---------- Sticky CTA ----------
function StickyCTA({ setRoute }) {
  const { lang } = useLang();
  return (
    <div className="sticky-cta">
      <a href="tel:+971600500022">
        <PhoneIcon className="" /><span style={{ width: 16, height: 16, display: "inline-flex" }}><PhoneIcon /></span> {pick(COPY.cta.call, lang)}
      </a>
      <span className="cta-divider" />
      <a href="https://wa.me/971565041754" target="_blank" rel="noreferrer">
        <span style={{ width: 16, height: 16, display: "inline-flex" }}><WhatsAppIcon /></span> {pick(COPY.cta.whatsapp, lang)}
      </a>
      <span className="cta-divider" />
      <button className="reserve" onClick={() => setRoute("reserve")}>
        {pick(COPY.cta.reserve, lang)} <ArrowRight />
      </button>
    </div>
  );
}

// Simpler StickyCTA without double phone icons
function StickyCTAClean({ setRoute }) {
  const { lang } = useLang();
  return (
    <div className="sticky-cta" role="region" aria-label="Quick contact">
      <a href="tel:+971600500022" title="Call 600 500022">
        <span style={{ width: 14, height: 14, display: "inline-flex" }}><PhoneIcon /></span>
        {pick(COPY.cta.call, lang)}
      </a>
      <span className="cta-divider" />
      <a href="https://wa.me/971565041754" target="_blank" rel="noreferrer">
        <span style={{ width: 14, height: 14, display: "inline-flex" }}><WhatsAppIcon /></span>
        {pick(COPY.cta.whatsapp, lang)}
      </a>
      <span className="cta-divider" />
      <button className="reserve" onClick={() => setRoute("reserve")}>
        {pick(COPY.cta.reserve, lang)} <ArrowRight />
      </button>
    </div>
  );
}

// ---------- WhatsApp FAB ----------
function WAFab() {
  return (
    <a className="wa-fab" href="https://wa.me/971565041754" target="_blank" rel="noreferrer" aria-label="WhatsApp">
      <WhatsAppIcon />
    </a>
  );
}

// ---------- Footer ----------
function Footer({ setRoute }) {
  const { lang } = useLang();
  return (
    <footer className="foot">
      <div className="container">
        <div className="foot-grid">
          <div>
            <div className="foot-brand">Aroos Damascus</div>
            <span className="foot-brand-ar">عروس دمشق</span>
            <p className="foot-tag">
              {lang === "en"
                ? "Forty-five years of charcoal, mezze and Deira nights."
                : "خمسة وأربعون عاماً من الفحم والمازة وليالي ديرة."}
            </p>
          </div>
          <div>
            <h4>{lang === "en" ? "Visit" : "زورنا"}</h4>
            <ul>
              <li><a onClick={() => setRoute("branches")}>{lang === "en" ? "Al Muraqqabat" : "المرقّبات"}</a></li>
              <li><a onClick={() => setRoute("branches")}>{lang === "en" ? "Sheikh Zayed Rd" : "شارع الشيخ زايد"}</a></li>
              <li><a onClick={() => setRoute("branches")}>{lang === "en" ? "Sharjah" : "الشارقة"}</a></li>
              <li><a onClick={() => setRoute("late-night")}>{lang === "en" ? "Late Night · until 03:00" : "ساعة متأخرة · حتى 03:00"}</a></li>
            </ul>
          </div>
          <div>
            <h4>{lang === "en" ? "Order" : "اطلب"}</h4>
            <ul>
              <li><a href="tel:+971600500022">600 500022</a></li>
              <li><a href="https://wa.me/971565041754" target="_blank" rel="noreferrer">WhatsApp · +971 56 504 1754</a></li>
              <li><a href="https://talabat.com" target="_blank" rel="noreferrer">Talabat</a></li>
              <li><a onClick={() => setRoute("reserve")}>{lang === "en" ? "Reserve" : "احجز"}</a></li>
            </ul>
          </div>
          <div>
            <h4>{lang === "en" ? "Follow" : "تابعنا"}</h4>
            <ul>
              <li><a href="https://instagram.com/aroosdamascus" target="_blank" rel="noreferrer">Instagram · @aroosdamascus</a></li>
              <li><a href="https://facebook.com" target="_blank" rel="noreferrer">Facebook</a></li>
              <li><a onClick={() => setRoute("story")}>{lang === "en" ? "Our Story" : "حكايتنا"}</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-base">
          <span>© 1980 – {new Date().getFullYear()} Aroos Damascus · عروس دمشق</span>
          <span>{lang === "en" ? "Deira · Sheikh Zayed Rd · Sharjah" : "ديرة · شارع الشيخ زايد · الشارقة"}</span>
        </div>
      </div>
    </footer>
  );
}

// Export
Object.assign(window, {
  LangCtx, useLang, pick,
  RubElHizb, TrayIcon, PhoneIcon, WhatsAppIcon, MapPinIcon, ClockIcon, MetroIcon, CarIcon, ArrowRight, StarIcon,
  dubaiTime, isOpenAt,
  LateBadge, BranchOpenPill,
  Nav, StickyCTA: StickyCTAClean, WAFab, Footer,
});
