/* global React, Reveal, Star, Asterisk, TremendoLogo */
const { useState } = React;

// ──────────────────────────────────────────────────────────
// SERVICIOS page — interactive carousel-style pricing
// ──────────────────────────────────────────────────────────

const APPS_IMPRESOS = [
  { text: "Tarjetas de presentación" },
  { text: "Postal de agradecimiento" },
  { text: "Hoja membretada" },
  { text: "Formato de cotización", pro: true },
  { text: "Tarjetas de lealtad" },
  { text: "Folder" },
  { text: "Menú", pro: true },
  { text: "Empaques", pro: true },
  { text: "Papel envoltura" },
  { text: "Stickers" },
  { text: "Etc." },
];
const APPS_DIGITALES = [
  { text: "Firma de correo" },
  { text: "Diseño de datos de pago" },
  { text: "Presentaciones", pro: true },
  { text: "Catálogo de servicios", pro: true },
  { text: "Menú digital", pro: true },
];

function AppItem({ a }) {
  return (
    <li>
      {a.text}
      {a.pro && <span className="apps-pro">(Pro)</span>}
    </li>
  );
}

function AppsModal({ pkg, onClose }) {
  const showPro = pkg.tier !== "TR-1";
  const impresos = showPro ? APPS_IMPRESOS : APPS_IMPRESOS.filter(a => !a.pro);
  const digitales = showPro ? APPS_DIGITALES : APPS_DIGITALES.filter(a => !a.pro);
  return ReactDOM.createPortal(
    <div className="apps-overlay" onClick={onClose}>
      <div className="apps-modal" onClick={e => e.stopPropagation()}>
        <button className="apps-close" onClick={onClose} aria-label="Cerrar">✕</button>
        <div className="apps-body">
        <p className="apps-title">Aplicaciones disponibles</p>
        <div className="apps-cols">
          <div>
            <p className="eyebrow apps-col-head">Impresos</p>
            <ul className="apps-list">
              {impresos.map((a, i) => <AppItem key={i} a={a} />)}
            </ul>
          </div>
          <div>
            <p className="eyebrow apps-col-head">Digitales</p>
            <ul className="apps-list">
              {digitales.map((a, i) => <AppItem key={i} a={a} />)}
            </ul>
          </div>
        </div>
        </div>
        {pkg.appsImage &&
          <img className="apps-img" src={pkg.appsImage} alt={"Ejemplo de aplicaciones del paquete " + pkg.name} />
        }
      </div>
    </div>,
    document.body
  );
}

const BRANDING_PKG = [
{ tier: "TR-1", name: "Starter", subtitle: "Diseño de branding", price: "$15,000", unit: "MXN + IVA", tag: "más elegido", appsImage: "/assets/apps-starter.webp",
  blurb: "Para marcas que están dando sus primeros pasos y quieren comenzar con una identidad clara y profesional.",
  features: ["Concepto estratégico de marca", "2 propuestas de logotipo y variantes", "Paleta de color", "Tipografías", "2 Aplicaciones básicas [apps]", "Manual de identidad"] },
{ tier: "TR-2", name: "Premium", subtitle: "Diseño de branding completo", price: "$18,000", unit: "MXN + IVA", tag: "pro", appsImage: "/assets/apps-premium.webp",
  blurb: "Para marcas listas que buscan desarrollar una identidad completa y versátil.",
  features: ["Concepto estratégico de marca", "2 propuestas de logotipo y variantes", "Paleta de color", "Tipografías", "5 Aplicaciones Pro [apps]", "Manual de identidad"] }];


const CONTENT_PKG = [
{ tier: "TR-1", name: "Pack Básico de Contenido", price: "$8,200", unit: "MXN + IVA / mes", tag: "básico",
  blurb: "El impulso visual que tu feed necesita para empezar a verte profesional en redes.",
  features: ["10 artes estáticos", "2 videos editados", "Producción de contenido digital (precio extra)"],
  savings: "+ $2,000 MXN por 3 horas de producción de contenido digital\n(Video y contenido para redes sociales)" },
{ tier: "TR-2", name: "Pack Plus de Contenido", price: "$12,500", unit: "MXN + IVA / mes", tag: "el sweet spot",
  blurb: "Para cuando tu marca está lista para crecer más rápido.",
  features: ["15 artes estáticos", "4 videos editados", "6 stories interactivos", "Producción de contenido digital (precio extra)"],
  savings: "+ $2,000 MXN por 3 horas de producción de contenido digital\n(Video y contenido para redes sociales)" },
{ tier: "TR-3", name: "Pack Premium de Contenido", price: "$15,000", unit: "MXN + IVA / mes", tag: "pro",
  blurb: "Para estar siempre presente en todos lados.",
  features: ["20 artes estáticos", "6 videos profesionales", "8 stories interactivos", "Estrategia personalizada", "Producción de contenido digital (precio extra)", "Reporte de métricas mensual"],
  savings: "+ $2,000 MXN por 3 horas de producción de contenido digital\n(Video y contenido para redes sociales)" }];


// ──────────────────────────────────────────────────────────
// Carousel — featured card center, side cards muted
// ──────────────────────────────────────────────────────────
function PkgCarousel({ pkgs, variant, eyebrow, title, subtitle, accent = "var(--orange)", logoColor = "white" }) {
  const [active, setActive] = useState(0);
  const [appsPkg, setAppsPkg] = useState(null);

  const go = (dir) => {
    setActive((a) => (a + dir + pkgs.length) % pkgs.length);
  };

  return (
    <section className={"carousel-block " + (variant === "dark" ? "dark" : "light")}>
      <Reveal className="carousel-head">
        <div>
          <span className="eyebrow" style={{ color: variant === "dark" ? "var(--orange)" : "var(--burnt)" }}>
            {eyebrow}
          </span>
          <h2 className="display carousel-h">
            <TremendoLogo color={logoColor} /> <span style={{ color: accent }}>{title}</span>
          </h2>
          <p className="carousel-sub">{subtitle}</p>
        </div>
        <div className="carousel-controls">
          <button onClick={() => go(-1)} className="cc-btn hoverable" aria-label="Anterior" data-cursor="prev">
            ←
          </button>
          <span className="cc-count display">
            {String(active + 1).padStart(2, "0")}
            <span className="cc-slash">/</span>
            {String(pkgs.length).padStart(2, "0")}
          </span>
          <button onClick={() => go(1)} className="cc-btn hoverable" aria-label="Siguiente" data-cursor="next">
            →
          </button>
        </div>
      </Reveal>

      {appsPkg && <AppsModal pkg={appsPkg} onClose={() => setAppsPkg(null)} />}

      <div className="carousel-stage">
        {pkgs.map((p, i) => {
          const offset = i - active;
          const wrap = offset > pkgs.length / 2 ? offset - pkgs.length :
          offset < -pkgs.length / 2 ? offset + pkgs.length : offset;
          const isActive = wrap === 0;
          return (
            <PkgCard
              key={p.tier}
              pkg={p}
              isActive={isActive}
              wrap={wrap}
              variant={variant}
              accent={accent}
              onAppsClick={() => setAppsPkg(p)}
              onClick={() => !isActive && setActive(i)} />);
        })}
      </div>

      {/* Dots */}
      <div className="carousel-dots">
        {pkgs.map((p, i) =>
        <button
          key={i}
          className={"dot hoverable " + (i === active ? "on" : "")}
          onClick={() => setActive(i)}
          aria-label={"Ver " + p.name}
          data-cursor="ver">
          
            <span className="dot-tier eyebrow">{p.tier}</span>
            <span className="dot-name">{p.name}</span>
          </button>
        )}
      </div>
    </section>);

}

function renderFeat(f, onAppsClick) {
  if (!f.includes("[apps]")) return f;
  const [before] = f.split("[apps]");
  return (
    <span className="pkg-feat-apps">
      {before}
      <button className="apps-trigger" onClick={e => { e.stopPropagation(); onAppsClick(); }}>
        (Materiales impresos o digitales)
      </button>
    </span>
  );
}

function PkgCard({ pkg, isActive, wrap, variant, accent, onClick, onAppsClick }) {
  const isSide = !isActive;
  const dir = wrap < 0 ? "left" : wrap > 0 ? "right" : "center";

  return (
    <div
      className={
      "pkg-card hoverable" + (
      isActive ? " active" : " side") +
      " side-" + dir
      }
      onClick={onClick}
      data-cursor={isSide ? "ver" : "elegir"}
      style={{
        "--accent": accent,
        zIndex: isActive ? 10 : 5
      }}>
      
      {/* Featured circle stamp on active */}
      {isActive && pkg.tag === "más elegido" &&
      <div className="pkg-stamp" aria-hidden="true">
          <svg viewBox="0 0 100 100" width="92" height="92">
            <defs>
              <path id={"c-" + pkg.tier} d="M50,50 m-38,0 a38,38 0 1,1 76,0 a38,38 0 1,1 -76,0" />
            </defs>
            <text fill="var(--cream)" fontFamily="var(--display)" fontSize="11" letterSpacing="2">
              <textPath href={"#c-" + pkg.tier}>MÁS ELEGIDO · MÁS ELEGIDO ·</textPath>
            </text>
          </svg>
          <span className="pkg-stamp-star">✦</span>
        </div>
      }

      <div className="pkg-card-top">
        <span className="eyebrow pkg-tier">{pkg.tier}</span>
        <span className="pkg-tag serif-ital">{pkg.tag === "más elegido" ? "" : pkg.tag}</span>
      </div>

      <h3 className="display pkg-name">{pkg.name}</h3>
      {pkg.subtitle && <p className="pkg-subtitle">{pkg.subtitle}</p>}

      {isActive &&
      <>
          <div className="pkg-price-row">
            <span className="display pkg-price">{pkg.price}</span>
            <span className="pkg-unit">{pkg.unit}</span>
          </div>
          <p className="serif-ital pkg-blurb">{pkg.blurb}</p>
          <div className="pkg-divider" />
          <ul className="pkg-feats">
            {pkg.features.map((f, i) =>
          <li key={i} style={{ animationDelay: i * 60 + "ms" }}>
                <Asterisk size={11} />
                {renderFeat(f, onAppsClick)}
              </li>
          )}
          </ul>
          {pkg.savings && (
            <div className="pkg-savings">
              <span className="pkg-savings-icon">✦</span>
              <p className="pkg-savings-text">
                {pkg.savings.split("\n").map((line, i, arr) => (
                  <React.Fragment key={i}>
                    {line}
                    {i < arr.length - 1 && <br />}
                  </React.Fragment>
                ))}
              </p>
            </div>
          )}
          <a
            className="btn pkg-btn"
            href={"https://wa.me/525548900185?text=" + encodeURIComponent("Hola! Me interesa el paquete " + pkg.name + (pkg.subtitle ? " (" + pkg.subtitle + ")" : "") + " de Tremendo Studio 🙌")}
            target="_blank"
            rel="noopener noreferrer">
            Lo quiero <Star size={12} />
          </a>
        </>
      }

      {!isActive &&
      <>
          <p className="pkg-side-hint">
            <span className="pkg-side-price">{pkg.price}</span>
            <span className="pkg-side-cta">click para ver <span className="pkg-side-arrow">→</span></span>
          </p>
        </>
      }
    </div>);

}

// ──────────────────────────────────────────────────────────
// Academia — keep as is (user already direct-edited it)
// ──────────────────────────────────────────────────────────
function Academia() {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);
  return (
    <section className="academia">
      <Reveal className="academia-card">
        <div className="academia-left">
          <span className="stamp academia-stamp">Coming · Soon</span>
          <h2 className="display academia-h">
            Academia <br />
            <span className="serif-ital" style={{ color: "var(--orange)" }}>Tremenda</span>
          </h2>
          <p className="academia-lede">
            Muy pronto compartiremos todo lo que sabemos sobre diseño,
            creatividad y cómo sobrevivir al mundo creativo sin morir en el intento.
          </p>
          <ul className="academia-list">
            <li><Asterisk size={11} /> Cursos online en vivo</li>
            <li><Asterisk size={11} /> Templates y plantillas editables</li>
            <li><Asterisk size={11} /> Comunidad privada para emprendedoras</li>
          </ul>
          {!sent ?
          <form className="academia-form" onSubmit={(e) => {e.preventDefault();if (email) setSent(true);}}>
              <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="tu@correo.com" />
              <button className="btn" type="submit">Avísenme <Star size={12} /></button>
            </form> :

          <p className="academia-sent serif-ital">✦ Listo. Te avisamos en cuanto abra el telón.</p>
          }
        </div>
        <div className="academia-right" aria-hidden="true" />
      </Reveal>
    </section>);

}

function Servicios({ go }) {
  return (
    <div className="page-servicios tab-enter">
      <section className="page-hero">
        <Reveal>
          <span className="eyebrow" style={{ color: "var(--orange)" }}>✦ Servicios / 02</span>
          <h1 className="display page-hero-h" style={{ fontSize: "clamp(2.5rem, 6vw, 6rem)" }}>
            Tu marca no nació <br />
            para ser <span style={{ color: "var(--orange)" }}>una más.</span>
          </h1>
          <p className="page-hero-lede">
            El mercado está lleno de lo mismo y tú necesitas conectar de verdad con una identidad sólida y una comunicación auténtica.
          </p>
        </Reveal>
      </section>

      <PkgCarousel
        pkgs={BRANDING_PKG}
        variant="light"
        eyebrow="✦ 01 · Identidad"
        title="Branding"
        subtitle="Construimos identidades que se notan y se quedan."
        accent="var(--burnt)" />
      

      <PkgCarousel
        pkgs={CONTENT_PKG}
        variant="dark"
        eyebrow="✦ 02 · Redes"
        title="Content"
        subtitle={<>Estética implacable para redes sociales.<br className="line-break-desktop" /> Sin gestión de comunidad, solo arte puro.</>}
        accent="var(--cream)" />
      

      <Academia />

      <section className="page-foot">
        <Reveal>
          <h3 className="display page-foot-h">
            ¿No sabes cuál es el <span style={{ color: "var(--orange)" }}>tuyo?</span>
          </h3>
          <p>Escríbenos y te ayudamos a encontrar el ideal para tu marca.</p>
          <button className="btn" onClick={() => go("hablemos")}>
            Hablemos <Star size={12} />
          </button>
        </Reveal>
      </section>
    </div>);

}

Object.assign(window, { Servicios });