// Malbec Live — Show detail screen (Show ID)
// Two views: Overview (summary + categorías table) and Marketing-Pauta (deep list).

const { useState: useStateShow, useEffect: useEffectShow, useRef: useRefShow } = React;

function TeamStack() {
  const colors = ["#F3D9C4", "#2D2A33", "#E9DCC9"];
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
      <div style={{ display: "flex" }}>
        {colors.map((c, i) => (
          <div
            key={i}
            style={{
              width: 30, height: 30, borderRadius: 999, background: c,
              border: "2px solid var(--live-card)", marginLeft: i === 0 ? 0 : -10,
            }}
          />
        ))}
        <div
          style={{
            width: 30, height: 30, borderRadius: 999, background: "var(--live-primary)",
            color: "#fff", fontSize: 10, fontWeight: 600,
            display: "grid", placeItems: "center",
            border: "2px solid var(--live-card)", marginLeft: -10,
          }}
        >+3</div>
      </div>
      <button style={{
        width: 32, height: 32, borderRadius: 6,
        border: "1px solid var(--live-border)", background: "var(--live-card)",
        cursor: "pointer", display: "grid", placeItems: "center", color: "var(--live-body)",
      }}>
        <i data-lucide="user-plus" style={{ width: 14, height: 14 }} />
      </button>
    </div>
  );
}

function OverviewDropdown({ current, onPick }) {
  const [open, setOpen] = useStateShow(false);
  const [sub, setSub] = useStateShow(null);
  const ref = useRefShow(null);

  useEffectShow(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) { setOpen(false); setSub(null); } };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);

  const items = [
    { label: "Overview" },
    { label: "Hospitality" },
    { label: "Estructura y técnica", sub: ["Backline", "Audio", "Luces"] },
    { label: "Logística" },
    { label: "RRHH" },
    { label: "Marketing", sub: ["Redes sociales", "Pauta", "Freelancers"] },
    { label: "G.V producción", sub: ["Catering", "Runners"] },
    { label: "Servicios" },
  ];

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        onClick={() => setOpen(!open)}
        style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          height: 34, padding: "0 14px",
          background: "var(--live-card)", border: "1px solid var(--live-border)",
          borderRadius: 8, fontSize: 13, fontWeight: 500, color: "var(--live-heading)",
          cursor: "pointer", fontFamily: "var(--font-sans)",
        }}
      >
        <i data-lucide="list-filter" style={{ width: 14, height: 14, color: "var(--live-muted)" }} />
        {current}
      </button>
      {open && (
        <div style={{
          position: "absolute", top: 40, left: 0, zIndex: 30,
          minWidth: 220, background: "var(--live-card)",
          border: "1px solid var(--live-border)", borderRadius: 8,
          boxShadow: "0 12px 32px rgba(9,14,25,0.12)", padding: 6,
        }}>
          <div style={{ padding: "8px 12px", fontSize: 13, fontWeight: 600, color: "var(--live-heading)" }}>Categorías</div>
          {items.map((it) => (
            <div key={it.label} style={{ position: "relative" }}
              onMouseEnter={() => setSub(it.sub ? it.label : null)}
            >
              <button
                onClick={() => { if (!it.sub) { onPick(it.label); setOpen(false); setSub(null); } }}
                style={{
                  display: "flex", alignItems: "center", width: "100%",
                  padding: "7px 12px", fontSize: 13,
                  background: sub === it.label ? "var(--live-row-hover)" : "transparent",
                  border: "none", borderRadius: 6, cursor: "pointer",
                  color: "var(--live-body)", fontFamily: "var(--font-sans)", textAlign: "left",
                }}
              >
                <span style={{ flex: 1 }}>{it.label}</span>
                {it.sub && <i data-lucide="chevron-right" style={{ width: 13, height: 13, color: "var(--live-muted)" }} />}
              </button>
              {sub === it.label && it.sub && (
                <div style={{
                  position: "absolute", top: -4, left: "100%", marginLeft: 4,
                  minWidth: 180, background: "var(--live-card)",
                  border: "1px solid var(--live-border)", borderRadius: 8,
                  boxShadow: "0 12px 32px rgba(9,14,25,0.12)", padding: 6, zIndex: 40,
                }}>
                  <div style={{ padding: "8px 12px", fontSize: 13, fontWeight: 600, color: "var(--live-heading)" }}>{it.label}</div>
                  {it.sub.map((s) => (
                    <button key={s}
                      onClick={() => { onPick(`${it.label} - ${s}`); setOpen(false); setSub(null); }}
                      style={{
                        display: "block", width: "100%", padding: "7px 12px", fontSize: 13,
                        background: "transparent", border: "none", borderRadius: 6, cursor: "pointer",
                        color: "var(--live-body)", fontFamily: "var(--font-sans)", textAlign: "left",
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.background = "var(--live-row-hover)"}
                      onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
                    >{s}</button>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function MetricIcon({ name }) {
  return (
    <div style={{
      width: 36, height: 36, borderRadius: 999,
      border: "1px dashed var(--live-border-strong)",
      display: "grid", placeItems: "center", color: "var(--live-muted)", flexShrink: 0,
    }}>
      <i data-lucide={name} style={{ width: 16, height: 16 }} />
    </div>
  );
}

function OverviewView() {
  // Bad Bunny – River – 13/02/2026.
  // Each row's total = aprob + pend. Sum of totals = $3.040.444 (project cost).
  // Sum aprob = $2.128.444 ; sum pend = $912.000. pct = share of project cost.
  const cats = [
    { name: "Alquiler Venue",      total: "$880.000", pct: "28,9%", aprob: "$660.000", pend: "$220.000" },
    { name: "Estructura técnica",  total: "$480.000", pct: "15,8%", aprob: "$384.000", pend: "$96.000"  },
    { name: "Sadaic",              total: "$264.000", pct: "8,7%",  aprob: "$0",       pend: "$264.000" },
    { name: "RRHH",                total: "$240.000", pct: "7,9%",  aprob: "$192.000", pend: "$48.000"  },
    { name: "Servicios",           total: "$220.000", pct: "7,2%",  aprob: "$220.000", pend: "$0"       },
    { name: "Comisión ticketera",  total: "$220.000", pct: "7,2%",  aprob: "$220.000", pend: "$0"       },
    { name: "Hospitality",         total: "$180.000", pct: "5,9%",  aprob: "$180.000", pend: "$0"       },
    { name: "Producción",          total: "$176.000", pct: "5,8%",  aprob: "$176.000", pend: "$0"       },
    { name: "Ingresos Brutos",     total: "$132.000", pct: "4,3%",  aprob: "$0",       pend: "$132.000" },
    { name: "Logística",           total: "$96.444",  pct: "3,2%",  aprob: "$96.444",  pend: "$0"       },
    { name: "Marketing",           total: "$92.000",  pct: "3,0%",  aprob: "$0",       pend: "$92.000"  },
    { name: "Seguros",             total: "$60.000",  pct: "2,0%",  aprob: "$0",       pend: "$60.000"  },
  ];

  return (
    <>
      {/* Summary card with top navy accent */}
      <div style={{
        background: "var(--live-banner-bg)", border: "1px solid var(--live-border)",
        borderTop: "3px solid var(--live-primary)", borderRadius: 10,
        padding: "22px 28px", marginBottom: 36,
        display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16,
      }}>
        {[
          { l: "Pendiente de aprobación", v: "$912.000",   i: "clock" },
          { l: "Total aprobado",          v: "$2.128.444", i: "check-circle-2" },
          { l: "Total del proyecto",      v: "$3.040.444", i: "equal" },
        ].map((m, i) => (
          <div key={i} style={{
            display: "flex", alignItems: "center", gap: 14,
            paddingLeft: i === 0 ? 0 : 24,
            borderLeft: i === 0 ? "none" : "1px solid var(--live-border)",
          }}>
            <MetricIcon name={m.i} />
            <div>
              <div style={{ fontSize: 12, color: "var(--live-muted)", marginBottom: 2 }}>{m.l}</div>
              <div style={{ fontSize: 20, fontWeight: 700, color: "var(--live-heading)", letterSpacing: "-0.01em" }}>{m.v}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ fontSize: 15, fontWeight: 600, color: "var(--live-heading)", marginBottom: 14 }}>Categorías</div>

      <div style={{ background: "var(--live-card)", border: "1px solid var(--live-border)", borderRadius: 10, overflow: "hidden" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr 1.1fr",
          padding: "12px 20px", background: "var(--live-banner-bg)",
          borderBottom: "1px solid var(--live-border)",
          fontSize: 12, color: "var(--live-muted)", fontWeight: 500,
        }}>
          {[
            { i: "layout-grid", l: "Categorías" },
            { i: "circle-dollar-sign", l: "Total" },
            { i: "percent", l: "over total" },
            { i: "check-circle-2", l: "Aprobados" },
            { i: "clock", l: "Pendientes" },
          ].map((h, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <i data-lucide={h.i} style={{ width: 12, height: 12 }} />
              {h.l}
            </div>
          ))}
        </div>
        {cats.map((r, i) => (
          <div key={i} style={{
            display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr 1.1fr",
            padding: "14px 20px", borderTop: i === 0 ? "none" : "1px solid var(--live-border)",
            fontSize: 13, alignItems: "center",
          }}>
            <div style={{ color: "var(--live-heading)", fontWeight: 500 }}>{r.name}</div>
            <div style={{ color: "var(--live-body)" }}>{r.total}</div>
            <div>
              <span style={{
                display: "inline-block", padding: "2px 10px", background: "#E3F3E3",
                color: "#1F6B2F", borderRadius: 4, fontSize: 12, fontWeight: 500,
              }}>{r.pct}</span>
            </div>
            <div style={{ color: "var(--live-body)" }}>{r.aprob}</div>
            <div style={{ color: "var(--live-body)" }}>{r.pend}</div>
          </div>
        ))}
      </div>
    </>
  );
}

function SelectionActionBar({ count, onClear }) {
  const [mount, setMount] = useStateShow(false);
  useEffectShow(() => {
    if (count > 0) {
      // mount then animate in next frame
      setMount(true);
    } else {
      // keep mounted briefly for exit
      const t = setTimeout(() => setMount(false), 180);
      return () => clearTimeout(t);
    }
  }, [count]);
  useEffectShow(() => { if (mount && window.lucide) window.lucide.createIcons(); }, [mount, count]);
  if (!mount && count === 0) return null;
  const visible = count > 0;
  return (
    <div style={{
      position: "fixed", left: "50%", bottom: 28,
      transform: `translateX(-50%) translateY(${visible ? 0 : 12}px)`,
      opacity: visible ? 1 : 0,
      transition: "transform 200ms cubic-bezier(0.22, 1, 0.36, 1), opacity 180ms ease-out",
      zIndex: 70, pointerEvents: visible ? "auto" : "none",
    }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 14,
        padding: "8px 10px 8px 16px",
        background: "var(--live-card)",
        border: "1px solid var(--live-border)",
        borderRadius: 12,
        boxShadow: "0 14px 34px rgba(9,14,25,0.14), 0 2px 6px rgba(9,14,25,0.06)",
        fontFamily: "var(--font-sans)",
      }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: "var(--live-heading)" }}>
          {count} Selected
        </span>
        <div style={{ width: 1, height: 18, background: "var(--live-border)" }} />
        <button style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          background: "transparent", border: "none", fontSize: 13,
          color: "var(--live-body)", cursor: "pointer", fontFamily: "var(--font-sans)",
          padding: "4px 6px", borderRadius: 6,
        }}
          onMouseEnter={(e) => e.currentTarget.style.background = "var(--live-row-hover)"}
          onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
        >
          <i data-lucide="send" style={{ width: 13, height: 13 }} /> Enviar a facturar
        </button>
        <button style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          background: "transparent", border: "none", fontSize: 13,
          color: "var(--live-body)", cursor: "pointer", fontFamily: "var(--font-sans)",
          padding: "4px 6px", borderRadius: 6,
        }}
          onMouseEnter={(e) => e.currentTarget.style.background = "var(--live-row-hover)"}
          onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
        >
          <i data-lucide="trash-2" style={{ width: 13, height: 13 }} /> Eliminar
        </button>
        <button onClick={onClear} style={{
          background: "transparent", border: "none", color: "var(--live-muted)",
          cursor: "pointer", width: 24, height: 24, borderRadius: 6,
          display: "grid", placeItems: "center",
        }}>
          <i data-lucide="x" style={{ width: 14, height: 14 }} />
        </button>
      </div>
    </div>
  );
}

function StatusSelect({ value }) {
  const map = {
    "Valor referencia": { bg: "#E5E2F3", fg: "#4A3E9E" },
    "No aplica":        { bg: "#F5DADA", fg: "#8E2323" },
    "Aprobado":         { bg: "#E3F3E3", fg: "#1F6B2F" },
  };
  const s = map[value] || map["Valor referencia"];
  return (
    <button style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "3px 8px", background: s.bg, color: s.fg,
      border: "none", borderRadius: 5, fontSize: 11.5, fontWeight: 500,
      cursor: "pointer", fontFamily: "var(--font-sans)",
    }}>
      {value}
      <i data-lucide="chevron-down" style={{ width: 11, height: 11 }} />
    </button>
  );
}

function MarketingPautaView() {
  const [sel, setSel] = useStateShow({});
  const rows = [
    { d: "Regalo - Caja Madera",     rs: "Silvia Gimenez",  e: "Juan Martinez",   s: "Valor referencia", ars:"2.134.222", arsIva:"2.667.999", usd:"1.500", usdIva:"1.700" },
    { d: "Regalo - Auriculares",     rs: "Rosa Gómez",      e: "Julio Cordero",   s: "Valor referencia", ars:"400.000",   arsIva:"600.000",   usd:"250",   usdIva:"300" },
    { d: "Regalo - Jarrón de....",   rs: "Laura Torres",    e: "Carlos Rivera",   s: "Valor referencia", ars:"1.200.300", arsIva:"1.500.000", usd:"800",   usdIva:"950" },
    { d: "Regalo - Set de Té",       rs: "Ana López",       e: "Luis Pérez",      s: "Valor referencia", ars:"3.000.000", arsIva:"3.500.500", usd:"1.200", usdIva:"1.500" },
    { d: "Regalo - Reloj de Pulsera",rs: "Pedro Sánchez",   e: "Javier Gómez",    s: "Valor referencia", ars:"1.800.000", arsIva:"2.200.000", usd:"600",   usdIva:"750" },
    { d: "Regalo - Libro de Arte",   rs: "María Fernández", e: "Alberto Ruiz",    s: "Valor referencia", ars:"500.000",   arsIva:"750.000",   usd:"300",   usdIva:"400" },
    { d: "Regalo - Camiseta ...",    rs: "Diego Morales",   e: "Cristina Salazar",s: "Valor referencia", ars:"250.000",   arsIva:"350.000",   usd:"150",   usdIva:"200" },
    { d: "Regalo - Botella de Vino", rs: "Elena Castillo",  e: "Fernando Rom...", s: "Valor referencia", ars:"700.000",   arsIva:"900.000",   usd:"400",   usdIva:"500" },
    { d: "Regalo - Mochila de Viaje",rs: "Victor Salas",    e: "Sofía León",      s: "Valor referencia", ars:"1.000.000", arsIva:"1.300.000", usd:"700",   usdIva:"800" },
    { d: "Regalo - Cojín Decorativo",rs: "Natalia Ruiz",    e: "Fernando Sali...", s:"No aplica",        ars:"300.000",   arsIva:"450.000",   usd:"180",   usdIva:"220" },
    { d: "Vinos Artista",            rs: "Trentanove Enzo", e: "-",               s: "Aprobado",         ars:"2.134.222", arsIva:"2.667.999", usd:"1.500", usdIva:"1.700" },
  ];
  const cols = "36px minmax(200px,1.3fr) 1fr 1fr 140px 100px 110px 90px 110px 90px";
  const selectedCount = Object.values(sel).filter(Boolean).length;

  return (
    <>
      <div style={{ fontSize: 15, fontWeight: 600, color: "var(--live-heading)", marginBottom: 14 }}>Marketing - Pauta</div>

      <div style={{ background: "var(--live-card)", border: "1px solid var(--live-border)", borderRadius: 10, overflow: "hidden" }}>
        <div style={{
          display: "grid", gridTemplateColumns: cols,
          padding: "12px 16px", background: "var(--live-banner-bg)",
          borderBottom: "1px solid var(--live-border)",
          fontSize: 11.5, color: "var(--live-muted)", fontWeight: 500,
          alignItems: "center",
        }}>
          <div><input type="checkbox" style={{ accentColor: "var(--live-primary)" }} /></div>
          {[
            { i:"info", l:"Descripción" },
            { i:"building-2", l:"Razon social" },
            { i:"user", l:"Encargado" },
            { i:"sliders-horizontal", l:"Status" },
            { i:"circle-dollar-sign", l:"(ARS)" },
            { i:"circle-dollar-sign", l:"(ARS+IVA)" },
            { i:"circle-dollar-sign", l:"(USD)" },
            { i:"circle-dollar-sign", l:"(USD+IVA)" },
          ].map((h,i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 5 }}>
              <i data-lucide={h.i} style={{ width: 11, height: 11 }} />
              {h.l}
            </div>
          ))}
          <div>Acciones</div>
        </div>
        {rows.map((r, i) => (
          <div key={i} style={{
            display: "grid", gridTemplateColumns: cols,
            padding: "10px 16px", borderTop: i === 0 ? "none" : "1px solid var(--live-border)",
            fontSize: 12.5, alignItems: "center",
            background: sel[i] ? "var(--live-row-hover)" : "transparent",
          }}>
            <div>
              <input type="checkbox" checked={!!sel[i]} onChange={(e) => setSel({...sel, [i]: e.target.checked})} style={{ accentColor: "var(--live-primary)" }} />
            </div>
            <div style={{ color: "var(--live-heading)" }}>{r.d}</div>
            <div style={{ color: "var(--live-body)" }}>{r.rs}</div>
            <div style={{ color: "var(--live-body)" }}>{r.e}</div>
            <div><StatusSelect value={r.s} /></div>
            <div style={{ color: "var(--live-body)" }}>{r.ars}</div>
            <div style={{ color: "var(--live-body)" }}>{r.arsIva}</div>
            <div style={{ color: "var(--live-body)" }}>{r.usd}</div>
            <div style={{ color: "var(--live-body)" }}>{r.usdIva}</div>
            <div style={{ display: "flex", gap: 8, color: "var(--live-muted)" }}>
              <i data-lucide="file-text" style={{ width: 14, height: 14 }} />
              <i data-lucide="file" style={{ width: 14, height: 14 }} />
            </div>
          </div>
        ))}
      </div>

      <SelectionActionBar count={selectedCount} onClear={() => setSel({})} />
    </>
  );
}

function ShowDetailPane({ onBack }) {
  const [view, setView] = useStateShow("Overview");
  useEffectShow(() => { if (window.lucide) window.lucide.createIcons(); });

  const isMarketing = view.startsWith("Marketing");

  return (
    <div style={{ padding: "28px 36px 40px", overflow: "auto", height: "100%" }}>
      {/* Header row */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 22 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <button onClick={onBack} style={{
            background: "transparent", border: "none", cursor: "pointer",
            color: "var(--live-muted)", display: "grid", placeItems: "center",
            width: 28, height: 28, borderRadius: 6,
          }}>
            <i data-lucide="arrow-left" style={{ width: 16, height: 16 }} />
          </button>
          <h1 style={{
            fontSize: 22, fontWeight: 700, color: "var(--live-heading)",
            letterSpacing: "-0.015em", margin: 0,
          }}>Bad Bunny - River - 13/02/2026</h1>
          <OverviewDropdown current={isMarketing ? view.split(" - ")[0] : view} onPick={setView} />
        </div>
        <button style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          height: 36, padding: "0 16px",
          background: "var(--live-primary)", color: "#fff",
          border: "none", borderRadius: 8, fontSize: 13, fontWeight: 500,
          cursor: "pointer", fontFamily: "var(--font-sans)",
        }}>
          <i data-lucide="plus" style={{ width: 14, height: 14 }} />
          Crear gasto
        </button>
      </div>

      {view === "Overview" ? <OverviewView /> : <MarketingPautaView />}

      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, marginTop: 24, fontSize: 13 }}>
        <span style={{ color: "var(--live-body)", display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 10px" }}>
          <i data-lucide="chevron-left" style={{ width: 14, height: 14 }} /> Previous
        </span>
        {[1,2,3].map((n) => (
          <span key={n} style={{
            width: 32, height: 32, display: "grid", placeItems: "center",
            background: n === 2 ? "var(--live-card)" : "transparent",
            border: n === 2 ? "1px solid var(--live-border)" : "1px solid transparent",
            borderRadius: 6, fontWeight: n === 2 ? 600 : 500,
            color: n === 2 ? "var(--live-heading)" : "var(--live-body)",
          }}>{n}</span>
        ))}
        <span style={{ padding: "0 6px", color: "var(--live-muted)" }}>…</span>
        <span style={{ color: "var(--live-body)", display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 10px" }}>
          Next <i data-lucide="chevron-right" style={{ width: 14, height: 14 }} />
        </span>
      </div>
    </div>
  );
}

function ShowDetailHeader() {
  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "14px 28px", borderBottom: "1px solid var(--live-border)",
      background: "var(--live-bg)", height: 54,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <Grape size={18} color="var(--live-primary)" />
        <div style={{ fontSize: 16, letterSpacing: "-0.07em", color: "var(--live-heading)" }}>
          <span style={{ fontWeight: 500 }}>Malbec</span><span style={{ fontStyle: "italic", fontWeight: 300 }}>Live</span>
        </div>
      </div>
      <TeamStack />
    </div>
  );
}

Object.assign(window, { ShowDetailPane, ShowDetailHeader });
