/* creatives.jsx — creative gallery with SVG mock ad thumbnails
   and inline-play behavior for videos. */

const { useState: useStateC } = React;

/* ===================================================================
   AD VISUALS — each is a self-contained SVG that looks like a real ad
   creative (product hero, before/after, promo, etc).
   No external images — these are stylised mock creatives in brand DNA.
   =================================================================== */
function AdVisual({ visual, animated }) {
  const sw = {
    "linen-sofa":    <LinenSofaVisual animated={animated}/>,
    "promo-sale":    <PromoSaleVisual animated={animated}/>,
    "before-after":  <BeforeAfterVisual animated={animated}/>,
    "carousel":      <CarouselVisual animated={animated}/>,
    "testimonial":   <TestimonialVisual animated={animated}/>,
    "pattern-drop":  <PatternDropVisual animated={animated}/>,
    "room-tour":     <RoomTourVisual animated={animated}/>,
    "free-ship":     <FreeShipVisual animated={animated}/>
  };
  return sw[visual] || null;
}

/* All visuals share a 400×500 viewBox so they fit a 4:5 thumbnail.
   They're stylised mock ads — not photoreal — but read clearly as
   shoppable creative when scaled down. */

function LinenSofaVisual({ animated }) {
  return (
    <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
      <defs>
        <linearGradient id="ls-bg" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="#1a0033"/>
          <stop offset="60%" stopColor="#4E34FE"/>
          <stop offset="100%" stopColor="#7600FF"/>
        </linearGradient>
        <radialGradient id="ls-glow" cx="50%" cy="60%" r="60%">
          <stop offset="0%" stopColor="rgba(255,255,255,.25)"/>
          <stop offset="100%" stopColor="rgba(255,255,255,0)"/>
        </radialGradient>
      </defs>
      <rect width="400" height="500" fill="url(#ls-bg)"/>
      <ellipse cx="200" cy="300" rx="180" ry="120" fill="url(#ls-glow)"/>
      {/* Stylised linen sofa */}
      <g transform="translate(60, 230)">
        <rect x="0" y="60" width="280" height="80" rx="14" fill="#e8d8b8"/>
        <rect x="-8" y="80" width="296" height="20" rx="6" fill="#1a0033"/>
        <rect x="8" y="40" width="80" height="60" rx="10" fill="#f4e4c0"/>
        <rect x="98" y="36" width="80" height="64" rx="10" fill="#f4e4c0"/>
        <rect x="188" y="40" width="80" height="60" rx="10" fill="#f4e4c0"/>
        <rect x="-2" y="98" width="14" height="40" rx="4" fill="#3a2810"/>
        <rect x="268" y="98" width="14" height="40" rx="4" fill="#3a2810"/>
      </g>
      {/* Headline */}
      <g transform="translate(28, 60)">
        <text fontFamily="Gotham, sans-serif" fontWeight="900" fontSize="38" fill="#fff" letterSpacing="-1.2">
          <tspan x="0" y="0">LINHO</tspan>
          <tspan x="0" y="38">PLUMA</tspan>
        </text>
        <text fontFamily="Gotham, monospace" fontWeight="500" fontSize="11" fill="#A8A8A8" letterSpacing="2.2" x="0" y="62">SOFÁ-CAMA · CAIXA</text>
      </g>
      {/* Bottom CTA pill */}
      <g transform="translate(28, 430)">
        <rect width="180" height="42" rx="21" fill="#fff"/>
        <text fontFamily="Gotham" fontWeight="900" fontSize="13" fill="#000" letterSpacing="2" x="90" y="27" textAnchor="middle">COMPRAR AGORA</text>
      </g>
      <text fontFamily="Gotham" fontWeight="900" fontSize="20" fill="#fff" x="372" y="465" textAnchor="end">25%</text>
      {animated && <rect x="0" y={Math.random()*450} width="400" height="50" fill="rgba(255,255,255,.04)">
        <animate attributeName="y" from="-50" to="500" dur="3.4s" repeatCount="indefinite"/>
      </rect>}
    </svg>
  );
}

function PromoSaleVisual({ animated }) {
  return (
    <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
      <defs>
        <linearGradient id="ps-bg" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="#EF1166"/>
          <stop offset="60%" stopColor="#CE3EBA"/>
          <stop offset="100%" stopColor="#7600FF"/>
        </linearGradient>
      </defs>
      <rect width="400" height="500" fill="url(#ps-bg)"/>
      {/* Big -25% */}
      <text fontFamily="Gotham" fontWeight="900" fontSize="240" fill="#fff" x="200" y="290" textAnchor="middle" letterSpacing="-12">−25%</text>
      <g transform="translate(40, 60)">
        <text fontFamily="Gotham" fontWeight="700" fontSize="11" fill="#fff" letterSpacing="3" opacity=".85">PROMOÇÃO RELÂMPAGO</text>
        <text fontFamily="Gotham" fontWeight="900" fontSize="28" fill="#fff" letterSpacing="-.5" y="32">SÓ ATÉ DOMINGO</text>
      </g>
      <g transform="translate(40, 390)">
        <text fontFamily="Gotham" fontWeight="700" fontSize="14" fill="#fff" letterSpacing=".5">Linho Pluma · todas as cores</text>
        <text fontFamily="Gotham, monospace" fontWeight="500" fontSize="11" fill="#fff" letterSpacing="2" y="22" opacity=".75">CUPOM PLUMA25 · NA SACOLA</text>
      </g>
      <g transform="translate(40, 442)">
        <rect width="320" height="38" rx="19" fill="#000"/>
        <text fontFamily="Gotham" fontWeight="900" fontSize="12" fill="#fff" letterSpacing="2" x="160" y="24" textAnchor="middle">APROVEITAR AGORA →</text>
      </g>
    </svg>
  );
}

function BeforeAfterVisual({ animated }) {
  return (
    <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
      <defs>
        <linearGradient id="ba-bg" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="#FF7F00"/>
          <stop offset="100%" stopColor="#EF1166"/>
        </linearGradient>
      </defs>
      <rect width="400" height="500" fill="url(#ba-bg)"/>
      {/* Two rooms side by side */}
      <g transform="translate(0, 80)">
        {/* Before */}
        <g transform="translate(20, 0)">
          <rect width="170" height="240" rx="12" fill="#1a1a1a"/>
          <rect x="20" y="120" width="130" height="90" rx="6" fill="#3a3a3a"/>
          <rect x="40" y="60" width="80" height="50" fill="#2a2a2a"/>
          <text fontFamily="Gotham" fontWeight="900" fontSize="11" fill="#fff" letterSpacing="2.5" x="85" y="232" textAnchor="middle">ANTES</text>
        </g>
        {/* After */}
        <g transform="translate(210, 0)">
          <rect width="170" height="240" rx="12" fill="#f0e0c8"/>
          <rect x="20" y="120" width="130" height="90" rx="6" fill="#c8a878"/>
          <rect x="40" y="60" width="80" height="50" fill="#8a6a3a"/>
          <circle cx="60" cy="50" r="20" fill="#FF7F00"/>
          <text fontFamily="Gotham" fontWeight="900" fontSize="11" fill="#000" letterSpacing="2.5" x="85" y="232" textAnchor="middle">DEPOIS</text>
        </g>
      </g>
      {/* Headline at top */}
      <g transform="translate(20, 40)">
        <text fontFamily="Gotham" fontWeight="900" fontSize="22" fill="#fff" letterSpacing="-.5">7 DIAS · 1 ENTREGA</text>
      </g>
      {/* Bottom strip */}
      <g transform="translate(20, 380)">
        <text fontFamily="Gotham" fontWeight="900" fontSize="14" fill="#fff">"Mudou minha sala."</text>
        <text fontFamily="Gotham" fontWeight="500" fontSize="11" fill="#fff" y="20" opacity=".82">— Maria S., SP</text>
      </g>
      <g transform="translate(20, 432)">
        <rect width="180" height="38" rx="19" fill="#000"/>
        <text fontFamily="Gotham" fontWeight="900" fontSize="11" fill="#fff" letterSpacing="2" x="90" y="24" textAnchor="middle">VER MAIS HISTÓRIAS</text>
      </g>
    </svg>
  );
}

function CarouselVisual({ animated }) {
  const colors = ["#e8d8b8", "#a8786c", "#3a4858", "#c8a878", "#1a2030", "#8c6c4c"];
  return (
    <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
      <defs>
        <linearGradient id="ca-bg" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="#00E7FF"/>
          <stop offset="60%" stopColor="#2E79FF"/>
          <stop offset="100%" stopColor="#4E34FE"/>
        </linearGradient>
      </defs>
      <rect width="400" height="500" fill="url(#ca-bg)"/>
      <g transform="translate(20, 60)">
        <text fontFamily="Gotham" fontWeight="900" fontSize="26" fill="#fff" letterSpacing="-.5">SEIS TONS QUE</text>
        <text fontFamily="Gotham" fontWeight="900" fontSize="26" fill="#fff" letterSpacing="-.5" y="30">COMBINAM. DE VERDADE.</text>
      </g>
      {/* 6 color swatches in a 3×2 grid */}
      <g transform="translate(20, 160)">
        {colors.map((c, i) => {
          const row = Math.floor(i/3), col = i%3;
          return (
            <g key={i} transform={`translate(${col*125}, ${row*145})`}>
              <rect width="115" height="135" rx="10" fill={c}/>
              <text fontFamily="Gotham, monospace" fontWeight="500" fontSize="9" fill={i < 3 ? "#000" : "#fff"} letterSpacing="1.5" x="10" y="125" opacity=".75">0{i+1} / 06</text>
            </g>
          );
        })}
      </g>
      {/* dots indicator */}
      <g transform="translate(200, 470)">
        {[0,1,2,3,4,5].map(i => (
          <circle key={i} cx={i*16 - 40} cy="0" r={i===0 ? 5 : 3} fill="#fff" opacity={i===0 ? 1 : 0.4}/>
        ))}
      </g>
    </svg>
  );
}

function TestimonialVisual({ animated }) {
  return (
    <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
      <defs>
        <linearGradient id="ts-bg" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="#0a0014"/>
          <stop offset="50%" stopColor="#3a0070"/>
          <stop offset="100%" stopColor="#7600FF"/>
        </linearGradient>
      </defs>
      <rect width="400" height="500" fill="url(#ts-bg)"/>
      {/* Person silhouette circle */}
      <g transform="translate(150, 100)">
        <circle cx="50" cy="50" r="55" fill="#000" opacity=".4"/>
        <circle cx="50" cy="50" r="52" fill="none" stroke="rgba(255,255,255,.4)" strokeWidth="1.5"/>
        <circle cx="50" cy="40" r="18" fill="rgba(255,255,255,.85)"/>
        <path d="M15 95 Q50 60 85 95" fill="rgba(255,255,255,.85)"/>
      </g>
      {/* Quote */}
      <g transform="translate(28, 240)">
        <text fontFamily="Gotham" fontWeight="900" fontSize="60" fill="#CE3EBA" y="0" opacity=".8">"</text>
        <text fontFamily="Gotham" fontWeight="700" fontSize="20" fill="#fff" letterSpacing="-.3" y="38" textLength="350">Não pareço mais</text>
        <text fontFamily="Gotham" fontWeight="700" fontSize="20" fill="#fff" letterSpacing="-.3" y="62">profissional —</text>
        <text fontFamily="Gotham" fontWeight="900" fontSize="20" fill="#00E7FF" letterSpacing="-.3" y="88">sou profissional.</text>
      </g>
      {/* Attribution */}
      <g transform="translate(28, 410)">
        <text fontFamily="Gotham" fontWeight="900" fontSize="13" fill="#fff" letterSpacing=".5">Camila R.</text>
        <text fontFamily="Gotham" fontWeight="500" fontSize="11" fill="#fff" opacity=".7" y="18">Decoradora · São Paulo</text>
      </g>
      <g transform="translate(28, 460)">
        <text fontFamily="Gotham, monospace" fontWeight="500" fontSize="10" fill="#00E7FF" letterSpacing="2">★★★★★</text>
      </g>
    </svg>
  );
}

function PatternDropVisual({ animated }) {
  return (
    <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
      <defs>
        <linearGradient id="pd-bg" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="#FF7F00"/>
          <stop offset="100%" stopColor="#c84a00"/>
        </linearGradient>
        <pattern id="pd-pat" x="0" y="0" width="50" height="50" patternUnits="userSpaceOnUse">
          <circle cx="25" cy="25" r="6" fill="#fff" opacity=".15"/>
          <circle cx="0" cy="0" r="3" fill="#fff" opacity=".25"/>
        </pattern>
      </defs>
      <rect width="400" height="500" fill="url(#pd-bg)"/>
      <rect width="400" height="500" fill="url(#pd-pat)"/>
      {/* MANGA tag */}
      <g transform="translate(28, 70)">
        <rect width="74" height="20" rx="10" fill="#000"/>
        <text fontFamily="Gotham" fontWeight="900" fontSize="9" fill="#FF7F00" letterSpacing="2" x="37" y="14" textAnchor="middle">NOVA COLAB</text>
      </g>
      <g transform="translate(28, 110)">
        <text fontFamily="Gotham" fontWeight="900" fontSize="58" fill="#fff" letterSpacing="-2.5">MANGA</text>
        <text fontFamily="Gotham" fontWeight="900" fontSize="58" fill="#000" letterSpacing="-2.5" y="58">BRANCA.</text>
      </g>
      {/* Object */}
      <g transform="translate(80, 280)">
        <rect width="240" height="160" rx="14" fill="#fff" opacity=".95"/>
        <path d="M30 130 Q120 30 210 130" fill="#FF7F00"/>
        <circle cx="180" cy="60" r="18" fill="#000"/>
      </g>
      <g transform="translate(28, 470)">
        <text fontFamily="Gotham, monospace" fontWeight="500" fontSize="10" fill="#fff" letterSpacing="2">PRÉ-VENDA · 30 MAI →</text>
      </g>
    </svg>
  );
}

function RoomTourVisual({ animated }) {
  return (
    <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
      <defs>
        <linearGradient id="rt-bg" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="#0a0014"/>
          <stop offset="60%" stopColor="#2E79FF"/>
          <stop offset="100%" stopColor="#4E34FE"/>
        </linearGradient>
      </defs>
      <rect width="400" height="500" fill="url(#rt-bg)"/>
      {/* 12 numbered tiles */}
      <g transform="translate(20, 90)">
        {Array.from({length: 12}).map((_,i) => {
          const r = Math.floor(i/3), c = i%3;
          const shades = ["#8a7a5c", "#3a4858", "#a8886c", "#2a3848", "#c8a878", "#3a2818",
                          "#5a6878", "#a87858", "#1a2030", "#d8c8a8", "#4a5868", "#684838"];
          return (
            <g key={i} transform={`translate(${c*120}, ${r*88})`}>
              <rect width="110" height="78" rx="6" fill={shades[i]}/>
              <text fontFamily="Gotham" fontWeight="900" fontSize="11" fill="#fff" letterSpacing="2.5" x="9" y="20">0{i+1}</text>
            </g>
          );
        })}
      </g>
      <g transform="translate(20, 50)">
        <text fontFamily="Gotham" fontWeight="900" fontSize="22" fill="#fff" letterSpacing="-.3">12 AMBIENTES.</text>
      </g>
      <g transform="translate(20, 460)">
        <text fontFamily="Gotham" fontWeight="700" fontSize="13" fill="#fff" opacity=".75">Inspire-se. Compre os looks.</text>
      </g>
    </svg>
  );
}

function FreeShipVisual({ animated }) {
  return (
    <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
      <defs>
        <linearGradient id="fs-bg" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="#00E7FF"/>
          <stop offset="100%" stopColor="#fff"/>
        </linearGradient>
      </defs>
      <rect width="400" height="500" fill="url(#fs-bg)"/>
      <g transform="translate(28, 80)">
        <rect width="100" height="24" rx="12" fill="#000"/>
        <text fontFamily="Gotham" fontWeight="900" fontSize="10" fill="#fff" letterSpacing="2" x="50" y="17" textAnchor="middle">FRETE GRÁTIS</text>
      </g>
      <g transform="translate(28, 130)">
        <text fontFamily="Gotham" fontWeight="900" fontSize="62" fill="#000" letterSpacing="-3">ACIMA DE</text>
        <text fontFamily="Gotham" fontWeight="900" fontSize="120" fill="#000" letterSpacing="-7" y="124">R$999</text>
      </g>
      {/* Truck */}
      <g transform="translate(60, 360)">
        <rect width="160" height="80" rx="8" fill="#000"/>
        <rect x="160" y="20" width="60" height="60" rx="6" fill="#000"/>
        <circle cx="50" cy="90" r="14" fill="#000"/>
        <circle cx="50" cy="90" r="6" fill="#fff"/>
        <circle cx="200" cy="90" r="14" fill="#000"/>
        <circle cx="200" cy="90" r="6" fill="#fff"/>
        <text fontFamily="Gotham" fontWeight="900" fontSize="14" fill="#fff" letterSpacing="2" x="80" y="50" textAnchor="middle">NUVEM &amp; CO.</text>
      </g>
      <g transform="translate(28, 470)">
        <text fontFamily="Gotham, monospace" fontWeight="500" fontSize="10" fill="#000" letterSpacing="2.5">TODO O BRASIL · ENTREGA EM 5 DIAS</text>
      </g>
    </svg>
  );
}

/* ===================================================================
   CREATIVE CARD
   =================================================================== */
function CreativeCard({ creative, lang, isPlaying, onPlay, onTagsChange, tagOptions }) {
  const headline = lang === "pt" ? creative.headline_pt : creative.headline_en;
  const roas = lang === "pt" ? creative.roas.pt : creative.roas.en;
  const spend = lang === "pt" ? creative.spend.pt : creative.spend.en;
  const ctr = lang === "pt" ? creative.ctr : creative.ctr_en;

  const isVideo = creative.type === "video";

  return (
    <article
      className={"creative" + (isPlaying ? " is-playing" : "")}
    >
      <div className="creative__thumb" style={{background: creative.bg}}
           onClick={() => isVideo && onPlay(creative.id)}>
        <div className="creative__thumb-bg">
          <AdVisual visual={creative.visual} animated={isPlaying}/>
        </div>
        {/* Static overlays only when not playing */}
        {!isPlaying && (
          <>
            <span className="creative__rank">#{creative.rank}</span>
            <span className={"creative__badge " + (isVideo ? "video" : "")}>
              <Icon name={isVideo ? "video" : "image"} size={11}/>
              {isVideo ? "VIDEO" : "STATIC"}
            </span>
            {isVideo && (
              <div className="creative__play">
                <div className="creative__play-btn">
                  <Icon name="play" size={22}/>
                </div>
              </div>
            )}
            {isVideo && creative.duration && (
              <span className="creative__duration">{creative.duration}</span>
            )}
          </>
        )}
        {isPlaying && (
          <>
            <div className="now-playing-pill">
              <span className="np-bars"><span/><span/><span/><span/></span>
              {lang === "pt" ? "TOCANDO" : "PLAYING"}
            </div>
            {/* progress bar */}
            <div style={{
              position: "absolute", left: 0, right: 0, bottom: 0,
              height: 3, background: "rgba(0,0,0,.4)", zIndex: 4
            }}>
              <div style={{
                height: "100%", width: "0%",
                background: "var(--mk-acqua)",
                animation: "video-progress 18s linear infinite"
              }}/>
            </div>
          </>
        )}
        <div className="creative__thumb-overlay"/>
        {!isPlaying && (
          <div className="creative__caption">{headline}</div>
        )}
      </div>

      <div className="creative__body">
        <div className="creative__top">
          <span className="creative__platform">
            <Icon name={creative.icon || "meta"} size={12}/>
            {creative.platform}
          </span>
          <span className="creative__id">{creative.id}</span>
        </div>

        {/* Concept tags — manual tagging */}
        {onTagsChange ? (
          <TagPicker
            tags={creative.tags || []}
            options={tagOptions || []}
            onChange={(tags) => onTagsChange(creative.id, tags)}
            lang={lang}
            size="sm"
            placement="above"
          />
        ) : null}

        <div className="creative__stats">
          <div>
            <div className="creative__stat-l">ROAS</div>
            <div className={"creative__stat-v " + (creative.roas_dir === "down" ? "neg" : "pos")}>{roas}</div>
          </div>
          <div>
            <div className="creative__stat-l">{t("kpi.spend", lang)}</div>
            <div className="creative__stat-v">{spend}</div>
          </div>
          <div>
            <div className="creative__stat-l">CTR</div>
            <div className="creative__stat-v">{ctr}</div>
          </div>
        </div>
      </div>
    </article>
  );
}
window.CreativeCard = CreativeCard;

function CreativeGrid({ creatives, lang, onTagsChange, tagOptions }) {
  const [playing, setPlaying] = useStateC(null);
  return (
    <div className="creative-grid">
      {creatives.map(c => (
        <CreativeCard
          key={c.id}
          creative={c}
          lang={lang}
          isPlaying={playing === c.id}
          onPlay={(id) => setPlaying(playing === id ? null : id)}
          onTagsChange={onTagsChange}
          tagOptions={tagOptions}
        />
      ))}
    </div>
  );
}
window.CreativeGrid = CreativeGrid;

/* Inject keyframes for video progress bar */
if (typeof document !== "undefined" && !document.getElementById("video-kf")) {
  const s = document.createElement("style");
  s.id = "video-kf";
  s.textContent = "@keyframes video-progress { from { width: 0%; } to { width: 100%; } }";
  document.head.appendChild(s);
}
