// components.jsx — shared UI building blocks

// Map a Portuguese color name to an approximate hue/lightness for placeholder gradients
const COR_HUE = {
  branco: { h: 95, l: 0.78, c: 0.01 }, prata: { h: 250, l: 0.66, c: 0.01 },
  cinza: { h: 250, l: 0.52, c: 0.008 }, "cinza platinum": { h: 250, l: 0.58, c: 0.01 },
  preto: { h: 250, l: 0.28, c: 0.006 }, vermelho: { h: 25, l: 0.52, c: 0.16 },
  azul: { h: 250, l: 0.52, c: 0.13 }, verde: { h: 150, l: 0.55, c: 0.12 },
  amarelo: { h: 95, l: 0.78, c: 0.15 }, laranja: { h: 55, l: 0.62, c: 0.15 },
};
function corStyle(cor) {
  const key = (cor || "").toLowerCase();
  const m = COR_HUE[key] || { h: 250, l: 0.5, c: 0.01 };
  return m;
}

// Vehicle photo: real image if URL provided, otherwise a designed placeholder
function VehiclePhoto({ vehicle, className, style, rounded = true, label = true }) {
  const foto = vehicle.fotos && vehicle.fotos[0];
  const m = corStyle(vehicle.cor);
  const Icon = IconBike;
  if (foto) {
    return (
      <div className={className} style={{ ...style, overflow: "hidden", borderRadius: rounded ? "inherit" : 0 }}>
        <img src={foto} alt={vehicle.marca + " " + vehicle.modelo}
             style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
      </div>
    );
  }
  const c1 = `oklch(${m.l} ${m.c} ${m.h})`;
  const c2 = `oklch(${Math.max(0.2, m.l - 0.22)} ${m.c} ${m.h})`;
  return (
    <div className={className} style={{
      ...style, position: "relative", overflow: "hidden",
      background: `radial-gradient(120% 90% at 70% 10%, ${c1}, ${c2})`,
      display: "flex", alignItems: "center", justifyContent: "center",
    }}>
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: "repeating-linear-gradient(125deg, rgba(255,255,255,.05) 0 2px, transparent 2px 22px)",
      }} />
      <Icon size={64} stroke="rgba(255,255,255,.5)" sw={1.2} style={{ position: "absolute", opacity: .9 }} />
      {label && (
        <div style={{
          position: "absolute", bottom: 12, left: 14, fontFamily: "ui-monospace, monospace",
          fontSize: 11, letterSpacing: ".06em", color: "rgba(255,255,255,.72)",
          textTransform: "uppercase", display: "flex", alignItems: "center", gap: 6,
        }}>
          <IconCamera size={13} stroke="rgba(255,255,255,.72)" /> foto da moto
        </div>
      )}
    </div>
  );
}

function StatusBadge({ status }) {
  const meta = STATUS_META[status];
  if (!meta || !meta.badge) return null;
  return <span className={"badge badge-" + meta.badge}>{meta.label}</span>;
}

function SpecPill({ icon: Icon, label, value }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <div style={{
        width: 38, height: 38, borderRadius: 10, flexShrink: 0,
        background: "var(--surface-2)", border: "1px solid var(--border-soft)",
        display: "flex", alignItems: "center", justifyContent: "center", color: "var(--accent)",
      }}><Icon size={19} /></div>
      <div style={{ lineHeight: 1.25 }}>
        <div style={{ fontSize: 12, color: "var(--faint)", fontWeight: 600 }}>{label}</div>
        <div style={{ fontSize: 15, fontWeight: 700 }}>{value}</div>
      </div>
    </div>
  );
}

// Vehicle card for catalog grid
function VehicleCard({ vehicle, onOpen }) {
  const sold = vehicle.status === "vendido";
  const meta = STATUS_META[vehicle.status];
  return (
    <button onClick={() => onOpen(vehicle)} className="card fade-in" style={{
      textAlign: "left", padding: 0, overflow: "hidden", cursor: "pointer",
      transition: "transform .16s ease, border-color .16s, box-shadow .16s",
      display: "flex", flexDirection: "column",
    }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-4px)"; e.currentTarget.style.borderColor = "var(--faint)"; e.currentTarget.style.boxShadow = "var(--shadow)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = ""; e.currentTarget.style.borderColor = "var(--border-soft)"; e.currentTarget.style.boxShadow = "none"; }}>
      <div style={{ position: "relative", aspectRatio: "4 / 3" }}>
        <VehiclePhoto vehicle={vehicle} style={{ width: "100%", height: "100%" }} rounded={false} />
        <div style={{ position: "absolute", top: 12, left: 12, display: "flex", gap: 6 }}>
          {meta && meta.badge && <StatusBadge status={vehicle.status} />}
        </div>
        {sold && (
          <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,.45)", backdropFilter: "blur(1px)" }} />
        )}
        <div style={{
          position: "absolute", top: 12, right: 12, padding: "6px 10px", borderRadius: 999,
          background: "rgba(0,0,0,.5)", backdropFilter: "blur(6px)", color: "#fff",
          fontSize: 12, fontWeight: 700, display: "flex", alignItems: "center", gap: 5,
        }}><IconBike size={14} />{vehicle.ano}</div>
      </div>
      <div style={{ padding: "16px 18px 18px", display: "flex", flexDirection: "column", gap: 12, flex: 1 }}>
        <div>
          <div style={{ fontSize: 12, color: "var(--faint)", fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase" }}>{vehicle.marca}</div>
          <h3 style={{ fontSize: 20, marginTop: 2 }}>{vehicle.modelo}</h3>
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: "6px 14px", fontSize: 13, color: "var(--muted)", fontWeight: 600 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><IconGauge size={15} />{formatKM(vehicle.km)}</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><IconGear size={15} />{vehicle.cambio}</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><IconFuel size={15} />{vehicle.combustivel}</span>
        </div>
        <div style={{ marginTop: "auto", display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 8 }}>
          <div>
            {vehicle.status === "oferta" && vehicle.precoAntigo > vehicle.preco && (
              <div style={{ fontSize: 13, color: "var(--faint)", textDecoration: "line-through" }}>{formatBRL(vehicle.precoAntigo)}</div>
            )}
            <div style={{ fontFamily: "var(--font-display)", fontSize: 23, fontWeight: 700, color: vehicle.status === "oferta" ? "var(--warn)" : "var(--text)" }}>{formatBRL(vehicle.preco)}</div>
          </div>
          <span className="btn btn-ghost btn-sm" style={{ pointerEvents: "none" }}>Ver detalhes <IconArrowRight size={15} /></span>
        </div>
      </div>
    </button>
  );
}

// Generic modal
function Modal({ open, onClose, children, maxWidth = 560, label }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [open]);
  if (!open) return null;
  return (
    <div onClick={onClose} role="dialog" aria-label={label} style={{
      position: "fixed", inset: 0, zIndex: 200, background: "rgba(0,0,0,.6)", backdropFilter: "blur(4px)",
      display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "5vh 16px", overflowY: "auto",
      animation: "fadeIn .2s ease",
    }}>
      <div onClick={(e) => e.stopPropagation()} className="card" style={{
        maxWidth, width: "100%", boxShadow: "0 30px 80px -20px rgba(0,0,0,.7)", animation: "fadeIn .25s ease",
      }}>{children}</div>
    </div>
  );
}

function ModalHeader({ title, subtitle, onClose }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12, padding: "20px 22px", borderBottom: "1px solid var(--border-soft)" }}>
      <div>
        <h3 style={{ fontSize: 19 }}>{title}</h3>
        {subtitle && <div style={{ fontSize: 13.5, color: "var(--muted)", marginTop: 3 }}>{subtitle}</div>}
      </div>
      <button onClick={onClose} className="btn btn-ghost btn-sm" style={{ padding: 8, borderRadius: 10 }} aria-label="Fechar"><IconX size={18} /></button>
    </div>
  );
}

// Store location placeholder map
function StoreMap({ height = 150 }) {
  return (
    <div style={{ position: "relative", height, borderRadius: 12, overflow: "hidden", border: "1px solid var(--border-soft)",
      background: "var(--surface-2)" }}>
      <div style={{ position: "absolute", inset: 0,
        backgroundImage: "linear-gradient(var(--border) 1px, transparent 1px), linear-gradient(90deg, var(--border) 1px, transparent 1px)",
        backgroundSize: "30px 30px", opacity: .5 }} />
      <div style={{ position: "absolute", left: "8%", right: "32%", top: "55%", height: 8, background: "var(--surface-3)", borderRadius: 4, transform: "rotate(-4deg)" }} />
      <div style={{ position: "absolute", left: "40%", top: "8%", bottom: "12%", width: 8, background: "var(--surface-3)", borderRadius: 4, transform: "rotate(3deg)" }} />
      <div style={{ position: "absolute", left: "calc(40% - 6px)", top: "44%", color: "var(--accent)", transform: "translateY(-100%)" }}>
        <IconPin size={32} fill="var(--accent)" stroke="var(--accent-ink)" />
      </div>
      <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, padding: "10px 12px", fontSize: 12.5,
        background: "linear-gradient(transparent, rgba(0,0,0,.35))", color: "rgba(255,255,255,.92)", fontWeight: 600,
        display: "flex", alignItems: "center", gap: 6 }}>
        <IconPin size={14} /> {STORE.nome}
      </div>
    </div>
  );
}

Object.assign(window, {
  VehiclePhoto, StatusBadge, SpecPill, VehicleCard, Modal, ModalHeader, StoreMap, corStyle,
});
