/* ============================================================
   MEMBER SOCIAL — member-social.jsx
   PonyMatch (Tinder-style crowd), free-ticket Drops, Invite,
   and the reusable LockGate that paywalls free accounts.
   ============================================================ */

/* ---------- LOCK GATE — blurs content + upgrade panel for free users ---------- */
function LockGate({ locked, go, title, sub, perks, children, accent = "#FF6B5B" }) {
  const t = useT();
  if (!locked) return children;
  return (
    <div className="relative rounded-3xl overflow-hidden border border-white/10 min-h-[460px]">
      <div className="absolute inset-0 pointer-events-none select-none" style={{ filter: "blur(11px) brightness(.4) saturate(1.2)", transform: "scale(1.05)" }}>{children}</div>
      <div className="absolute inset-0" style={{ background: "radial-gradient(120% 90% at 50% 0%, rgba(255,46,136,.18), rgba(11,11,12,.92) 70%)" }}></div>
      <div className="relative z-10 flex flex-col items-center justify-center text-center px-6 py-16 min-h-[460px]">
        <div className="w-16 h-16 rounded-2xl flex items-center justify-center mb-6 border" style={{ background: accent + "1a", borderColor: accent + "66", boxShadow: `0 0 40px ${accent}40` }}>
          <Icon name="lock" className="w-7 h-7" style={{ color: accent }} />
        </div>
        <div className="label text-[10px] mb-3" style={{ color: accent }}>{t("Members only", "Solo miembros")}</div>
        <h3 className="text-3xl md:text-4xl font-black uppercase leading-none mb-3">{title}</h3>
        <p className="text-white/60 max-w-md mb-7">{sub}</p>
        {perks && (
          <ul className="space-y-2.5 mb-8 text-left">
            {perks.map((p, i) => <li key={i} className="flex items-center gap-3 text-white/80 text-sm"><Icon name="check" className="w-4 h-4 shrink-0" style={{ color: accent }} />{p}</li>)}
          </ul>
        )}
        <PrimaryBtn icon="crown" onClick={() => go("membership")}>{t("Unlock with membership", "Desbloquear con membresía")}</PrimaryBtn>
        <button onClick={() => go("membership")} className="mt-4 text-white/45 text-xs hover:text-white transition-colors">{t("Plans from $49/mo", "Planes desde $49/mes")}</button>
      </div>
    </div>
  );
}

/* ---------- PONYMATCH — swipe through the crowd going out tonight ---------- */
function MatchCard({ p, lang, style, stamp, onRef, onDown }) {
  const t = useT();
  const initials = p.name.slice(0, 1);
  return (
    <div ref={onRef} onPointerDown={onDown}
      className="absolute inset-0 rounded-[28px] overflow-hidden border border-white/12 cursor-grab active:cursor-grabbing select-none touch-none"
      style={{ background: "#101012", boxShadow: "0 30px 80px -24px rgba(0,0,0,.9)", ...style }}>
      {/* stylized identity field — blurred until you match */}
      <div className="absolute inset-0" style={{ background: `radial-gradient(110% 80% at 50% 0%, ${p.accent}40, #0c0c0e 72%)` }}></div>
      <div className="absolute inset-0 opacity-[0.5]" style={{ backgroundImage: "radial-gradient(circle at 1px 1px,rgba(255,255,255,.10) 1px,transparent 0)", backgroundSize: "22px 22px" }}></div>
      <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-[58%] font-black select-none" style={{ fontSize: 200, lineHeight: 1, color: p.accent + "33", filter: "blur(2px)" }}>{initials}</div>
      <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-[58%] w-28 h-28 rounded-full flex items-center justify-center text-5xl font-black backdrop-blur-md" style={{ background: p.accent + "22", border: `2px solid ${p.accent}`, color: "#fff", boxShadow: `0 0 50px ${p.accent}55` }}>{initials}</div>

      {/* going-to chip */}
      <div className="absolute top-5 left-5 z-10">
        <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-black/55 backdrop-blur border border-white/15 text-[10px] font-bold uppercase tracking-wider text-white/85"><Icon name="calendar" className="w-3 h-3" style={{ color: p.accent }} />{L(p.going, lang)}</span>
      </div>
      {p.likesYou && (
        <div className="absolute top-5 right-5 z-10">
          <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-[10px] font-bold uppercase tracking-wider text-white animate-pulse" style={{ background: "#FF2E88", boxShadow: "0 0 20px #FF2E8888" }}><Icon name="heart" className="w-3 h-3" />{t("Likes you", "Le gustas")}</span>
        </div>
      )}

      {/* LIKE / PASS stamps */}
      <div className="absolute top-10 left-7 z-20 px-4 py-1.5 rounded-lg border-4 font-black uppercase tracking-widest text-2xl -rotate-12" style={{ color: "#5FBFA8", borderColor: "#5FBFA8", opacity: stamp === "like" ? 1 : 0, transition: "opacity .1s" }}>{t("Like", "Like")}</div>
      <div className="absolute top-10 right-7 z-20 px-4 py-1.5 rounded-lg border-4 font-black uppercase tracking-widest text-2xl rotate-12" style={{ color: "#FF4D4D", borderColor: "#FF4D4D", opacity: stamp === "pass" ? 1 : 0, transition: "opacity .1s" }}>{t("Pass", "Pass")}</div>

      <div className="absolute inset-x-0 bottom-0 z-10 p-6" style={{ background: "linear-gradient(to top, rgba(8,8,10,.96), transparent)" }}>
        <div className="flex items-end gap-2 mb-1.5">
          <h3 className="text-3xl font-black leading-none">{p.name}</h3>
          <span className="text-2xl font-light text-white/70 leading-none">{p.age}</span>
          <Icon name="badge-check" className="w-5 h-5 mb-0.5" style={{ color: p.accent }} />
        </div>
        <p className="serif-it text-white/75 text-lg mb-3">{L(p.tag, lang)}</p>
        <div className="flex flex-wrap gap-2">
          {p.vibes.map((v, i) => <span key={i} className="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider border border-white/15 text-white/75 bg-white/5">{v}</span>)}
        </div>
      </div>
    </div>
  );
}

function PonyMatch({ account }) {
  const t = useT(); const { lang } = useLang();
  const CROWD = window.PP.CROWD;
  const [idx, setIdx] = useState(0);
  const [drag, setDrag] = useState({ x: 0, y: 0, active: false });
  const [fly, setFly] = useState(null); // {dir, x}
  const [match, setMatch] = useState(null);
  const [liked, setLiked] = useState(0);
  const start = useRef(null);
  const cardRef = useRef(null);

  const cur = CROWD[idx];
  const stamp = drag.x > 45 ? "like" : drag.x < -45 ? "pass" : (fly ? (fly.dir === "like" ? "like" : "pass") : null);

  const finish = (dir) => {
    const profile = CROWD[idx];
    setFly({ dir, x: dir === "like" ? 600 : -600 });
    setTimeout(() => {
      setFly(null); setDrag({ x: 0, y: 0, active: false });
      setIdx((i) => i + 1);
      if (dir === "like") {
        setLiked((n) => n + 1);
        if (profile && profile.likesYou) setMatch(profile);
      }
    }, 320);
  };

  const onDown = (e) => {
    if (fly) return;
    start.current = { x: e.clientX, y: e.clientY };
    setDrag({ x: 0, y: 0, active: true });
    e.currentTarget.setPointerCapture?.(e.pointerId);
    const move = (ev) => setDrag({ x: ev.clientX - start.current.x, y: ev.clientY - start.current.y, active: true });
    const up = (ev) => {
      window.removeEventListener("pointermove", move);
      window.removeEventListener("pointerup", up);
      const dx = ev.clientX - start.current.x;
      if (dx > 110) finish("like");
      else if (dx < -110) finish("pass");
      else setDrag({ x: 0, y: 0, active: false });
    };
    window.addEventListener("pointermove", move);
    window.addEventListener("pointerup", up);
  };

  const topStyle = () => {
    if (fly) return { transform: `translate(${fly.x}px, -40px) rotate(${fly.dir === "like" ? 22 : -22}deg)`, opacity: 0, transition: "transform .32s ease, opacity .32s ease" };
    return { transform: `translate(${drag.x}px, ${drag.y}px) rotate(${drag.x / 18}deg)`, transition: drag.active ? "none" : "transform .35s cubic-bezier(.18,.9,.3,1.2)" };
  };

  const done = idx >= CROWD.length;

  return (
    <div className="fade-view">
      <div className="flex flex-col lg:flex-row gap-8 lg:gap-12 items-start">
        {/* deck */}
        <div className="w-full max-w-[400px] mx-auto lg:mx-0">
          <div className="relative w-full" style={{ aspectRatio: "3/4.2" }}>
            {done ? (
              <div className="absolute inset-0 rounded-[28px] border border-white/12 bg-card flex flex-col items-center justify-center text-center px-8">
                <div className="w-16 h-16 rounded-full bg-coral/15 border border-coral/40 flex items-center justify-center mb-5"><Icon name="sparkles" className="w-7 h-7 text-coral" /></div>
                <h3 className="text-2xl font-black uppercase mb-2">{t("You're all caught up", "Por hoy es todo")}</h3>
                <p className="text-white/55 text-sm mb-6">{t("New faces drop every night. Check back before you head out.", "Caras nuevas cada noche. Vuelve antes de salir.")}</p>
                <button onClick={() => { setIdx(0); setLiked(0); }} className="px-6 py-3 rounded-full border border-white/20 text-white text-[12px] font-bold uppercase tracking-wider hover:bg-white/5 transition-colors flex items-center gap-2"><Icon name="rotate-ccw" className="w-4 h-4" />{t("Start over", "Reiniciar")}</button>
              </div>
            ) : (
              <React.Fragment>
                {/* next card peeking */}
                {CROWD[idx + 1] && <div className="absolute inset-0 rounded-[28px] border border-white/10 bg-card" style={{ transform: "scale(.94) translateY(14px)", opacity: .6 }}></div>}
                {CROWD[idx + 2] && <div className="absolute inset-0 rounded-[28px] border border-white/8 bg-card" style={{ transform: "scale(.88) translateY(28px)", opacity: .3 }}></div>}
                <MatchCard p={cur} lang={lang} style={topStyle()} stamp={stamp} onRef={cardRef} onDown={onDown} />
              </React.Fragment>
            )}
          </div>
          {/* controls */}
          {!done && (
            <div className="flex items-center justify-center gap-5 mt-6">
              <button onClick={() => finish("pass")} className="w-16 h-16 rounded-full border-2 border-white/15 bg-card flex items-center justify-center text-[#FF4D4D] hover:scale-110 hover:border-[#FF4D4D]/60 transition-all" aria-label="Pass"><Icon name="x" className="w-7 h-7" /></button>
              <button onClick={() => finish("like")} className="w-20 h-20 rounded-full flex items-center justify-center text-white hover:scale-110 transition-all" style={{ background: "linear-gradient(135deg,#FF2E88,#FF6B5B)", boxShadow: "0 10px 40px rgba(255,46,136,.5)" }} aria-label="Like"><Icon name="heart" className="w-9 h-9" /></button>
              <button onClick={() => finish("like")} className="w-16 h-16 rounded-full border-2 border-white/15 bg-card flex items-center justify-center text-gold hover:scale-110 hover:border-gold/60 transition-all" aria-label="Super like"><Icon name="star" className="w-7 h-7" /></button>
            </div>
          )}
        </div>

        {/* side panel */}
        <div className="flex-1 w-full">
          <Eyebrow num="" className="!text-coral">{t("PonyMatch", "PonyMatch")}</Eyebrow>
          <h2 className="text-3xl md:text-5xl font-black uppercase leading-[0.95] mt-3 mb-4">{t(<>Meet the<br /><span className="serif-it font-normal text-coral">crowd</span> tonight</>, <>Conoce a la<br /><span className="serif-it font-normal text-coral">gente</span> de hoy</>)}</h2>
          <p className="text-white/60 leading-relaxed mb-7 max-w-md">{t("Swipe through verified members heading out tonight. Like who you vibe with — when it's mutual, you match and the chat opens. Identities stay blurred until you both say yes.", "Desliza entre miembros verificados que salen hoy. Dale like a quien conectes — si es mutuo, hacen match y se abre el chat. Las identidades quedan difuminadas hasta que ambos digan que sí.")}</p>
          <div className="grid grid-cols-3 gap-3 mb-8 max-w-md">
            <div className="rounded-2xl border border-white/10 bg-card p-4 text-center"><div className="serif text-3xl text-coral">{liked}</div><div className="label text-white/45 text-[9px] mt-1">{t("Liked", "Likes")}</div></div>
            <div className="rounded-2xl border border-white/10 bg-card p-4 text-center"><div className="serif text-3xl text-gold-soft">{account.matches}</div><div className="label text-white/45 text-[9px] mt-1">{t("Matches", "Matches")}</div></div>
            <div className="rounded-2xl border border-white/10 bg-card p-4 text-center"><div className="serif text-3xl text-white">{Math.max(0, window.PP.CROWD.length - idx)}</div><div className="label text-white/45 text-[9px] mt-1">{t("Nearby", "Cerca")}</div></div>
          </div>
          <div className="flex items-start gap-3 text-white/45 text-xs max-w-md"><Icon name="shield-check" className="w-4 h-4 shrink-0 mt-0.5 text-gold" /><span>{t("21+ verified members only. Be respectful — every profile is a real guest. Report & block available on every chat.", "Solo miembros verificados 21+. Sé respetuoso — cada perfil es un invitado real. Reportar y bloquear disponible en cada chat.")}</span></div>
        </div>
      </div>

      {/* MATCH overlay */}
      {match && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center px-6" style={{ background: "rgba(8,8,10,.82)", backdropFilter: "blur(8px)" }} onClick={() => setMatch(null)}>
          <div className="fade-view text-center max-w-sm" onClick={(e) => e.stopPropagation()}>
            <div className="text-coral font-black uppercase tracking-[0.3em] text-sm mb-4 animate-pulse">{t("It's a match", "Es un match")}</div>
            <h2 className="text-5xl md:text-6xl font-black uppercase leading-none mb-3" style={{ background: "linear-gradient(135deg,#FF2E88,#FF6B5B,#C9929A)", WebkitBackgroundClip: "text", backgroundClip: "text", color: "transparent" }}>{t("You & ", "Tú & ")}{match.name}</h2>
            <p className="text-white/65 mb-8">{t(`You both like each other. You're both at `, `Ambos se gustan. Los dos van a `)}<span className="text-white font-semibold">{L(match.going, lang)}</span>.</p>
            <div className="flex flex-col gap-3">
              <button onClick={() => setMatch(null)} className="py-4 rounded-full text-white text-[13px] font-bold uppercase tracking-[0.16em]" style={{ background: "linear-gradient(135deg,#FF2E88,#FF6B5B)", boxShadow: "0 10px 40px rgba(255,46,136,.4)" }}><Icon name="message-circle" className="w-4 h-4 inline mr-2" />{t("Send a message", "Enviar mensaje")}</button>
              <button onClick={() => setMatch(null)} className="py-3.5 rounded-full border border-white/20 text-white/80 text-[12px] font-bold uppercase tracking-[0.16em] hover:bg-white/5 transition-colors">{t("Keep swiping", "Seguir deslizando")}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------- DROPS — claimable free tickets (members) ---------- */
function DropsTab({ account, go }) {
  const t = useT(); const { lang } = useLang();
  const order = { free: 0, member: 1, vip: 2, black: 3 };
  const myRank = order[account.tier] ?? 0;
  const [claimed, setClaimed] = useState({});
  return (
    <div className="fade-view">
      <div className="flex items-center justify-between mb-5">
        <div><div className="label text-coral text-[10px] mb-1">{t("Live now", "En vivo")}</div><h3 className="text-2xl font-black uppercase">{t("Free Drops", "Drops Gratis")}</h3></div>
        <span className="text-white/45 text-xs">{t("Resets weekly", "Se reinicia cada semana")}</span>
      </div>
      <div className="grid md:grid-cols-2 gap-4">
        {window.PP.DROPS.map((d) => {
          const tierColor = { member: "#CBA35C", vip: "#FF6B5B", black: "#E9E4DA" }[d.tier];
          const eligible = myRank >= (order[d.tier] ?? 1);
          const isClaimed = claimed[d.id];
          return (
            <div key={d.id} className="relative rounded-2xl overflow-hidden border border-white/10 bg-card group">
              <div className="relative h-40 overflow-hidden">
                <img src={d.img} alt="" loading="lazy" className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" style={{ filter: "brightness(.55)" }} />
                <div className="absolute inset-0 bg-gradient-to-t from-card to-transparent"></div>
                <span className="absolute top-3 left-3 px-2.5 py-1 rounded-full text-[9px] font-bold uppercase tracking-wider" style={{ background: tierColor + "22", color: tierColor, border: `1px solid ${tierColor}66` }}>{d.tier}</span>
                <span className="absolute top-3 right-3 px-2.5 py-1 rounded-full bg-black/55 backdrop-blur text-[9px] font-bold uppercase tracking-wider text-white/80">{d.left} {t("left", "quedan")}</span>
              </div>
              <div className="p-5">
                <h4 className="font-black uppercase text-lg leading-tight mb-1">{L(d.title, lang)}</h4>
                <div className="text-white/50 text-xs flex items-center gap-2 mb-4"><Icon name="calendar" className="w-3 h-3" />{L(d.night, lang)} · {L(d.when, lang)}</div>
                {eligible ? (
                  isClaimed ? (
                    <div className="flex items-center justify-center gap-2 py-3 rounded-full bg-[#5FBFA8]/15 border border-[#5FBFA8]/40 text-[#5FBFA8] text-[12px] font-bold uppercase tracking-wider"><Icon name="check-circle" className="w-4 h-4" />{t("Claimed — check Wallet", "Reclamado — ve a Billetera")}</div>
                  ) : (
                    <button onClick={() => setClaimed((c) => ({ ...c, [d.id]: true }))} className="gbtn w-full py-3 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-wider transition-all flex items-center justify-center gap-2"><Icon name="ticket" className="w-4 h-4" />{t("Claim free", "Reclamar gratis")}</button>
                  )
                ) : (
                  <button onClick={() => go("membership")} className="w-full py-3 rounded-full border border-white/15 text-white/65 text-[12px] font-bold uppercase tracking-wider hover:bg-white/5 transition-colors flex items-center justify-center gap-2"><Icon name="lock" className="w-3.5 h-3.5" />{t(`Unlock with ${d.tier}`, `Desbloquea con ${d.tier}`)}</button>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- INVITE — bring your people (members) ---------- */
function InviteTab({ account }) {
  const t = useT();
  const [copied, setCopied] = useState(false);
  const code = "PONY-" + account.handle.replace("@", "").toUpperCase();
  const friends = [
    { n: "Mariana", s: "joined", pts: 250 },
    { n: "Tomás", s: "pending" },
    { n: "Carla", s: "joined", pts: 250 },
  ];
  return (
    <div className="fade-view max-w-3xl">
      <div className="rounded-3xl border border-coral/30 bg-gradient-to-br from-coral/10 to-grape/10 p-7 mb-6">
        <div className="label text-coral text-[10px] mb-2">{t("Guest list power", "Poder de guest list")}</div>
        <h3 className="text-2xl md:text-3xl font-black uppercase mb-2">{t("Invite your crew, earn rewards", "Invita a tu gente, gana premios")}</h3>
        <p className="text-white/65 text-sm mb-6 max-w-lg">{t("You have", "Tienes")} <span className="text-white font-bold">{account.invitesLeft} {t("guest-list spots", "lugares en guest list")}</span> {t("this month. Each friend who joins earns you 250 points + skip-the-line for both of you.", "este mes. Cada amigo que se une te da 250 puntos + sin fila para ambos.")}</p>
        <div className="flex flex-col sm:flex-row gap-3">
          <div className="flex-1 flex items-center gap-3 bg-ink border border-white/12 rounded-full px-5 py-3.5">
            <Icon name="link" className="w-4 h-4 text-white/40" />
            <span className="font-mono text-sm tracking-wider flex-1 truncate">{code}</span>
          </div>
          <button onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1600); }} className="gbtn px-7 py-3.5 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-wider transition-all flex items-center justify-center gap-2">
            <Icon name={copied ? "check" : "copy"} className="w-4 h-4" />{copied ? t("Copied", "Copiado") : t("Copy invite", "Copiar")}
          </button>
        </div>
        <div className="flex gap-3 mt-4">
          {[["message-circle", "WhatsApp"], ["instagram", "Instagram"], ["share-2", t("Share", "Compartir")]].map(([ic, lbl], i) => (
            <button key={i} className="flex items-center gap-2 px-4 py-2.5 rounded-full border border-white/12 text-white/75 text-xs font-semibold hover:bg-white/5 transition-colors"><Icon name={ic} className="w-4 h-4" />{lbl}</button>
          ))}
        </div>
      </div>
      <div className="label text-white/45 text-[10px] mb-3">{t("Your invites", "Tus invitaciones")}</div>
      <div className="space-y-2.5">
        {friends.map((f, i) => (
          <div key={i} className="flex items-center gap-4 p-4 rounded-2xl border border-white/10 bg-card">
            <div className="w-10 h-10 rounded-full bg-white/8 flex items-center justify-center font-bold text-white/80">{f.n[0]}</div>
            <div className="flex-1"><div className="font-semibold text-sm">{f.n}</div><div className="text-white/45 text-xs">{f.s === "joined" ? t("Joined · +" + f.pts + " pts", "Se unió · +" + f.pts + " pts") : t("Invite sent", "Invitación enviada")}</div></div>
            <Chip color={f.s === "joined" ? "#5FBFA8" : "#CBA35C"}>{f.s === "joined" ? t("Active", "Activo") : t("Pending", "Pendiente")}</Chip>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { LockGate, PonyMatch, DropsTab, InviteTab });
