// editor-panels.jsx — the 4 glassmorphing control panels for the editor
// exposes: DesignPanel, ImagePanel, TextPanel, AccessoryPanel

// ---- small shared control bits -------------------------------------
function Swatch({ color, active, onClick, size = 34 }) {
  return (
    <button onClick={onClick} title={color} style={{
      width: size, height: size, borderRadius: "50%", cursor: "pointer", flexShrink: 0,
      background: color, border: active ? "2.5px solid #fff" : "2px solid rgba(255,255,255,0.25)",
      boxShadow: active ? `0 0 0 3px rgba(255,255,255,0.18), 0 0 16px ${color}` : "inset 0 1px 3px rgba(0,0,0,0.3)",
      transition: "transform 0.15s ease, box-shadow 0.2s ease", transform: active ? "scale(1.08)" : "none",
    }}/>
  );
}

function PanelShell({ title, subtitle, children, onClose }) {
  return (
    <div className="glass-strong" style={{
      borderRadius: 26, padding: "22px 22px 20px", width: "100%", height: "100%",
      display: "flex", flexDirection: "column",
      boxShadow: "0 30px 70px -20px rgba(0,0,0,0.55), inset 0 1px 0 rgba(255,255,255,0.14)",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10, flexShrink: 0 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, lineHeight: 1.1 }}>{title}</div>
          {subtitle && <p style={{ fontSize: 13, color: "var(--ink-50)", margin: "8px 0 0", lineHeight: 1.4 }}>{subtitle}</p>}
        </div>
        {onClose && (
          <button onClick={onClose} style={{ background: "var(--glass-bg)", border: "1px solid var(--glass-border)", borderRadius: "50%", width: 32, height: 32, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", color: "var(--ink-70)", flexShrink: 0 }}>
            <Icon name="close" size={16} />
          </button>
        )}
      </div>
      <div style={{ height: 16, flexShrink: 0 }}/>
      <div style={{ overflowY: "auto", flex: 1, margin: "0 -22px", padding: "0 22px" }}>{children}</div>
    </div>
  );
}

const subLabel = { fontSize: 11.5, fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-50)", marginBottom: 10, display: "block" };

// ---- DESIGN / COLOR panel ------------------------------------------
function DesignPanel({ design, setDesign, onClose }) {
  const [genColors, setGenColors] = React.useState(["#ff3df0", "#8b5cff"]);
  const [genStyle, setGenStyle] = React.useState("linear");

  const applyPreset = (img) => setDesign((d) => ({ ...d, design: null, img }));
  const applyColor = (c) => setDesign((d) => ({ ...d, base: c, design: null, img: null }));
  const applyPattern = (p) => setDesign((d) => ({ ...d, pattern: p, design: null, img: null }));

  const toggleGen = (c) => setGenColors((arr) => arr.includes(c) ? arr.filter((x) => x !== c) : (arr.length >= 3 ? [...arr.slice(1), c] : [...arr, c]));
  const generate = () => {
    const cols = genColors.length ? genColors : ["#ff3df0", "#8b5cff"];
    let bg;
    if (genStyle === "radial") bg = `radial-gradient(120% 90% at 30% 20%, ${cols.join(",")})`;
    else if (genStyle === "conic") bg = `conic-gradient(from 200deg, ${cols.join(",")}, ${cols[0]})`;
    else bg = `linear-gradient(135deg, ${cols.join(",")})`;
    setDesign((d) => ({ ...d, design: bg, img: null }));
  };

  return (
    <PanelShell title="Color y diseños" subtitle="Parte de un prediseño COOLCASE, un color sólido o genera tu propio degradado." onClose={onClose}>
      <span style={subLabel}>Prediseños COOLCASE</span>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(54px,1fr))", gap: 10, marginBottom: 20 }}>
        {CC.designs.map((d) => (
          <button key={d.id} onClick={() => applyPreset(d.img)} title={d.name} style={{
            height: 72, borderRadius: 12, cursor: "pointer",
            backgroundImage: `url(${d.img})`, backgroundSize: "cover", backgroundPosition: "center",
            border: design.img === d.img ? "2.5px solid #fff" : "1px solid rgba(255,255,255,0.2)",
            boxShadow: design.img === d.img ? "0 0 14px rgba(255,255,255,0.4)" : "inset 0 1px 4px rgba(0,0,0,0.3)",
            transition: "transform 0.15s ease", transform: design.img === d.img ? "scale(1.04)" : "none",
          }}/>
        ))}
      </div>

      <span style={subLabel}>Color sólido</span>
      <div className="row" style={{ gap: 9, flexWrap: "wrap", marginBottom: 20 }}>
        {CC.colors.map((c) => <Swatch key={c} color={c} active={!design.design && design.base === c} onClick={() => applyColor(c)} />)}
      </div>

      <span style={subLabel}>Textura</span>
      <div className="row" style={{ gap: 8, flexWrap: "wrap", marginBottom: 22 }}>
        {CC.patterns.map((p) => {
          const active = !design.design && design.pattern === p.id;
          return (
            <button key={p.id} onClick={() => applyPattern(p.id)} style={{
              padding: "8px 14px", borderRadius: 999, cursor: "pointer", fontSize: 13, fontWeight: 600,
              background: active ? "var(--grad-neon)" : "var(--glass-bg)",
              border: active ? "1px solid transparent" : "1px solid var(--glass-border)", color: "#fff",
            }}>{p.name}</button>
          );
        })}
      </div>

      {/* generator */}
      <div style={{ background: "rgba(255,255,255,0.04)", border: "1px solid var(--glass-border)", borderRadius: 18, padding: 16 }}>
        <div className="row" style={{ gap: 8, marginBottom: 12 }}>
          <Icon name="wand" size={17} stroke="var(--neon-cyan)" />
          <span style={{ fontWeight: 700, fontSize: 14 }}>Generar degradado</span>
        </div>
        <span style={subLabel}>Elige 2–3 colores</span>
        <div className="row" style={{ gap: 8, flexWrap: "wrap", marginBottom: 14 }}>
          {CC.colors.slice(2).map((c) => <Swatch key={c} color={c} size={28} active={genColors.includes(c)} onClick={() => toggleGen(c)} />)}
        </div>
        <div className="row" style={{ gap: 8, marginBottom: 14 }}>
          {["linear", "radial", "conic"].map((s) => (
            <button key={s} onClick={() => setGenStyle(s)} style={{
              flex: 1, padding: "9px 0", borderRadius: 11, cursor: "pointer", fontSize: 12.5, fontWeight: 600, textTransform: "capitalize",
              background: genStyle === s ? "var(--glass-bg-strong)" : "transparent",
              border: genStyle === s ? "1px solid var(--glass-border-strong)" : "1px solid var(--glass-border)", color: "#fff",
            }}>{s === "linear" ? "Lineal" : s === "radial" ? "Radial" : "Cónico"}</button>
          ))}
        </div>
        <button className="btn btn-neon" onClick={generate} style={{ width: "100%", justifyContent: "center", padding: "12px 0" }}>
          <Icon name="spark" size={17} /> Generar y aplicar
        </button>
      </div>
    </PanelShell>
  );
}

// ---- IMAGE panel ---------------------------------------------------
function ImagePanel({ design, setDesign, selectedLayer, onClose }) {
  const fileRef = React.useRef(null);
  const addImage = (src) => setDesign((d) => ({ ...d, images: [...(d.images || []), { src, x: 50, y: 55, size: 90, shape: "rounded" }] }));
  const onFile = (e) => {
    const f = e.target.files[0];
    if (!f) return;
    const url = URL.createObjectURL(f);
    addImage(url);
  };
  const imgs = design.images || [];
  const sel = selectedLayer && selectedLayer.type === "images" ? selectedLayer.idx : (imgs.length - 1);
  const updSel = (patch) => setDesign((d) => {
    const arr = [...(d.images || [])];
    if (arr[sel]) arr[sel] = { ...arr[sel], ...patch };
    return { ...d, images: arr };
  });
  const delImg = (i) => setDesign((d) => ({ ...d, images: (d.images || []).filter((_, k) => k !== i) }));

  return (
    <PanelShell title="Agrega tus imágenes" subtitle="Sube tus fotos y arrástralas sobre la carcasa para acomodarlas." onClose={onClose}>
      <input ref={fileRef} type="file" accept="image/*" onChange={onFile} style={{ display: "none" }} />
      <button className="btn" onClick={() => fileRef.current.click()} style={{
        width: "100%", justifyContent: "center", padding: "26px 0", marginBottom: 16, flexDirection: "column", gap: 8,
        background: "rgba(255,255,255,0.04)", border: "1.5px dashed var(--glass-border-strong)", color: "#fff", borderRadius: 18,
      }}>
        <Icon name="image" size={26} stroke="var(--neon-cyan)" />
        <span style={{ fontWeight: 600 }}>Subir imagen</span>
        <span style={{ fontSize: 12, color: "var(--ink-50)" }}>PNG, JPG · arrástrala sobre la carcasa para moverla</span>
      </button>

      {imgs.length > 0 && (
        <>
          <span style={subLabel}>Imágenes ({imgs.length})</span>
          <div className="row" style={{ gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
            {imgs.map((im, i) => (
              <div key={i} style={{ position: "relative" }}>
                <div style={{ width: 48, height: 48, borderRadius: 12, backgroundImage: `url(${im.src})`, backgroundSize: "cover", backgroundPosition: "center", border: i === sel ? "2px solid var(--neon-cyan)" : "1px solid var(--glass-border)" }}/>
                <button onClick={() => delImg(i)} style={{ position: "absolute", top: -6, right: -6, width: 20, height: 20, borderRadius: "50%", background: "var(--neon-magenta)", border: "none", color: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="close" size={11} /></button>
              </div>
            ))}
          </div>
          {imgs[sel] && (
            <>
              <span style={subLabel}>Tamaño</span>
              <input type="range" min="50" max="180" value={imgs[sel].size} onChange={(e) => updSel({ size: +e.target.value })} style={{ width: "100%", accentColor: "var(--neon-magenta)", marginBottom: 14 }} />
              <div className="row" style={{ gap: 8 }}>
                {["rounded", "circle"].map((sh) => (
                  <button key={sh} onClick={() => updSel({ shape: sh })} style={{ flex: 1, padding: "9px 0", borderRadius: 11, cursor: "pointer", fontSize: 13, fontWeight: 600, background: imgs[sel].shape === sh ? "var(--glass-bg-strong)" : "transparent", border: "1px solid var(--glass-border)", color: "#fff" }}>{sh === "rounded" ? "Cuadrada" : "Círculo"}</button>
                ))}
              </div>
            </>
          )}
        </>
      )}
    </PanelShell>
  );
}

// ---- TEXT panel ----------------------------------------------------
function TextPanel({ design, setDesign, selectedLayer, onClose }) {
  const texts = design.texts || [];
  const addText = () => setDesign((d) => ({ ...d, texts: [...(d.texts || []), { value: "Tu texto", x: 50, y: 78, size: 26, color: "#ffffff", font: TEXT_FONTS[0].css, weight: 700, glow: true, spacing: 0, rot: 0 }] }));
  const upd = (i, patch) => setDesign((d) => { const arr = [...(d.texts || [])]; arr[i] = { ...arr[i], ...patch }; return { ...d, texts: arr }; });
  const del = (i) => setDesign((d) => ({ ...d, texts: (d.texts || []).filter((_, k) => k !== i) }));
  const activeIdx = selectedLayer && selectedLayer.type === "texts" ? selectedLayer.idx : -1;

  return (
    <PanelShell title="Agrega texto" subtitle="Suma bloques de texto, cambia tipografía, color y rotación. Arrástralos sobre la carcasa." onClose={onClose}>
      <div className="col" style={{ gap: 14, maxHeight: 360, overflowY: "auto", marginBottom: 14, paddingRight: 4 }}>
        {texts.length === 0 && <p style={{ color: "var(--ink-50)", fontSize: 13.5, textAlign: "center", margin: "12px 0" }}>Sin bloques de texto todavía.<br/>Agrega uno con el botón +.</p>}
        {texts.map((t, i) => (
          <div key={i} style={{ background: activeIdx === i ? "rgba(45,226,255,0.08)" : "rgba(255,255,255,0.04)", border: activeIdx === i ? "1px solid rgba(45,226,255,0.4)" : "1px solid var(--glass-border)", borderRadius: 16, padding: 14 }}>
            <div className="row" style={{ gap: 8, marginBottom: 12 }}>
              <input value={t.value} onChange={(e) => upd(i, { value: e.target.value })} placeholder="Escribe…" style={{
                flex: 1, background: "rgba(0,0,0,0.25)", border: "1px solid var(--glass-border)", borderRadius: 10, padding: "9px 12px", color: "#fff", fontSize: 14, fontFamily: "var(--font-ui)", outline: "none",
              }}/>
              <button onClick={() => del(i)} style={{ background: "var(--glass-bg)", border: "1px solid var(--glass-border)", borderRadius: 10, width: 36, height: 36, cursor: "pointer", color: "var(--ink-70)", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="trash" size={16} /></button>
            </div>
            <div className="row" style={{ gap: 6, marginBottom: 10, flexWrap: "wrap" }}>
              {TEXT_FONTS.map((f) => (
                <button key={f.id} onClick={() => upd(i, { font: f.css })} style={{ padding: "6px 11px", borderRadius: 9, cursor: "pointer", fontSize: 12, fontWeight: 600, fontFamily: f.css, background: t.font === f.css ? "var(--glass-bg-strong)" : "transparent", border: t.font === f.css ? "1px solid var(--glass-border-strong)" : "1px solid var(--glass-border)", color: "#fff" }}>{f.label}</button>
              ))}
            </div>
            <div className="row" style={{ gap: 7, marginBottom: 10, flexWrap: "wrap" }}>
              {CC.colors.slice(1, 8).map((c) => <Swatch key={c} color={c} size={24} active={t.color === c} onClick={() => upd(i, { color: c })} />)}
            </div>
            <div className="row" style={{ gap: 12 }}>
              <div className="col" style={{ flex: 1 }}>
                <span style={{ fontSize: 11, color: "var(--ink-50)", marginBottom: 4 }}>Tamaño</span>
                <input type="range" min="14" max="56" value={t.size} onChange={(e) => upd(i, { size: +e.target.value })} style={{ accentColor: "var(--neon-magenta)" }} />
              </div>
              <div className="col" style={{ flex: 1 }}>
                <span style={{ fontSize: 11, color: "var(--ink-50)", marginBottom: 4 }}>Rotación</span>
                <input type="range" min="-45" max="45" value={t.rot || 0} onChange={(e) => upd(i, { rot: +e.target.value })} style={{ accentColor: "var(--neon-magenta)" }} />
              </div>
              <button onClick={() => upd(i, { glow: !t.glow })} style={{ alignSelf: "flex-end", padding: "8px 12px", borderRadius: 9, cursor: "pointer", fontSize: 12, fontWeight: 600, background: t.glow ? "var(--grad-neon)" : "transparent", border: t.glow ? "1px solid transparent" : "1px solid var(--glass-border)", color: "#fff" }}>Glow</button>
            </div>
          </div>
        ))}
      </div>
      <button className="btn" onClick={addText} style={{ width: "100%", justifyContent: "center", padding: "13px 0", background: "var(--glass-bg-strong)", border: "1px solid var(--glass-border-strong)", color: "#fff" }}>
        <Icon name="plus" size={18} /> Agregar bloque de texto
      </button>
    </PanelShell>
  );
}

// ---- ACCESSORY panel -----------------------------------------------
function AccessoryPanel({ design, setDesign, onClose }) {
  const sel = design.accessories || [];
  const toggle = (id) => setDesign((d) => {
    const cur = d.accessories || [];
    const next = cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id];
    return { ...d, accessories: next, accStrap: next.includes("strap") };
  });
  return (
    <PanelShell title="Accesorios" subtitle="Complementa tu carcasa. Se suman al total y a tu pedido." onClose={onClose}>
      <div className="col" style={{ gap: 10 }}>
        {CC.accessories.map((a) => {
          const on = sel.includes(a.id);
          return (
            <button key={a.id} onClick={() => toggle(a.id)} style={{
              display: "flex", alignItems: "center", gap: 14, textAlign: "left", cursor: "pointer",
              padding: "13px 15px", borderRadius: 16, width: "100%",
              background: on ? "rgba(255,61,240,0.10)" : "rgba(255,255,255,0.04)",
              border: on ? "1px solid rgba(255,61,240,0.45)" : "1px solid var(--glass-border)",
              transition: "background 0.2s ease, border-color 0.2s ease",
            }}>
              <div style={{ width: 42, height: 42, borderRadius: 12, display: "flex", alignItems: "center", justifyContent: "center", background: on ? "var(--grad-neon)" : "var(--glass-bg)", flexShrink: 0 }}>
                <Icon name={a.icon} size={21} stroke="#fff" />
              </div>
              <div className="col" style={{ flex: 1, gap: 2 }}>
                <span style={{ fontWeight: 600, fontSize: 14.5 }}>{a.name}</span>
                <span style={{ fontSize: 12, color: "var(--ink-50)" }}>{a.desc}</span>
              </div>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink-70)" }}>{fmt(a.price)}</span>
              <div style={{ width: 24, height: 24, borderRadius: "50%", border: on ? "none" : "1.5px solid var(--glass-border-strong)", background: on ? "var(--neon-magenta)" : "transparent", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                {on && <Icon name="check" size={15} stroke="#fff" />}
              </div>
            </button>
          );
        })}
      </div>
    </PanelShell>
  );
}

// ---- STICKER panel -------------------------------------------------
function StickerPanel({ design, setDesign, selectedLayer, onClose }) {
  const stickers = design.stickers || [];
  const add = (src) => setDesign((d) => ({ ...d, stickers: [...(d.stickers || []), { src, x: 50, y: 46, size: 120, rot: 0 }] }));
  const sel = selectedLayer && selectedLayer.type === "stickers" ? selectedLayer.idx : (stickers.length - 1);
  const updSel = (patch) => setDesign((d) => { const arr = [...(d.stickers || [])]; if (arr[sel]) arr[sel] = { ...arr[sel], ...patch }; return { ...d, stickers: arr }; });
  const del = (i) => setDesign((d) => ({ ...d, stickers: (d.stickers || []).filter((_, k) => k !== i) }));

  return (
    <PanelShell title="Stickers" subtitle="Toca para agregarlos y arrástralos sobre la carcasa. Puedes sumar todos los que quieras." onClose={onClose}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10, marginBottom: stickers.length ? 22 : 0 }}>
        {CC.stickers.map((s) => (
          <button key={s.id} onClick={() => add(s.src)} title={s.name} style={{
            aspectRatio: "1", borderRadius: 16, cursor: "pointer", padding: 10,
            background: "rgba(255,255,255,0.05)", border: "1px solid var(--glass-border)",
            display: "flex", alignItems: "center", justifyContent: "center",
            transition: "transform 0.15s ease, background 0.2s ease, border-color 0.2s ease",
          }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "rgba(255,255,255,0.1)"; e.currentTarget.style.transform = "scale(1.05)"; e.currentTarget.style.borderColor = "var(--glass-border-strong)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "rgba(255,255,255,0.05)"; e.currentTarget.style.transform = "none"; e.currentTarget.style.borderColor = "var(--glass-border)"; }}>
            <img src={s.src} alt={s.name} style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "contain", filter: "drop-shadow(0 2px 4px rgba(0,0,0,0.3))" }}/>
          </button>
        ))}
      </div>

      {stickers.length > 0 && (
        <>
          <span style={subLabel}>En tu carcasa ({stickers.length})</span>
          <div className="row" style={{ gap: 8, flexWrap: "wrap", marginBottom: 18 }}>
            {stickers.map((st, i) => (
              <div key={i} style={{ position: "relative" }}>
                <div onClick={() => updSel({})} style={{ width: 50, height: 50, borderRadius: 12, padding: 5, background: i === sel ? "rgba(45,226,255,0.12)" : "rgba(255,255,255,0.05)", border: i === sel ? "2px solid var(--neon-cyan)" : "1px solid var(--glass-border)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <img src={st.src} style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "contain" }}/>
                </div>
                <button onClick={() => del(i)} style={{ position: "absolute", top: -6, right: -6, width: 20, height: 20, borderRadius: "50%", background: "var(--neon-magenta)", border: "none", color: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="close" size={11} /></button>
              </div>
            ))}
          </div>
          {stickers[sel] && (
            <div style={{ background: "rgba(255,255,255,0.04)", border: "1px solid var(--glass-border)", borderRadius: 16, padding: 16 }}>
              <span style={{ ...subLabel, marginBottom: 12 }}>Ajustar sticker</span>
              <div className="col" style={{ gap: 14 }}>
                <div className="col" style={{ gap: 6 }}>
                  <span style={{ fontSize: 12, color: "var(--ink-50)" }}>Tamaño</span>
                  <input type="range" min="50" max="220" value={stickers[sel].size} onChange={(e) => updSel({ size: +e.target.value })} style={{ accentColor: "var(--neon-magenta)" }} />
                </div>
                <div className="col" style={{ gap: 6 }}>
                  <span style={{ fontSize: 12, color: "var(--ink-50)" }}>Rotación</span>
                  <input type="range" min="-180" max="180" value={stickers[sel].rot || 0} onChange={(e) => updSel({ rot: +e.target.value })} style={{ accentColor: "var(--neon-magenta)" }} />
                </div>
              </div>
            </div>
          )}
        </>
      )}
    </PanelShell>
  );
}

Object.assign(window, { DesignPanel, ImagePanel, TextPanel, AccessoryPanel, StickerPanel });
