// Notifications.jsx — header bell + notifications page.
// Plus Reviews modal flow for delivered orders.

const { useState: useNotifState } = React;

const NOTIFICATIONS = [
  { id: "n1", type: "order", icon: "local_shipping", color: "var(--primary)",       fg: "var(--primary-soft)",  title: "Tu pedido #AL-711981 va en camino",          sub: "Llega hoy entre 10:00 y 18:00",        t: "hace 12 min", unread: true,  href: ["order", { id: "AL-711981" }] },
  { id: "n2", type: "promo", icon: "favorite",       color: "#B691FF",              fg: "rgba(182,145,255,.16)",title: "Tenis Running UltraBoost ahora −24%",         sub: "El producto de tu lista bajó a $1,899",t: "hace 1 h",   unread: true,  href: ["pdp",   { id: "p005" }] },
  { id: "n3", type: "review",icon: "star",           color: "var(--star)",           fg: "rgba(247,207,82,.18)", title: "Reseña tu compra de Crema hidratante",       sub: "¿Cómo te fue con el producto?",       t: "hace 3 h",   unread: true,  action: "review", productId: "p003" },
  { id: "n4", type: "order", icon: "check_circle",   color: "var(--success)",       fg: "var(--success-bg)",    title: "Pedido #AL-712304 entregado",                sub: "Te dejamos PIN 8432 con el repartidor",t: "hace 1 d",   unread: false, href: ["order", { id: "AL-712304" }] },
  { id: "n5", type: "system",icon: "verified",       color: "var(--primary)",       fg: "var(--primary-soft)",  title: "Tu cuenta es ahora Allen Prime gratis",      sub: "30 días con envío en 24 h y cashback 3%", t: "hace 2 d",  unread: false, href: ["prime"] },
  { id: "n6", type: "promo", icon: "credit_card",    color: "var(--primary)",       fg: "var(--primary-soft)",  title: "Tu tarjeta •••• 4242 fue cargada con $1,560",sub: "Pedido #AL-712802 confirmado",        t: "hace 4 d",   unread: false },
  { id: "n7", type: "order", icon: "support_agent",  color: "#8A6500",              fg: "var(--warning-bg)",    title: "Disputa #D-2835 abierta",                    sub: "Allen Ops está revisando tu caso",    t: "hace 5 d",   unread: false },
];

// =====================================================================
// NotificationBell — header trigger with unread badge + dropdown panel.
const NotificationBell = ({ onNav, onReview }) => {
  const [open, setOpen] = useNotifState(false);
  const [items, setItems] = useNotifState(NOTIFICATIONS);
  const unread = items.filter(n => n.unread).length;

  const markRead = (id) => setItems(arr => arr.map(n => n.id === id ? { ...n, unread: false } : n));
  const markAllRead = () => setItems(arr => arr.map(n => ({ ...n, unread: false })));

  const onClick = (n) => {
    markRead(n.id);
    setOpen(false);
    if (n.action === "review") onReview?.(n.productId);
    else if (n.href) onNav(...n.href);
  };

  return (
    <div style={{ position: "relative" }}>
      <button onClick={() => setOpen(o => !o)} aria-label="Notificaciones"
        style={{ background: "transparent", border: 0, padding: 10, borderRadius: "9999px", cursor: "pointer", color: "var(--fg-strong)", display: "grid", placeItems: "center", position: "relative" }}
        onMouseEnter={e => e.currentTarget.style.background = "var(--bg-elev-2)"}
        onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
        <BellIcon size={22} />
        {unread > 0 && (
          <span style={{ position: "absolute", top: 4, right: 4, minWidth: 18, height: 18, padding: "0 5px", borderRadius: 9, background: "var(--error)", color: "#fff", font: "700 10px/18px var(--font-sans)", textAlign: "center", border: "2px solid var(--bg-elev-1)" }}>{unread}</span>
        )}
      </button>

      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 90 }} />
          <div style={{
            position: "absolute", top: "calc(100% + 10px)", right: 0,
            width: 400, maxHeight: 540, background: "var(--bg-elev-1)",
            borderRadius: "var(--radius-lg)", boxShadow: "var(--elev-pop)",
            border: "1px solid var(--border-soft)",
            display: "flex", flexDirection: "column", overflow: "hidden", zIndex: 100,
            animation: "popIn .18s var(--ease-out-quart)",
          }}>
            <style>{`@keyframes popIn { from { opacity: 0; transform: translateY(-4px) } to { opacity: 1; transform: translateY(0) } }`}</style>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 20px", borderBottom: "1px solid var(--border-soft)" }}>
              <h3 className="title-sm">Notificaciones</h3>
              <button onClick={markAllRead} style={{ background: "transparent", border: 0, color: "var(--primary)", font: "700 12px var(--font-sans)", cursor: "pointer" }}>Marcar todas leídas</button>
            </div>
            <div style={{ flex: 1, overflowY: "auto" }}>
              {items.slice(0, 5).map(n => <NotifRow key={n.id} n={n} onClick={onClick} />)}
            </div>
            <button onClick={() => { setOpen(false); onNav("notifications"); }}
              style={{ padding: "14px", background: "var(--bg-elev-2)", border: 0, borderTop: "1px solid var(--border-soft)", color: "var(--primary)", font: "700 13px var(--font-sans)", cursor: "pointer" }}>
              Ver todas las notificaciones →
            </button>
          </div>
        </>
      )}
    </div>
  );
};

const NotifRow = ({ n, onClick }) => (
  <button onClick={() => onClick(n)} style={{
    width: "100%", padding: "14px 18px", background: n.unread ? "var(--primary-soft)" : "transparent",
    border: 0, borderBottom: "1px solid var(--border-soft)",
    display: "flex", gap: 12, alignItems: "flex-start", cursor: "pointer", textAlign: "left",
    transition: "background var(--dur-fast)",
  }}>
    <span style={{ width: 36, height: 36, borderRadius: 18, background: n.fg, display: "grid", placeItems: "center", flexShrink: 0 }}>
      <AllenIcon name={n.icon} size={18} color={n.color} fill={n.type === "review" || n.type === "system"} />
    </span>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ font: n.unread ? "700 13px var(--font-sans)" : "500 13px var(--font-sans)", color: "var(--fg-strong)", lineHeight: 1.35 }}>{n.title}</div>
      <div className="body-sm" style={{ marginTop: 2, fontSize: 12 }}>{n.sub}</div>
      <div style={{ marginTop: 6, font: "500 11px var(--font-sans)", color: "var(--fg-subtle)", display: "flex", alignItems: "center", gap: 6 }}>
        {n.unread && <span style={{ width: 6, height: 6, borderRadius: 3, background: "var(--primary)" }} />}
        {n.t}
      </div>
    </div>
  </button>
);

const BellIcon = ({ size = 22 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
    <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
  </svg>
);

// =====================================================================
// NotificationsPage — full inbox view (linked from "Ver todas")
const NotificationsPage = ({ onNav, onReview }) => {
  const [filter, setFilter] = useNotifState("all");
  const [items, setItems] = useNotifState(NOTIFICATIONS);
  const filtered = filter === "all" ? items : filter === "unread" ? items.filter(n => n.unread) : items.filter(n => n.type === filter);
  const markRead = (id) => setItems(arr => arr.map(n => n.id === id ? { ...n, unread: false } : n));
  return (
    <div style={{ maxWidth: 880, margin: "0 auto", padding: "0 32px" }}>
      <Breadcrumb items={["Inicio", "Notificaciones"]} />
      <h1 className="display-sm" style={{ marginBottom: 8 }}>Notificaciones</h1>
      <p className="body-sm" style={{ marginBottom: 24 }}>{items.filter(n => n.unread).length} sin leer · {items.length} en total</p>

      <div style={{ display: "flex", gap: 8, marginBottom: 16, overflowX: "auto", paddingBottom: 4 }}>
        {[
          { id: "all",    l: "Todas" },
          { id: "unread", l: `Sin leer (${items.filter(n => n.unread).length})` },
          { id: "order",  l: "Pedidos" },
          { id: "promo",  l: "Promos" },
          { id: "review", l: "Reseñas" },
          { id: "system", l: "Sistema" },
        ].map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)}
            style={{
              flexShrink: 0, padding: "8px 14px", borderRadius: "9999px",
              background: filter === f.id ? "var(--hub-black)" : "var(--bg-elev-1)",
              color: filter === f.id ? "#fff" : "var(--fg-strong)",
              border: filter === f.id ? 0 : "1px solid var(--border)",
              font: filter === f.id ? "700 12px var(--font-sans)" : "500 12px var(--font-sans)",
              cursor: "pointer",
            }}>{f.l}</button>
        ))}
      </div>

      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", overflow: "hidden" }}>
        {filtered.length === 0 ? (
          <div style={{ padding: 64, textAlign: "center" }}>
            <BellIcon size={40} />
            <h3 className="title-lg" style={{ marginTop: 14 }}>Nada por aquí</h3>
            <p className="body-sm" style={{ marginTop: 6 }}>Te avisamos cuando algo pase con tus pedidos o tus favoritos.</p>
          </div>
        ) : (
          filtered.map(n => (
            <NotifRow key={n.id} n={n} onClick={(x) => { markRead(x.id); if (x.action === "review") onReview?.(x.productId); else if (x.href) onNav(...x.href); }} />
          ))
        )}
      </div>
    </div>
  );
};

// =====================================================================
// ReviewModal — post-delivery "Califica tu compra" flow.
const ReviewModal = ({ productId, onClose }) => {
  const [stars, setStars] = useNotifState(0);
  const [hover, setHover] = useNotifState(0);
  const [text, setText]   = useNotifState("");
  const [tags, setTags]   = useNotifState(new Set());
  const [done, setDone]   = useNotifState(false);
  const toast = useToast();
  const product = CATALOG.find(p => p.id === productId) || CATALOG[0];

  const tagPool = stars >= 4
    ? ["Calidad excelente", "Llegó rapidísimo", "Empaque cuidado", "Tal cual la foto", "Lo recomiendo"]
    : stars > 0
    ? ["Calidad baja", "Llegó tarde", "Empaque dañado", "No es como la foto", "Caro para lo que es"]
    : [];

  const toggleTag = (t) => {
    const next = new Set(tags);
    next.has(t) ? next.delete(t) : next.add(t);
    setTags(next);
  };

  const submit = () => {
    setDone(true);
    setTimeout(() => { onClose(); toast("Reseña publicada · gracias por ayudar"); }, 1400);
  };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.55)", zIndex: 200, display: "grid", placeItems: "center", padding: 24, animation: "fadeIn .2s var(--ease-out-quart)" }}>
      <style>{`@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }`}</style>
      <div onClick={e => e.stopPropagation()} style={{ background: "var(--bg-elev-1)", borderRadius: "var(--radius-xl)", maxWidth: 540, width: "100%", padding: 32, boxShadow: "var(--elev-pop)" }}>
        {!done ? (
          <>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 24 }}>
              <div>
                <div className="label-sm" style={{ color: "var(--primary)" }}>Califica tu compra</div>
                <h2 className="headline-sm" style={{ marginTop: 4 }}>¿Cómo te fue?</h2>
              </div>
              <button onClick={onClose} aria-label="Cerrar" style={{ width: 36, height: 36, borderRadius: 18, background: "var(--bg-elev-2)", border: 0, cursor: "pointer", display: "grid", placeItems: "center", color: "var(--fg-strong)" }}>
                <AllenIcon name="close" size={18} />
              </button>
            </div>

            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 24, padding: 14, background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)" }}>
              <div style={{ width: 56, height: 56, borderRadius: "var(--radius-sm)", overflow: "hidden", background: product.imgBg, flexShrink: 0 }}>
                <img src={product.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="title-sm">{product.name}</div>
                <div className="body-sm" style={{ marginTop: 2 }}>{product.brand}</div>
              </div>
            </div>

            {/* Star rating */}
            <div style={{ display: "flex", justifyContent: "center", gap: 8, marginBottom: 20 }}>
              {[1,2,3,4,5].map(i => (
                <button key={i}
                  onClick={() => setStars(i)}
                  onMouseEnter={() => setHover(i)}
                  onMouseLeave={() => setHover(0)}
                  style={{ background: "transparent", border: 0, cursor: "pointer", padding: 4 }}
                  aria-label={`${i} estrellas`}>
                  <AllenIcon name="star" size={48} fill={i <= (hover || stars)} color={i <= (hover || stars) ? "var(--star)" : "var(--border-strong)"} />
                </button>
              ))}
            </div>
            {stars > 0 && (
              <div style={{ textAlign: "center", marginBottom: 20, font: "600 14px var(--font-sans)", color: "var(--fg-strong)" }}>
                {["", "Muy mala", "Mala", "Aceptable", "Buena", "Excelente"][stars]}
              </div>
            )}

            {/* Tags */}
            {stars > 0 && (
              <div style={{ marginBottom: 16 }}>
                <div className="label" style={{ marginBottom: 10 }}>¿Qué te llamó la atención?</div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {tagPool.map(t => (
                    <button key={t} onClick={() => toggleTag(t)}
                      style={{
                        padding: "8px 14px", borderRadius: "9999px",
                        background: tags.has(t) ? "var(--primary)" : "var(--bg-elev-2)",
                        color: tags.has(t) ? "#fff" : "var(--fg-strong)",
                        border: tags.has(t) ? 0 : "1px solid var(--border)",
                        font: tags.has(t) ? "700 12px var(--font-sans)" : "500 12px var(--font-sans)",
                        cursor: "pointer",
                      }}>
                      {tags.has(t) ? "✓ " : ""}{t}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* Free text */}
            <div style={{ marginBottom: 8 }}>
              <label className="label" style={{ display: "block", marginBottom: 6 }}>Cuéntale a otros compradores (opcional)</label>
              <textarea value={text} onChange={e => setText(e.target.value)} maxLength={500} rows={4}
                placeholder="Lo bueno, lo no tan bueno, lo que esperabas…"
                style={{ width: "100%", padding: "14px 16px", border: "1.5px solid var(--border-strong)", borderRadius: "var(--radius-input)", font: "400 14px var(--font-sans)", color: "var(--fg-strong)", background: "var(--bg-elev-1)", resize: "vertical", outline: "none", fontFamily: "var(--font-sans)" }} />
              <div style={{ font: "500 11px var(--font-sans)", color: "var(--fg-subtle)", marginTop: 4, textAlign: "right" }}>{text.length}/500</div>
            </div>

            {/* Photo upload (decorative) */}
            <div style={{ marginBottom: 20 }}>
              <button style={{
                display: "flex", alignItems: "center", gap: 8, padding: "12px 16px",
                background: "transparent", border: "1.5px dashed var(--border-strong)",
                borderRadius: "var(--radius-md)", color: "var(--fg-muted)", font: "600 13px var(--font-sans)", cursor: "pointer",
              }}>
                <AllenIcon name="add" size={16} /> Agregar fotos
                <span className="body-sm" style={{ fontSize: 11, color: "var(--fg-hint)" }}>Hasta 5 · JPG o PNG</span>
              </button>
            </div>

            <div style={{ display: "flex", gap: 12 }}>
              <button onClick={onClose} style={{ flex: 1, background: "transparent", color: "var(--fg-strong)", border: "1px solid var(--border-strong)", padding: "14px 20px", borderRadius: "9999px", font: "700 14px var(--font-sans)", cursor: "pointer" }}>Después</button>
              <PrimaryButton onClick={submit} style={{ flex: 2, opacity: stars === 0 ? .5 : 1, pointerEvents: stars === 0 ? "none" : "auto" }}>Publicar reseña</PrimaryButton>
            </div>
          </>
        ) : (
          <div style={{ textAlign: "center", padding: "32px 0" }}>
            <div style={{ width: 72, height: 72, borderRadius: 36, background: "var(--success-bg)", display: "grid", placeItems: "center", margin: "0 auto 18px", animation: "checkPop .4s var(--ease-out-quart)" }}>
              <style>{`@keyframes checkPop { from { transform: scale(0.6); opacity: 0 } to { transform: scale(1); opacity: 1 } }`}</style>
              <AllenIcon name="check_circle" size={44} fill color="var(--success)" />
            </div>
            <h3 className="headline-sm">¡Gracias por tu reseña!</h3>
            <p className="body" style={{ marginTop: 8, color: "var(--fg-muted)" }}>Ayuda a otros compradores a decidir.</p>
          </div>
        )}
      </div>
    </div>
  );
};

window.NotificationBell = NotificationBell;
window.NotificationsPage = NotificationsPage;
window.ReviewModal = ReviewModal;
