/* ============================================================
   APP — routing, footer, language, tweaks
   ============================================================ */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "tone": "coral",
  "hero": "video",
  "floor": "guided",
  "membership": "spotlight",
  "hookah": "scroll",
  "startLang": "en"
}/*EDITMODE-END*/;

const TONES = {
  coral: { "--c-coral": "#FF6B5B", "--c-coral-deep": "#E8725A", "--c-gold": "#C9929A", "--c-gold-soft": "#E8C8C6", "--c-purple": "#9333EA" },
  neon:  { "--c-coral": "#FF2E88", "--c-coral-deep": "#EA5D81", "--c-gold": "#D98FA0", "--c-gold-soft": "#F2C3D2", "--c-purple": "#B23A5C" },
  gold:  { "--c-coral": "#C08A6E", "--c-coral-deep": "#9C7259", "--c-gold": "#D7A39C", "--c-gold-soft": "#ECCBC4", "--c-purple": "#6E5A44" },
};

function Footer({ go }) {
  const t = useT(); const { lang } = useLang();
  const [subbed, setSubbed] = useState(false);
  const links = [
    ["home", t("Home", "Inicio")], ["reserve", t("Reservations", "Reservas")], ["menu", t("Menu", "Menú")],
    ["sports", t("Sports", "Deportes")], ["membership", t("Membership", "Membresía")], ["account", t("Members", "Miembros")],
  ];
  return (
    <footer className="bg-ink border-t border-white/5 pt-20 pb-28 sm:pb-10 relative overflow-hidden">
      <div className="absolute top-0 left-1/4 w-96 h-96 bg-coral/5 rounded-full blur-[120px] pointer-events-none"></div>
      <div className="container relative z-10">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-12 mb-14">
          <div className="space-y-6">
            <img src={window.__asset ? window.__asset("assets/logo-pink-trimmed.png") : "assets/logo-pink-trimmed.png"} alt="Pink Pony Club" className="h-10 object-contain" />
            <p className="text-white/55 font-light leading-relaxed text-sm">{t("Miami's premier gentlemen's club in the heart of Doral. Luxury nightlife, VIP bottle service, live performances and world-class entertainment.", "El club de caballeros premier de Miami en el corazón de Doral. Vida nocturna de lujo, botellas VIP, shows en vivo y entretenimiento de clase mundial.")}</p>
            <div className="flex gap-3">{["instagram", "facebook", "youtube", "tiktok", "x"].map((s) => {
              const url = window.PP.SOCIAL[s];
              return <a key={s} href={url || "#"} target={url ? "_blank" : undefined} rel="noopener" onClick={url ? undefined : (e) => e.preventDefault()} aria-label={s} className="w-10 h-10 rounded-full border border-white/12 flex items-center justify-center text-white/60 hover:text-coral hover:border-coral transition-colors"><BrandIcon name={s} className="w-4 h-4" /></a>;
            })}</div>
          </div>
          <div className="space-y-5"><h4 className="label text-white/80 border-b border-white/10 pb-2 inline-block">{t("Explore", "Explorar")}</h4><ul className="space-y-3">{links.map(([id, lbl]) => <li key={id}><button onClick={() => go(id)} className="text-white/55 text-sm hover:text-white transition-colors">{lbl}</button></li>)}<li><button onClick={() => go("casting")} className="text-white/55 text-sm hover:text-coral transition-colors inline-flex items-center gap-1.5">{t("Casting Call", "Casting Call")}<span className="text-[8px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-coral/20 text-coral">{t("Hiring", "Audición")}</span></button></li></ul></div>
          <div className="space-y-5">
            <h4 className="label text-white/80 border-b border-white/10 pb-2 inline-block">{t("Visit Us", "Visítanos")}</h4>
            <ul className="space-y-4 text-sm">
              <li className="flex items-start gap-3 text-white/55"><Icon name="map-pin" className="w-4 h-4 text-gold mt-0.5 shrink-0" /><span>7971 NW 33rd St<br />Doral, FL 33122</span></li>
              <li className="flex items-center gap-3 text-white/55"><Icon name="phone" className="w-4 h-4 text-gold shrink-0" /><a href={"https://wa.me/" + window.PP.WA} target="_blank" rel="noopener" className="hover:text-white transition-colors">{window.PP.WA_DISPLAY}</a></li>
              <li className="flex items-center gap-3 text-white/55"><Icon name="mail" className="w-4 h-4 text-gold shrink-0" /><a href="mailto:RSVP@clubpinkpony.com" className="hover:text-white transition-colors">RSVP@clubpinkpony.com</a></li>
              <li className="flex items-center gap-3 text-white/55"><Icon name="clock" className="w-4 h-4 text-gold shrink-0" /><span>{t("Open Daily · 12PM–5AM", "Abierto · 12PM–5AM")}</span></li>
            </ul>
          </div>
          <div className="space-y-5">
            <h4 className="label text-white/80 border-b border-white/10 pb-2 inline-block">{t("Stay Updated", "Mantente al Día")}</h4>
            <p className="text-white/55 text-sm">{t("Events, performances and exclusive offers.", "Eventos, shows y ofertas exclusivas.")}</p>
            {subbed ? (
              <div className="flex items-center gap-2 text-sm text-gold-soft fade-view"><Icon name="check" className="w-4 h-4 text-coral" />{t("You're on the list — we'll be in touch.", "Estás en la lista — te contactamos.")}</div>
            ) : (
              <form className="relative" onSubmit={(e) => {
                  e.preventDefault();
                  const email = (new FormData(e.target).get("email") || "").toString();
                  window.PP.waOpen(
                    t("New newsletter signup — Pink Pony Club", "Nuevo registro al boletín — Pink Pony Club"),
                    [[t("Email", "Correo"), email]],
                    t("Sent from clubpinkpony.com", "Enviado desde clubpinkpony.com"),
                  );
                  setSubbed(true);
                }}>
                <input name="email" type="email" required placeholder={t("Enter your email", "Tu correo")} className="w-full bg-white/5 border border-white/10 rounded-full px-5 py-3.5 pr-14 text-white text-sm focus:outline-none focus:border-gold/60 transition-all placeholder:text-white/35" />
                <button className="absolute right-1.5 top-1.5 bottom-1.5 w-10 bg-gradient-to-r from-coral to-coral-deep text-white rounded-full flex items-center justify-center hover:scale-105 transition-transform" aria-label={t("Subscribe", "Suscribirse")}><Icon name="arrow-right" className="w-4 h-4" /></button>
              </form>
            )}
          </div>
        </div>
        <div className="hairline mb-7"></div>
        <div className="flex flex-col md:flex-row justify-between items-center gap-4 text-xs text-white/40">
          <span>© 2026 Club Pink Pony · Doral, Miami · 21+ · {t("All rights reserved.", "Todos los derechos reservados.")}</span>
          <div className="flex gap-5"><button onClick={() => go("privacy")} className="hover:text-gold transition-colors">{t("Privacy", "Privacidad")}</button><button onClick={() => go("terms")} className="hover:text-gold transition-colors">{t("Terms", "Términos")}</button><a href="https://app.clubpinkpony.com" className="hover:text-gold transition-colors flex items-center gap-1.5"><Icon name="lock" className="w-3 h-3" />{t("Staff", "Staff")}</a></div>
        </div>
      </div>
    </footer>
  );
}

function ConciergeFloat() {
  const t = useT();
  const [open, setOpen] = useState(false);
  return (
    <div className="fixed bottom-20 sm:bottom-5 left-5 z-40 flex flex-col items-start gap-3">
      {open && (
        <div className="fade-view rounded-2xl border border-white/12 bg-ink/95 backdrop-blur-xl shadow-2xl p-4 w-60">
          <div className="label text-gold text-[10px] mb-2">{t("VIP Concierge", "Concierge VIP")}</div>
          <p className="text-white/65 text-xs mb-3">{t("Tables, bottles, birthdays — we handle it all. Message us now.", "Mesas, botellas, cumpleaños — lo resolvemos todo. Escríbenos ya.")}</p>
          <div className="flex flex-col gap-2">
            <a href={window.PP.waLink(t("Hi Pink Pony — I'd like help from the VIP concierge.", "Hola Pink Pony — quiero ayuda del concierge VIP."))} target="_blank" rel="noopener" className="flex items-center gap-2 px-3 py-2.5 rounded-xl bg-coral hover:bg-coral-deep text-white text-xs font-bold uppercase tracking-wider transition-colors"><Icon name="message-circle" className="w-4 h-4" />WhatsApp</a>
            <a href={"tel:" + window.PP.WA_TEL} className="flex items-center gap-2 px-3 py-2.5 rounded-xl border border-white/15 text-white/80 text-xs font-bold uppercase tracking-wider hover:bg-white/5 transition-colors"><Icon name="phone" className="w-4 h-4" />{t("Call", "Llamar")}</a>
          </div>
        </div>
      )}
      <button onClick={() => setOpen((o) => !o)} className="w-14 h-14 rounded-full bg-coral text-white flex items-center justify-center shadow-[0_8px_30px_rgba(255,107,91,.5)] hover:scale-105 transition-transform" title={t("VIP Concierge", "Concierge VIP")}>
        <Icon name={open ? "x" : "message-circle"} className="w-6 h-6" />
      </button>
    </div>
  );
}

/* 21+ age gate — industry standard for the public site; remembered per device */
function AgeGate({ go }) {
  const t = useT();
  const [ok, setOk] = useState(() => { try { return localStorage.getItem("pp_age_v1") === "1"; } catch (e) { return true; } });
  const [leaving, setLeaving] = useState(false);
  if (ok) return null;
  const enter = () => { try { localStorage.setItem("pp_age_v1", "1"); } catch (e) {} setOk(true); };
  return (
    <div className="fixed inset-0 z-[90] flex items-center justify-center p-6" role="dialog" aria-modal="true" aria-label="Age verification">
      <div className="absolute inset-0 bg-ink/95 backdrop-blur-xl"></div>
      <div className="absolute top-1/4 -left-24 w-96 h-96 bg-coral/15 rounded-full blur-[140px] pointer-events-none"></div>
      <div className="absolute bottom-0 right-0 w-96 h-96 bg-grape/15 rounded-full blur-[140px] pointer-events-none"></div>
      <div className="relative w-full max-w-md text-center fade-view">
        <img src={window.__asset ? window.__asset("assets/logo-pink-trimmed.png") : "assets/logo-pink-trimmed.png"} alt="Pink Pony Club" className="h-8 mx-auto mb-8 object-contain" />
        {leaving ? (
          <div className="rounded-3xl border border-white/12 bg-card p-8">
            <p className="text-white/70 text-sm leading-relaxed">{t("This venue is for guests 21 and over. See you when it's time.", "Este lugar es para mayores de 21 años. Nos vemos cuando sea el momento.")}</p>
          </div>
        ) : (
          <div className="rounded-3xl border border-white/12 bg-card p-8">
            <div className="serif text-6xl text-coral leading-none mb-3">21+</div>
            <h1 className="text-2xl font-black uppercase mb-2">{t("Are you 21 or older?", "¿Eres mayor de 21 años?")}</h1>
            <p className="text-white/50 text-sm mb-7">{t("You must be of legal age to enter this site. Valid photo ID is required at the door.", "Debes ser mayor de edad para entrar a este sitio. Se requiere identificación válida en la puerta.")}</p>
            <div className="flex flex-col gap-3">
              <button onClick={enter} className="gbtn w-full py-3.5 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-[0.16em] transition-all">{t("Yes — I'm 21 or older", "Sí — soy mayor de 21")}</button>
              <button onClick={() => setLeaving(true)} className="w-full py-3.5 rounded-full border border-white/15 text-white/70 text-[12px] font-bold uppercase tracking-[0.16em] hover:bg-white/5 transition-colors">{t("No, exit", "No, salir")}</button>
            </div>
            <p className="text-white/30 text-[11px] mt-6">{t("By entering you agree to our", "Al entrar aceptas nuestros")} <button onClick={() => { enter(); go("terms"); }} className="underline hover:text-white/60">{t("Terms", "Términos")}</button> · <button onClick={() => { enter(); go("privacy"); }} className="underline hover:text-white/60">{t("Privacy", "Privacidad")}</button></p>
          </div>
        )}
      </div>
    </div>
  );
}

/* mobile quick actions — reserve & whatsapp always one thumb away */
function MobileQuickBar({ view, go }) {
  const t = useT();
  if (view === "admin") return null;
  const items = [
    ["home", t("Home", "Inicio"), "house"],
    ["events", t("Events", "Eventos"), "calendar-days"],
    ["reserve", t("Reserve", "Reservar"), "sparkles", true],
    ["menu", t("Menu", "Menú"), "utensils"],
  ];
  return (
    <nav className="sm:hidden fixed bottom-0 inset-x-0 z-30 bg-ink/95 backdrop-blur-xl border-t border-white/10 flex items-stretch" style={{ paddingBottom: "env(safe-area-inset-bottom)" }}>
      {items.map(([id, lbl, ic, hot]) => (
        <button key={id} onClick={() => go(id)} className={"flex-1 flex flex-col items-center gap-1 py-2.5 transition-colors " + (view === id ? "text-coral" : hot ? "text-white" : "text-white/50")}>
          <span className={hot ? "w-9 h-9 -mt-4 rounded-full bg-coral flex items-center justify-center shadow-[0_6px_20px_rgba(255,107,91,.5)]" : ""}><Icon name={ic} className="w-5 h-5" /></span>
          <span className="text-[9px] font-bold uppercase tracking-wide">{lbl}</span>
        </button>
      ))}
      <a href={window.PP.waLink("Hi Pink Pony!")} target="_blank" rel="noopener" className="flex-1 flex flex-col items-center gap-1 py-2.5 text-white/50">
        <Icon name="message-circle" className="w-5 h-5" />
        <span className="text-[9px] font-bold uppercase tracking-wide">WhatsApp</span>
      </a>
    </nav>
  );
}

/* ============================================================
   TWO SURFACES, ONE CODEBASE — host decides:
   · PUBLIC   www.clubpinkpony.com   (Firebase: pinkpony-app)
   · WORKSPACE app.clubpinkpony.com  (Firebase: clubpinkpony-77d06)
   ?app=1 forces the workspace on any host (pre-DNS testing).
   ============================================================ */
const WORKSPACE_HOSTS = ["app.clubpinkpony.com", "clubpinkpony-77d06.web.app", "clubpinkpony-77d06.firebaseapp.com"];
const PUBLIC_HOSTS = ["clubpinkpony.com", "www.clubpinkpony.com", "pinkpony-app.web.app", "pinkpony-app.firebaseapp.com"];
function isWorkspaceHost() {
  if (typeof location === "undefined") return false;
  const host = (location.hostname || "").toLowerCase();
  // The public marketing domains are ALWAYS the website — never the workspace,
  // even if a stray ?app= query param is left in the URL.
  if (PUBLIC_HOSTS.includes(host)) return false;
  let params; try { params = new URLSearchParams(location.search || ""); } catch (e) { params = { has: () => false }; }
  return WORKSPACE_HOSTS.includes(host) || host.startsWith("app.") || params.has("app") || params.has("workspace");
}

function WorkspaceBar({ lang, setLang }) {
  return (
    <header className="fixed top-0 inset-x-0 z-40 h-14 bg-ink/90 backdrop-blur-xl border-b border-white/10 flex items-center justify-between px-4 md:px-6">
      <div className="flex items-center gap-2.5">
        <img src={window.__asset ? window.__asset("assets/logo-white.png") : "assets/logo-white.png"} alt="Pink Pony Club" className="h-4 object-contain" />
        <span className="label text-white/45 text-[9px] hidden sm:inline border-l border-white/15 pl-2.5">Hub · Plataforma Interna</span>
      </div>
      <div className="flex items-center rounded-full border border-white/15 overflow-hidden text-[11px] font-bold tracking-widest">
        {["en", "es"].map((l) => <button key={l} onClick={() => setLang(l)} className={"px-3 py-1.5 uppercase transition-colors " + (lang === l ? "bg-white text-black" : "text-white/60 hover:text-white")}>{l}</button>)}
      </div>
    </header>
  );
}

/* the workspace IS the admin portal — no public marketing chrome */
function Workspace() {
  const [lang, setLang] = useState(TWEAK_DEFAULTS.startLang || "en");
  useEffect(() => {
    const tone = TONES[TWEAK_DEFAULTS.tone] || TONES.coral;
    Object.entries(tone).forEach(([k, v]) => document.documentElement.style.setProperty(k, v));
    document.title = "Pink Pony Hub";
    // keep the private workspace out of search engines
    let m = document.querySelector('meta[name="robots"]');
    if (!m) { m = document.createElement("meta"); m.name = "robots"; document.head.appendChild(m); }
    m.content = "noindex, nofollow";
  }, []);
  useEffect(() => { document.documentElement.lang = lang; }, [lang]);
  useEffect(() => { window.__ppGo = () => {}; }, []); // portal previews don't navigate the public site
  return (
    <LangContext.Provider value={{ lang, setLang }}>
      <WorkspaceBar lang={lang} setLang={setLang} />
      <AdminPortal />
    </LangContext.Provider>
  );
}

function App() {
  const CFG = TWEAK_DEFAULTS;
  const VIEWS = ["home", "reserve", "menu", "events", "sports", "experiences", "venue", "store", "casting", "membership", "account", "privacy", "terms"];
  const [view, setView] = useState(() => {
    const h = (typeof location !== "undefined" ? location.hash : "").replace(/^#/, "");
    return VIEWS.includes(h) ? h : "home";
  });
  const [lang, setLang] = useState(CFG.startLang || "en");

  // apply tone
  useEffect(() => {
    const tone = TONES[CFG.tone] || TONES.coral;
    Object.entries(tone).forEach(([k, v]) => document.documentElement.style.setProperty(k, v));
  }, []);

  // keep <html lang> in sync with the chosen language (a11y + SEO)
  useEffect(() => { document.documentElement.lang = lang; }, [lang]);

  // Meta Pixel: count each in-app page view (SPA route change)
  useEffect(() => { window.PP && window.PP.track && window.PP.track("ViewContent", { content_name: view }); }, [view]);

  // lucide icons now self-render inside their own wrapper (see Icon component) —
  // no document-wide createIcons() needed, which previously corrupted the React tree.

  const go = useCallback((v) => {
    setView(v);
    try { history.replaceState(null, "", v === "home" ? location.pathname + location.search : "#" + v); } catch (e) {}
    window.scrollTo({ top: 0, behavior: "auto" });
  }, []);
  useEffect(() => { window.__ppGo = go; }, [go]);

  let page;
  if (view === "home") page = <HomePage heroVariant={CFG.hero} hookahVariant={CFG.hookah} go={go} />;
  else if (view === "reserve") page = <ReservePage variant={CFG.floor} account={null} />;
  else if (view === "menu") page = <MenuPage go={go} />;
  else if (view === "events") page = <EventsPage go={go} />;
  else if (view === "sports") page = <EventsPage go={go} initial="sports" />;
  else if (view === "experiences") page = <ExperiencesPage go={go} />;
  else if (view === "venue") page = <VenuePage go={go} />;
  else if (view === "store") page = <StorePage go={go} />;
  else if (view === "casting") page = <CastingPage go={go} />;
  else if (view === "membership") page = <MembershipPage variant={CFG.membership} go={go} />;
  else if (view === "account") page = <AccountPage go={go} />;
  else if (view === "privacy") page = <PrivacyPage />;
  else if (view === "terms") page = <TermsPage />;

  return (
    <LangContext.Provider value={{ lang, setLang }}>
      <Nav view={view} go={go} account={null} />
      <main key={view} className="fade-view min-h-screen pb-16 sm:pb-0">{page}</main>
      <Footer go={go} />
      <ConciergeFloat />
      <MobileQuickBar view={view} go={go} />
      <AgeGate go={go} />
    </LangContext.Provider>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(isWorkspaceHost() ? <Workspace /> : <App />);
