// data.jsx — shared constants, icons, and the phone-case renderer
// exposes to window: CC (data), Icon, PhoneCase, fmt

const fmt = (n) => "$" + n.toLocaleString("es-CL");

// ----------------------------------------------------------------
// DATA
// ----------------------------------------------------------------
const CC = {
  models: (typeof window !== "undefined" && window.PHONE_MODELS) ? window.PHONE_MODELS : [
    { id: "ip15pro", brand: "iPhone", name: "iPhone 15 Pro", price: 14990, notch: "dynamic", cam: "tri" },
  ],
  // preset designs — real artwork uploaded by COOLCASE
  designs: [
    { id: "cordillera", name: "Cordillera", cat: "Chile", author: "Coolcase",  price: 16990, img: "assets/pop-01-cordillera.png" },
    { id: "flamingo",   name: "Flamingo",   cat: "Pop",   author: "Coolcase",  price: 16990, img: "assets/pop-02-flamingo.png" },
    { id: "pisco",      name: "Pisco Sour", cat: "Chile", author: "Coolcase",  price: 16990, img: "assets/pop-03-pisco.png" },
    { id: "llama",      name: "Llamita",    cat: "Chile", author: "Coolcase",  price: 16990, img: "assets/pop-04-llama.png" },
    { id: "graffiti",   name: "Graffiti Hearts", cat: "Urbano", author: "Operaria", price: 18990, img: "assets/pop-05-graffiti.png" },
    { id: "mountain",   name: "Montaña",    cat: "Natura", author: "Coolcase",  price: 15990, img: "assets/nature-04-mountain.png" },
    { id: "citrus",     name: "Cítricos",   cat: "Natura", author: "Coolcase",  price: 15990, img: "assets/nature-05-citrus.png" },
    { id: "bling",      name: "Bling 3D",   cat: "Y2K",    author: "Estudio N", price: 18990, img: "assets/y2k-01-bling.png" },
    { id: "aura",       name: "Aura Pastel",cat: "Y2K",    author: "Estudio N", price: 17990, img: "assets/y2k-02-aura.png" },
    { id: "paint",      name: "Óleo",       cat: "Textura",author: "Operaria",  price: 17990, img: "assets/texture-04-paint.png" },
    { id: "glass",      name: "Glass Crack",cat: "Textura",author: "Coolcase",  price: 16990, img: "assets/texture-05-glass.png" },
    { id: "stripes",    name: "Rayas Neón", cat: "Urbano", author: "Coolcase",  price: 15990, img: "assets/type-01-stripes.png" },
    { id: "grunge",     name: "Grunge Type",cat: "Urbano", author: "Operaria",  price: 18990, img: "assets/type-02-grunge.png" },
  ],
  // solid case colors for the dock
  colors: ["#0d0a22", "#f3f0ff", "#ff3df0", "#8b5cff", "#2de2ff", "#3dffa8", "#ffd84d", "#ff7a3d", "#ff5470", "#1b9bff"],
  // pattern overlays (function of color)
  patterns: [
    { id: "none",  name: "Liso" },
    { id: "dots",  name: "Puntos" },
    { id: "grid",  name: "Grilla" },
    { id: "stripe",name: "Rayas" },
    { id: "waves", name: "Ondas" },
    { id: "stars", name: "Estrellas" },
  ],
  stickers: [
    { id: "daisy",     name: "Margarita", src: "assets/stk-daisy.png" },
    { id: "planet",    name: "Planeta",   src: "assets/stk-planet.png" },
    { id: "gameboy",   name: "Game Boy",  src: "assets/stk-gameboy.png" },
    { id: "boombox",   name: "Boombox",   src: "assets/stk-boombox.png" },
    { id: "cassette",  name: "Cassette",  src: "assets/stk-cassette.png" },
    { id: "camera",    name: "Cámara",    src: "assets/stk-camera.png" },
    { id: "car",       name: "Auto",      src: "assets/stk-car.png" },
    { id: "soda",      name: "Bebida",    src: "assets/stk-soda.png" },
    { id: "donut",     name: "Donut",     src: "assets/stk-donut.png" },
    { id: "icecream",  name: "Helado",    src: "assets/stk-icecream.png" },
    { id: "headphones",name: "Audífonos", src: "assets/stk-headphones.png" },
    { id: "skate",     name: "Skate",     src: "assets/stk-skate.png" },
    { id: "lipstick",  name: "Labial",    src: "assets/stk-lipstick.png" },
    { id: "bolt",      name: "Rayo",      src: "assets/stk-bolt.png" },
    { id: "floppy",    name: "Floppy",    src: "assets/stk-floppy.png" },
  ],
  accessories: [
    { id: "strap",  name: "Correa / cordón", price: 3990, icon: "strap",  desc: "Cordón ajustable cruzado" },
    { id: "magsafe",name: "Soporte MagSafe", price: 5990, icon: "magsafe",desc: "Anillo magnético integrado" },
    { id: "ring",   name: "Anillo soporte",  price: 4990, icon: "ring",   desc: "Grip giratorio 360°" },
    { id: "charm",  name: "Charms colgantes", price: 2990, icon: "charm",  desc: "Set de 3 dijes neón" },
    { id: "glitter",name: "Pajaritas glitter",price: 5990, icon: "spark",  desc: "Aplicación brillante" },
    { id: "stand",  name: "Kickstand",        price: 3490, icon: "stand",  desc: "Pie plegable invisible" },
  ],
  offers: [
    { id: "2x1",   tag: "2x1",   accent: "var(--neon-magenta)", title: "Lleva 2, paga 1", desc: "En carcasas seleccionadas de la galería.", until: "Válido hasta 30 jun" },
    { id: "pack",  tag: "-30%",  accent: "var(--neon-cyan)",    title: "Pack Accesorios", desc: "Correa + Anillo + Charm con 30% off.", until: "Solo hasta 15 jun" },
    { id: "envio", tag: "ENVÍO", accent: "var(--neon-purple)",  title: "Envío gratis",    desc: "Sobre $25.000 a todo Chile.", until: "Permanente" },
    { id: "first", tag: "-15%",  accent: "var(--neon-magenta)", title: "Primer diseño",   desc: "Descuento en tu primera carcasa personalizada.", until: "Para nuevos clientes" },
  ],
};

// ----------------------------------------------------------------
// ADMIN OVERRIDES — la administradora prende/apaga ítems, edita precios y ofertas.
// CC_FULL = catálogo original (nunca se filtra, lo lee el panel).
// CC      = vista pública, ya filtrada según lo guardado en localStorage.
// Muestra sin backend: todo vive en el navegador.
// ----------------------------------------------------------------
const CC_ADMIN_KEY = "coolcase_admin_v1";
const CC_FULL = JSON.parse(JSON.stringify(CC));

function ccLoadAdmin() {
  try { return JSON.parse(localStorage.getItem(CC_ADMIN_KEY)) || {}; }
  catch (e) { return {}; }
}
function ccSaveAdmin(s) { localStorage.setItem(CC_ADMIN_KEY, JSON.stringify(s)); }
function ccResetAdmin() { localStorage.removeItem(CC_ADMIN_KEY); }

(function ccApplyAdmin() {
  const a = ccLoadAdmin();
  const off = a.off || {};        // { designs:{id:true}, models:{}, accessories:{}, offers:{} }
  const price = a.price || {};    // { designs:{id:n}, models:{}, accessories:{} }
  const offerEdits = a.offers || {}; // { id:{tag,title,desc,until} }
  const priceFor = (g, it) => {
    const v = price[g] && price[g][it.id];
    return (v === undefined || v === null || v === "") ? it.price : Number(v);
  };
  const live = (g) => CC_FULL[g]
    .filter((it) => !(off[g] && off[g][it.id]))
    .map((it) => ({ ...it, price: priceFor(g, it) }));
  CC.designs     = live("designs");
  CC.models      = live("models");
  CC.accessories = live("accessories");
  CC.offers = CC_FULL.offers
    .filter((o) => !(off.offers && off.offers[o.id]))
    .map((o) => ({ ...o, ...(offerEdits[o.id] || {}) }));
})();

if (typeof window !== "undefined") {
  window.CC = CC; window.CC_FULL = CC_FULL;
  window.ccLoadAdmin = ccLoadAdmin; window.ccSaveAdmin = ccSaveAdmin; window.ccResetAdmin = ccResetAdmin;
}

// fonts to choose from in design panel
const TEXT_FONTS = [
  { id: "grotesk", label: "Display", css: '"Space Grotesk", sans-serif' },
  { id: "inter",   label: "Clean",   css: '"Inter", sans-serif' },
  { id: "mono",    label: "Mono",    css: '"Space Mono", monospace' },
  { id: "serif",   label: "Serif",   css: 'Georgia, serif' },
];

// ----------------------------------------------------------------
// ICONS  (stroke-based, 24x24)
// ----------------------------------------------------------------
function Icon({ name, size = 22, stroke = "currentColor", fill = "none", style }) {
  const p = { width: size, height: size, viewBox: "0 0 24 24", fill, stroke, strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", style };
  switch (name) {
    case "palette": return <svg {...p}><circle cx="12" cy="12" r="9"/><circle cx="8.5" cy="9" r="1.2" fill={stroke} stroke="none"/><circle cx="15.5" cy="9" r="1.2" fill={stroke} stroke="none"/><circle cx="9" cy="15" r="1.2" fill={stroke} stroke="none"/><path d="M14 14.5c2 0 3.5-.5 3.5 2 0 1.5-2.5 2-4 1"/></svg>;
    case "image": return <svg {...p}><rect x="3" y="4" width="18" height="16" rx="3"/><circle cx="8.5" cy="9.5" r="1.6"/><path d="m4 17 4.5-4 3.5 3 3-2.5L20 17"/></svg>;
    case "text": return <svg {...p}><path d="M5 6h14M5 6V5h14v1M12 6v13M9 19h6"/></svg>;
    case "accessory": return <svg {...p}><path d="M12 3v4M12 17v4M3 12h4M17 12h4"/><circle cx="12" cy="12" r="4"/></svg>;
    case "plus": return <svg {...p}><path d="M12 5v14M5 12h14"/></svg>;
    case "minus": return <svg {...p}><path d="M5 12h14"/></svg>;
    case "close": return <svg {...p}><path d="M6 6l12 12M18 6 6 18"/></svg>;
    case "cart": return <svg {...p}><path d="M3 4h2l2.2 11.5a1.5 1.5 0 0 0 1.5 1.2h8.1a1.5 1.5 0 0 0 1.5-1.2L21 8H6"/><circle cx="9" cy="20" r="1.3"/><circle cx="18" cy="20" r="1.3"/></svg>;
    case "share": return <svg {...p}><circle cx="6" cy="12" r="2.4"/><circle cx="18" cy="6" r="2.4"/><circle cx="18" cy="18" r="2.4"/><path d="m8.2 10.8 7.6-3.6M8.2 13.2l7.6 3.6"/></svg>;
    case "instagram": return <svg {...p}><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.2" cy="6.8" r="1.1" fill={stroke} stroke="none"/></svg>;
    case "whatsapp": return <svg {...p}><path d="M20 11.5a8 8 0 0 1-11.8 7L4 19.5l1.1-4A8 8 0 1 1 20 11.5Z"/><path d="M9 9.5c0 3 2.5 5.5 5.5 5.5.6 0 1-.5 1-1l-.2-1.2-2 .6c-.9-.4-1.7-1.2-2.1-2.1l.6-2L10.6 9c-.5 0-1.1.4-1.1 1 0-.3 0-.3-.5-.5Z" fill={stroke} stroke="none"/></svg>;
    case "arrow": return <svg {...p}><path d="M5 12h14M13 6l6 6-6 6"/></svg>;
    case "back": return <svg {...p}><path d="M19 12H5M11 6l-6 6 6 6"/></svg>;
    case "heart": return <svg {...p}><path d="M12 20s-7-4.3-9.3-8.3C1 8.5 2.6 5.5 5.7 5.5c1.8 0 3 1 4.3 2.5C11.3 6.5 12.5 5.5 14.3 5.5c3.1 0 4.7 3 3 6.2C19 15.7 12 20 12 20Z"/></svg>;
    case "spark": return <svg {...p}><path d="M12 3l1.6 5.4L19 10l-5.4 1.6L12 17l-1.6-5.4L5 10l5.4-1.6z"/></svg>;
    case "magsafe": return <svg {...p}><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="3"/></svg>;
    case "ring": return <svg {...p}><circle cx="12" cy="9" r="4"/><path d="M12 13v7M9 20h6"/></svg>;
    case "strap": return <svg {...p}><path d="M7 4v6a5 5 0 0 0 10 0V4"/><path d="M7 14c0 3 2 6 5 6s5-3 5-6"/></svg>;
    case "charm": return <svg {...p}><path d="M12 3v5"/><circle cx="8" cy="13" r="2.5"/><circle cx="16" cy="15" r="2"/></svg>;
    case "stand": return <svg {...p}><rect x="5" y="4" width="14" height="12" rx="2"/><path d="M9 16l-2 4M15 16l2 4"/></svg>;
    case "check": return <svg {...p}><path d="M5 12.5 10 17 19 7"/></svg>;
    case "drag": return <svg {...p}><circle cx="9" cy="6" r="1.1" fill={stroke} stroke="none"/><circle cx="15" cy="6" r="1.1" fill={stroke} stroke="none"/><circle cx="9" cy="12" r="1.1" fill={stroke} stroke="none"/><circle cx="15" cy="12" r="1.1" fill={stroke} stroke="none"/><circle cx="9" cy="18" r="1.1" fill={stroke} stroke="none"/><circle cx="15" cy="18" r="1.1" fill={stroke} stroke="none"/></svg>;
    case "wand": return <svg {...p}><path d="M5 19 16 8M15 5l1 2 2 1-2 1-1 2-1-2-2-1 2-1z"/></svg>;
    case "trash": return <svg {...p}><path d="M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"/></svg>;
    default: return null;
  }
}

// ----------------------------------------------------------------
// PATTERN backgrounds
// ----------------------------------------------------------------
function patternStyle(pattern, color) {
  const dot = color === "#0d0a22" ? "rgba(255,255,255,0.55)" : "rgba(255,255,255,0.42)";
  switch (pattern) {
    case "dots":  return { backgroundImage: `radial-gradient(${dot} 1.6px, transparent 1.8px)`, backgroundSize: "16px 16px" };
    case "grid":  return { backgroundImage: `linear-gradient(${dot} 1px, transparent 1px), linear-gradient(90deg, ${dot} 1px, transparent 1px)`, backgroundSize: "22px 22px" };
    case "stripe":return { backgroundImage: `repeating-linear-gradient(45deg, ${dot} 0 2px, transparent 2px 14px)` };
    case "waves": return { backgroundImage: `radial-gradient(circle at 50% 100%, transparent 18px, ${dot} 19px 20px, transparent 21px)`, backgroundSize: "40px 40px" };
    case "stars": return { backgroundImage: `radial-gradient(${dot} 1.2px, transparent 1.4px), radial-gradient(${dot} 1px, transparent 1.2px)`, backgroundSize: "30px 30px, 30px 30px", backgroundPosition: "0 0, 15px 15px" };
    default: return {};
  }
}

// ----------------------------------------------------------------
// PHONE CASE renderer
//   design = { base, pattern, design(presetBg), texts[], images[] }
//   interactive: drag texts/images when `editable`
// ----------------------------------------------------------------
function PhoneCase({ model, design, scale = 1, editable = false, onUpdate, selectedLayer, onSelectLayer }) {
  const W = 280, H = 580;
  const ref = React.useRef(null);
  const dragRef = React.useRef(null);

  const camMod = model?.cam || "tri";
  const baseFill = design.img
    ? { backgroundImage: `url(${design.img})`, backgroundSize: "cover", backgroundPosition: "center" }
    : design.design ? { background: design.design } : { background: design.base || "#0d0a22" };
  const pat = (design.design || design.img) ? {} : patternStyle(design.pattern, design.base || "#0d0a22");

  const startDrag = (e, layer, idx) => {
    if (!editable) return;
    e.stopPropagation();
    e.preventDefault();
    onSelectLayer && onSelectLayer({ type: layer, idx });
    const rect = ref.current.getBoundingClientRect();
    const pt = e.touches ? e.touches[0] : e;
    dragRef.current = { layer, idx, rect };
    const move = (ev) => {
      const p = ev.touches ? ev.touches[0] : ev;
      const x = ((p.clientX - rect.left) / rect.width) * 100;
      const y = ((p.clientY - rect.top) / rect.height) * 100;
      onUpdate && onUpdate(layer, idx, { x: Math.max(6, Math.min(94, x)), y: Math.max(6, Math.min(94, y)) });
    };
    const up = () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", up);
      window.removeEventListener("touchmove", move);
      window.removeEventListener("touchend", up);
    };
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseup", up);
    window.addEventListener("touchmove", move, { passive: false });
    window.addEventListener("touchend", up);
  };

  return (
    <div style={{ width: W * scale, height: H * scale, position: "relative" }}>
      <div ref={ref} style={{
        position: "absolute", top: 0, left: 0, width: W, height: H,
        transform: `scale(${scale})`, transformOrigin: "top left",
        borderRadius: 52, overflow: "hidden",
        boxShadow: "0 40px 90px -30px rgba(0,0,0,0.7), inset 0 0 0 2px rgba(255,255,255,0.12), inset 0 2px 14px rgba(255,255,255,0.18)",
        ...baseFill,
      }}>
        {/* pattern overlay */}
        <div style={{ position: "absolute", inset: 0, ...pat }}/>
        {/* glossy sheen */}
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(115deg, rgba(255,255,255,0.22), transparent 30%, transparent 75%, rgba(255,255,255,0.08))", pointerEvents: "none" }}/>

        {/* camera module */}
        <div style={{
          position: "absolute", top: 26, left: 26,
          width: camMod === "bar" ? 120 : 96, height: camMod === "bar" ? 50 : 96,
          borderRadius: camMod === "bar" ? 30 : 28,
          background: "linear-gradient(145deg, rgba(20,16,40,0.92), rgba(8,6,20,0.96))",
          border: "1px solid rgba(255,255,255,0.10)",
          boxShadow: "inset 0 2px 8px rgba(0,0,0,0.6)",
          display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "center", gap: 8, padding: 12,
        }}>
          {[...Array(camMod === "duo" ? 2 : 3)].map((_, i) => (
            <div key={i} style={{ width: camMod === "bar" ? 26 : 30, height: camMod === "bar" ? 26 : 30, borderRadius: "50%", background: "radial-gradient(circle at 35% 30%, #3a3658, #0a0818 70%)", border: "2px solid rgba(255,255,255,0.10)", boxShadow: "inset 0 0 6px rgba(120,120,255,0.4)" }}>
              <div style={{ width: 8, height: 8, borderRadius: "50%", background: "rgba(120,160,255,0.5)", margin: "6px auto" }}/>
            </div>
          ))}
        </div>
        {/* flash */}
        <div style={{ position: "absolute", top: 40, left: camMod === "bar" ? 156 : 132, width: 14, height: 14, borderRadius: "50%", background: "radial-gradient(circle,#fffbe6,#caa 60%,transparent)" }}/>

        {/* IMAGE layers */}
        {(design.images || []).map((img, i) => (
          <div key={"img" + i}
            onMouseDown={(e) => startDrag(e, "images", i)}
            onTouchStart={(e) => startDrag(e, "images", i)}
            style={{
              position: "absolute", left: img.x + "%", top: img.y + "%",
              width: img.size, height: img.size, transform: "translate(-50%,-50%)",
              borderRadius: img.shape === "circle" ? "50%" : 14, overflow: "hidden",
              backgroundImage: `url(${img.src})`, backgroundSize: "cover", backgroundPosition: "center",
              border: editable ? "1.5px dashed rgba(255,255,255,0.4)" : "none",
              cursor: editable ? "grab" : "default",
              boxShadow: "0 6px 18px rgba(0,0,0,0.4)",
              outline: selectedLayer && selectedLayer.type === "images" && selectedLayer.idx === i ? "2px solid var(--neon-cyan)" : "none",
            }}/>
        ))}

        {/* STICKER layers (transparent PNG cutouts) */}
        {(design.stickers || []).map((st, i) => (
          <div key={"stk" + i}
            onMouseDown={(e) => startDrag(e, "stickers", i)}
            onTouchStart={(e) => startDrag(e, "stickers", i)}
            style={{
              position: "absolute", left: st.x + "%", top: st.y + "%",
              width: st.size, height: st.size, transform: `translate(-50%,-50%) rotate(${st.rot || 0}deg)`,
              backgroundImage: `url(${st.src})`, backgroundSize: "contain", backgroundRepeat: "no-repeat", backgroundPosition: "center",
              cursor: editable ? "grab" : "default",
              filter: "drop-shadow(0 4px 8px rgba(0,0,0,0.35))",
              outline: selectedLayer && selectedLayer.type === "stickers" && selectedLayer.idx === i ? "2px solid var(--neon-cyan)" : "none",
              outlineOffset: 3,
            }}/>
        ))}

        {/* TEXT layers */}
        {(design.texts || []).map((t, i) => (
          <div key={"txt" + i}
            onMouseDown={(e) => startDrag(e, "texts", i)}
            onTouchStart={(e) => startDrag(e, "texts", i)}
            style={{
              position: "absolute", left: t.x + "%", top: t.y + "%",
              transform: "translate(-50%,-50%) rotate(" + (t.rot || 0) + "deg)",
              fontFamily: t.font, fontSize: t.size, fontWeight: t.weight || 700,
              color: t.color, whiteSpace: "nowrap", cursor: editable ? "grab" : "default",
              textShadow: t.glow ? `0 0 12px ${t.color}` : "none",
              padding: "2px 6px", letterSpacing: t.spacing || 0,
              outline: selectedLayer && selectedLayer.type === "texts" && selectedLayer.idx === i ? "2px solid var(--neon-cyan)" : "none",
              borderRadius: 6,
            }}>{t.value || "Texto"}</div>
        ))}

        {/* accessory: strap loop hint at bottom */}
        {design.accStrap && (
          <div style={{ position: "absolute", bottom: 18, left: "50%", transform: "translateX(-50%)", width: 46, height: 46, borderRadius: "50%", border: "3px solid rgba(255,255,255,0.5)", boxShadow: "0 0 14px rgba(255,255,255,0.3)" }}/>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CC, TEXT_FONTS, Icon, PhoneCase, patternStyle, fmt });
