// community.jsx — Comunidad Coolcase: live counter, IG follow, shared feed, Operaria credit
// exposes: CommunityView

function useCountUp(target, dur = 1400) {
  const [n, setN] = React.useState(target);
  const prev = React.useRef(target);
  React.useEffect(() => {
    const from = prev.current;
    const to = target;
    if (from === to) return;
    let raf, start;
    const tick = (ts) => {
      if (!start) start = ts;
      const p = Math.min(1, (ts - start) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      setN(Math.round(from + (to - from) * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
      else prev.current = to;
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, dur]);
  return n;
}

function CounterBlock({ count }) {
  const display = useCountUp(count);
  return (
    <div className="glass-strong rise" style={{
      borderRadius: 32, padding: "44px 40px", textAlign: "center", position: "relative", overflow: "hidden",
      maxWidth: 560, margin: "0 auto 26px",
    }}>
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(60% 80% at 50% 0%, rgba(255,61,240,0.18), transparent 70%)", pointerEvents: "none" }}/>
      <span className="eyebrow" style={{ position: "relative" }}>Carcasas personalizadas creadas</span>
      <div style={{ position: "relative", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(60px, 11vw, 104px)", lineHeight: 1, margin: "14px 0 6px", letterSpacing: "-0.04em" }} className="grad-text">
        {display.toLocaleString("es-CL")}
      </div>
      <p style={{ position: "relative", color: "var(--ink-70)", fontSize: 15.5, maxWidth: 380, margin: "0 auto" }}>
        Cada carcasa de la comunidad es única. El contador sube con cada pedido — el próximo puede ser el tuyo.
      </p>
    </div>
  );
}

function PostCard({ post, index, onDelete }) {
  const [liked, setLiked] = React.useState(false);
  const likes = post.likes + (liked ? 1 : 0);
  const model = CC.models.find((m) => m.id === post.modelId) || CC.models[0];
  const mine = post.user === "@tú";
  return (
    <div className="glass rise" style={{ borderRadius: 22, overflow: "hidden", animationDelay: index * 0.04 + "s" }}>
      {/* header */}
      <div className="row" style={{ gap: 10, padding: "12px 14px" }}>
        <div style={{ width: 34, height: 34, borderRadius: "50%", background: "var(--grad-neon)", padding: 2 }}>
          <div style={{ width: "100%", height: "100%", borderRadius: "50%", background: "var(--bg-2)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 700 }}>{post.user[1]?.toUpperCase()}</div>
        </div>
        <div className="col" style={{ flex: 1, lineHeight: 1.2 }}>
          <span style={{ fontSize: 13.5, fontWeight: 600 }}>{post.user}</span>
          <span style={{ fontSize: 11, color: "var(--ink-50)" }}>{model.name}{post.fromPurchase ? " · compró 🛍" : ""}</span>
        </div>
        {mine ? (
          <button onClick={() => onDelete && onDelete(post.id)} title="Eliminar mi publicación" style={{ background: "var(--glass-bg)", border: "1px solid var(--glass-border)", borderRadius: "50%", width: 30, height: 30, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", color: "var(--ink-70)" }}>
            <Icon name="trash" size={15} />
          </button>
        ) : (
          <Icon name="instagram" size={18} stroke="var(--ink-50)" />
        )}
      </div>
      {/* image — phone on gradient (story-like) */}
      <div style={{ position: "relative", aspectRatio: "4 / 5", background: post.backdrop || "linear-gradient(160deg,#241a52,#0d0a22)", display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden" }}>
        <div style={{ position: "absolute", inset: 0, background: "radial-gradient(circle at 50% 40%, rgba(255,255,255,0.10), transparent 60%)" }}/>
        <div style={{ transform: "rotate(-6deg)", filter: "drop-shadow(0 20px 40px rgba(0,0,0,0.5))" }}>
          <PhoneCase model={model} design={post.design} scale={0.34} />
        </div>
      </div>
      {/* actions */}
      <div className="row" style={{ gap: 16, padding: "11px 14px 4px" }}>
        <button onClick={() => setLiked(!liked)} style={{ background: "none", border: "none", cursor: "pointer", padding: 0, color: liked ? "var(--neon-magenta)" : "var(--ink)" }}>
          <Icon name="heart" size={22} fill={liked ? "var(--neon-magenta)" : "none"} stroke={liked ? "var(--neon-magenta)" : "var(--ink)"} />
        </button>
        <Icon name="share" size={20} stroke="var(--ink)" />
      </div>
      <div style={{ padding: "0 14px 14px" }}>
        <span style={{ fontSize: 13, fontWeight: 600 }}>{likes.toLocaleString("es-CL")} me gusta</span>
        <p style={{ fontSize: 13.5, color: "var(--ink-70)", margin: "5px 0 0", lineHeight: 1.45 }}>
          <span style={{ color: "var(--ink)", fontWeight: 600 }}>{post.user}</span> {post.caption}
        </p>
      </div>
    </div>
  );
}

function CommunityView({ count, posts, onFollow, onDeletePost }) {
  return (
    <div className="page section-pad">
      <div className="col" style={{ alignItems: "center", textAlign: "center", marginBottom: 44 }}>
        <span className="eyebrow rise" style={{ marginBottom: 18 }}>Comunidad Coolcase</span>
        <h1 className="display rise" style={{ fontSize: "clamp(40px, 6vw, 74px)", animationDelay: "0.05s" }}>Hecho por la comunidad</h1>
      </div>

      <CounterBlock count={count} />

      <div className="row rise" style={{ justifyContent: "center", marginBottom: 64, animationDelay: "0.1s" }}>
        <button className="btn btn-neon" onClick={onFollow} style={{ padding: "15px 28px", fontSize: 16 }}>
          <Icon name="instagram" size={20} /> Síguenos · @cool.case.cl
        </button>
      </div>

      <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-end", marginBottom: 24 }}>
        <h2 style={{ fontSize: 26 }}>Compartido por ustedes</h2>
        <span style={{ fontSize: 13.5, color: "var(--ink-50)" }}>{posts.length} publicaciones</span>
      </div>

      <div style={{ columnWidth: 280, columnGap: 22 }}>
        {posts.map((p, i) => (
          <div key={p.id} style={{ breakInside: "avoid", marginBottom: 22 }}>
            <PostCard post={p} index={i} onDelete={onDeletePost} />
          </div>
        ))}
      </div>

      {/* footer credit */}
      <div className="row" style={{ justifyContent: "space-between", alignItems: "center", marginTop: 80, paddingTop: 28, borderTop: "1px solid var(--glass-border)", flexWrap: "wrap", gap: 16 }}>
        <span style={{ fontSize: 13.5, color: "var(--ink-50)" }}>
          Diseñado por <a href="https://operaria.cl" target="_blank" rel="noopener" style={{ color: "var(--ink-70)", textDecoration: "none", borderBottom: "1px solid var(--ink-30)" }}>Operaria</a>
        </span>
        <a className="btn" href="https://wa.me/56900000000" target="_blank" rel="noopener" style={{ padding: "11px 20px", fontSize: 14, background: "rgba(61,255,168,0.12)", border: "1px solid rgba(61,255,168,0.4)", color: "#eafff5", textDecoration: "none" }}>
          <Icon name="whatsapp" size={18} stroke="#3dffa8" /> Contáctanos por WhatsApp
        </a>
      </div>
    </div>
  );
}

Object.assign(window, { CommunityView });
