// Malbec Live — Ticketing module
// List view + dates drawer + sales-history detail.

const { useState: useStateTk, useEffect: useEffectTk } = React;

function TkAvatar({ name }) {
  const seeds = {
    "Bad Bunny":    { bg: "#F3D9C4", fg: "#8B5E3C" },
    "Rels B":       { bg: "#D6D2CA", fg: "#4A443B" },
    "Nicki Nicole": { bg: "#F3D9C4", fg: "#8B5E3C" },
    "Duki":         { bg: "#E3D4C2", fg: "#6B4E2E" },
    "Bizarrap":     { bg: "#F4D4C0", fg: "#8B4A2E" },
    "Cazzu":        { bg: "#D6B8A5", fg: "#5A3E2E" },
  };
  const s = seeds[name] || { bg: "#E4E2DF", fg: "#3F3F46" };
  const initials = name.split(" ").map((p) => p[0]).slice(0, 2).join("");
  return (
    <div style={{
      width: 30, height: 30, borderRadius: 999,
      background: s.bg, color: s.fg,
      display: "grid", placeItems: "center",
      fontSize: 10, fontWeight: 600, flexShrink: 0,
      border: "1px solid var(--live-border)",
    }}>{initials}</div>
  );
}

function PercentPill({ value }) {
  const n = parseInt(value);
  let bg, fg;
  if (n >= 80) { bg = "#E3F3E3"; fg = "#1F6B2F"; }
  else if (n >= 50) { bg = "#FBE8D0"; fg = "#8A5A1B"; }
  else if (n >= 35) { bg = "#E5E2F3"; fg = "#4A3E9E"; }
  else { bg = "#F5DADA"; fg = "#8E2323"; }
  return (
    <span style={{
      display: "inline-block", padding: "3px 10px",
      background: bg, color: fg,
      borderRadius: 4, fontSize: 11.5, fontWeight: 500,
    }}>{value}</span>
  );
}

function DatesPill({ count }) {
  return (
    <span style={{
      display: "inline-block", padding: "2px 8px", marginLeft: 8,
      borderRadius: 4, background: "var(--live-banner-bg)",
      border: "1px solid var(--live-border)",
      color: "var(--live-muted)", fontSize: 11, fontWeight: 500,
      whiteSpace: "nowrap",
    }}>+{count} Dates</span>
  );
}

function TkSegmented({ value, onChange }) {
  return (
    <div style={{
      display: "inline-flex", padding: 3,
      background: "var(--live-banner-bg)",
      border: "1px solid var(--live-border)", borderRadius: 8,
    }}>
      {["Active", "Archived"].map((o) => {
        const active = o === value;
        return (
          <button key={o} onClick={() => onChange(o)} style={{
            appearance: "none", border: "none",
            background: active ? "var(--live-card)" : "transparent",
            color: active ? "var(--live-heading)" : "var(--live-muted)",
            height: 28, padding: "0 14px", fontSize: 12.5,
            fontWeight: active ? 600 : 500, borderRadius: 6,
            cursor: "pointer", fontFamily: "var(--font-sans)",
            boxShadow: active ? "0 1px 2px rgba(9,14,25,0.06)" : "none",
          }}>{o}</button>
        );
      })}
    </div>
  );
}

function DatesDrawer({ open, onClose, artist, onSelectDate }) {
  useEffectTk(() => { if (open && window.lucide) window.lucide.createIcons(); }, [open]);

  if (!open) return null;

  const dates = [
    { artist, venue: "Movistar Arena", city: "Madrid", date: "13/02/2026", today: "+54 Today" },
    { artist, venue: "Movistar Arena", city: "Madrid", date: "13/02/2026", today: "+251 Today" },
    { artist, venue: "Movistar Arena", city: "Madrid", date: "13/02/2026", today: "+54 Today" },
  ];

  return (
    <>
      {/* Overlay */}
      <div onClick={onClose} style={{
        position: "fixed", inset: 0,
        background: "rgba(20,22,32,0.35)",
        zIndex: 55,
        animation: "modal-fade 180ms ease-out",
      }} />
      {/* Drawer */}
      <aside style={{
        position: "fixed", top: 0, right: 0, bottom: 0,
        width: 420, background: "var(--live-card)",
        borderLeft: "1px solid var(--live-border)",
        zIndex: 60, padding: "20px 24px",
        boxShadow: "-12px 0 32px rgba(9,14,25,0.14)",
        animation: "drawer-slide 240ms cubic-bezier(0.22,1,0.36,1)",
        display: "flex", flexDirection: "column", gap: 14,
        overflowY: "auto",
      }}>
        <button onClick={onClose} style={{
          alignSelf: "flex-start",
          background: "transparent", border: "none",
          cursor: "pointer", color: "var(--live-body)",
          width: 32, height: 32, borderRadius: 6,
          display: "grid", placeItems: "center",
        }}>
          <LuIcon name="x" size={18} />
        </button>

        {dates.map((d, i) => (
          <button key={i} onClick={() => onSelectDate(d)} style={{
            display: "flex", alignItems: "center", gap: 12,
            padding: "12px 14px",
            background: "var(--live-card)",
            border: "1px solid var(--live-border)",
            borderRadius: 10,
            cursor: "pointer",
            fontFamily: "var(--font-sans)", textAlign: "left",
            transition: "border-color 140ms ease-out",
          }}
            onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--live-border-strong)"}
            onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--live-border)"}
          >
            <div style={{
              width: 58, height: 58, borderRadius: 8,
              background: "#F3D9C4",
              flexShrink: 0,
            }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: "var(--live-heading)" }}>{d.artist}</div>
              <div style={{ fontSize: 11.5, color: "var(--live-muted)", display: "flex", alignItems: "center", gap: 5, marginTop: 2 }}>
                <LuIcon name="map-pin" size={11} />
                {d.city}
                <LuIcon name="building" size={11} style={{ marginLeft: 8 }} />
                {d.venue}
              </div>
              <div style={{ fontSize: 11.5, color: "var(--live-muted)", display: "flex", alignItems: "center", gap: 5, marginTop: 2 }}>
                <LuIcon name="calendar" size={11} />
                {d.date}
              </div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 8 }}>
              <span style={{
                padding: "3px 9px", background: "#E3F3E3", color: "#1F6B2F",
                fontSize: 11, fontWeight: 500, borderRadius: 4,
              }}>{d.today}</span>
              <LuIcon name="arrow-right" size={16} color="var(--live-muted)" />
            </div>
          </button>
        ))}
      </aside>
    </>
  );
}

function SalesHistoryView({ show, onBack }) {
  useEffectTk(() => { if (window.lucide) window.lucide.createIcons(); });

  const sales = [
    { date: "13/02/2026", day: "Sunday",    sales: "+ 4", avail: "2.134", cap: "87%", ars: "$ 1.359.180.000", usd: "$ 1.031.244" },
    { date: "13/02/2026", day: "Saturday",  sales: "+ 4", avail: "3.042", cap: "84%", ars: "$ 1.359.180.000", usd: "$ 1.031.244" },
    { date: "13/02/2026", day: "Friday",    sales: "0",   avail: "3.046", cap: "87%", ars: "$ 1.359.180.000", usd: "$ 1.031.244", zero: true },
    { date: "13/02/2026", day: "Thursday",  sales: "+ 4", avail: "3.042", cap: "84%", ars: "$ 1.359.180.000", usd: "$ 1.031.244" },
    { date: "13/02/2026", day: "Wednesday", sales: "+ 4", avail: "3.042", cap: "84%", ars: "$ 1.359.180.000", usd: "$ 1.031.244" },
    { date: "13/02/2026", day: "Tuesday",   sales: "+ 4", avail: "3.042", cap: "84%", ars: "$ 1.359.180.000", usd: "$ 1.031.244" },
    { date: "13/02/2026", day: "Monday",    sales: "0",   avail: "3.046", cap: "87%", ars: "$ 1.359.180.000", usd: "$ 1.031.244", zero: true },
  ];

  const cols = "1fr 1fr 1fr 1.1fr 1fr 1.4fr 1.3fr";

  return (
    <div style={{ padding: "28px 36px 40px", overflow: "auto", height: "100%" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
        <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,
          }}>
            <LuIcon name="arrow-left" size={16} />
          </button>
          <h1 style={{
            fontSize: 22, fontWeight: 700, color: "var(--live-heading)",
            letterSpacing: "-0.015em", margin: 0,
          }}>{show.artist} - River - {show.date}</h1>
        </div>
        <TkSegmented value="Active" onChange={() => {}} />
      </div>

      {/* Metrics */}
      <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: 28,
        display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 16,
      }}>
        {[
          { l: "Avg. Daily sales", v: "1.231",  i: "trending-up" },
          { l: "Total sales",      v: "64.000", i: "circle-dollar-sign" },
          { l: "Cappacity",        v: "80.000", i: "users" },
          { l: "Avg. Sold",        v: "%87",    i: "bar-chart-3" },
        ].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)",
          }}>
            <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,
            }}>
              <LuIcon name={m.i} size={16} />
            </div>
            <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: 14, fontWeight: 600, color: "var(--live-heading)", marginBottom: 12 }}>Sales history.</div>

      {/* Sales table */}
      <div style={{
        background: "var(--live-card)", border: "1px solid var(--live-border)",
        borderRadius: 10, overflow: "hidden",
      }}>
        <div style={{
          display: "grid", gridTemplateColumns: cols,
          padding: "12px 20px", background: "var(--live-banner-bg)",
          borderBottom: "1px solid var(--live-border)",
          fontSize: 12, fontWeight: 500, color: "var(--live-muted)",
        }}>
          {[
            { i: "calendar", l: "Date" },
            { i: "calendar-days", l: "Day" },
            { i: "plus", l: "Daily sales" },
            { i: "ticket", l: "Available Tickets" },
            { i: "percent", l: "Cappacity" },
            { i: "circle-dollar-sign", l: "Total Income (ARS)" },
            { i: "circle-dollar-sign", l: "Total Income (USD)" },
          ].map((h, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <LuIcon name={h.i} size={12} />
              {h.l}
            </div>
          ))}
        </div>
        {sales.map((r, i) => (
          <div key={i} style={{
            display: "grid", gridTemplateColumns: cols,
            padding: "14px 20px", borderTop: i === 0 ? "none" : "1px solid var(--live-border)",
            fontSize: 12.5, alignItems: "center",
          }}>
            <div style={{ color: "var(--live-body)" }}>{r.date}</div>
            <div style={{ color: "var(--live-body)" }}>{r.day}</div>
            <div>
              <span style={{
                display: "inline-block", padding: "4px 12px", minWidth: 50, textAlign: "center",
                background: r.zero ? "#F5D8D6" : "#D7E9D1",
                color: r.zero ? "#8E3A36" : "#2E5A2E",
                borderRadius: 4, fontSize: 12, fontWeight: 500,
              }}>{r.sales}</span>
            </div>
            <div style={{ color: "var(--live-body)" }}>{r.avail}</div>
            <div><PercentPill value={r.cap} /></div>
            <div style={{ color: "var(--live-body)" }}>{r.ars}</div>
            <div style={{ color: "var(--live-body)" }}>{r.usd}</div>
          </div>
        ))}
      </div>

      {/* Pagination */}
      <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" }}>
          <LuIcon name="chevron-left" size={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 <LuIcon name="chevron-right" size={14} />
        </span>
      </div>
    </div>
  );
}

function TicketingPane() {
  const [filter, setFilter] = useStateTk("Active");
  const [search, setSearch] = useStateTk("");
  const [page, setPage] = useStateTk(2);
  const [drawerArtist, setDrawerArtist] = useStateTk(null);
  const [detail, setDetail] = useStateTk(null);

  useEffectTk(() => { if (window.lucide) window.lucide.createIcons(); });

  const rows = [
    { artist: "Bad Bunny",    total: 4, date: "13/02/2026", extra: 3, sold: "87%" },
    { artist: "Rels B",       total: 2, date: "13/02/2026", extra: 0, sold: "30%" },
    { artist: "Nicki Nicole", total: 1, date: "13/02/2026", extra: 0, sold: "40%" },
    { artist: "Duki",         total: 3, date: "13/02/2026", extra: 2, sold: "94%" },
    { artist: "Bizarrap",     total: 1, date: "13/02/2026", extra: 0, sold: "44%" },
    { artist: "Cazzu",        total: 6, date: "13/02/2026", extra: 5, sold: "97%" },
  ];

  const cols = "minmax(220px,1.4fr) 1fr 1.3fr 1fr 90px";

  if (detail) {
    return <SalesHistoryView show={detail} onBack={() => setDetail(null)} />;
  }

  return (
    <div style={{ padding: "28px 36px 40px", overflow: "auto", height: "100%", position: "relative" }}>
      {/* Toolbar */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        marginBottom: 20, gap: 16,
      }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 10,
          flex: 1, maxWidth: 340, height: 36, padding: "0 12px",
          background: "var(--live-card)", border: "1px solid var(--live-border)", borderRadius: 8,
        }}>
          <LuIcon name="search" size={14} color="var(--live-muted)" />
          <input value={search} onChange={(e) => setSearch(e.target.value)}
            placeholder="Search show…"
            style={{
              flex: 1, border: "none", outline: "none", background: "transparent",
              fontFamily: "var(--font-sans)", fontSize: 13,
              color: "var(--live-heading)", height: "100%",
            }}
          />
        </div>
        <TkSegmented value={filter} onChange={setFilter} />
      </div>

      {/* Table */}
      <div style={{
        background: "var(--live-card)", border: "1px solid var(--live-border)",
        borderRadius: 10, overflow: "hidden",
      }}>
        <div style={{
          display: "grid", gridTemplateColumns: cols,
          padding: "12px 20px", background: "var(--live-banner-bg)",
          borderBottom: "1px solid var(--live-border)",
          fontSize: 12, fontWeight: 500, color: "var(--live-muted)",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <LuIcon name="users" size={13} /> Artista
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <LuIcon name="building" size={13} /> Total shows
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <LuIcon name="calendar" size={13} /> Dates
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <LuIcon name="percent" size={13} /> Avg. Sold
          </div>
          <div style={{ textAlign: "right" }}>Acciones</div>
        </div>

        {rows.map((r, i) => (
          <div key={i}
            onClick={() => {
              if (r.extra > 0) setDrawerArtist(r);
              else setDetail({ artist: r.artist, date: r.date });
            }}
            style={{
              display: "grid", gridTemplateColumns: cols,
              padding: "12px 20px",
              borderTop: i === 0 ? "none" : "1px solid var(--live-border)",
              alignItems: "center", fontSize: 13,
              cursor: "pointer",
              transition: "background 120ms ease-out",
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--live-row-hover)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
          >
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <TkAvatar name={r.artist} />
              <span style={{ fontWeight: 600, color: "var(--live-heading)" }}>{r.artist}</span>
            </div>
            <div style={{ color: "var(--live-body)" }}>{r.total}</div>
            <div style={{ color: "var(--live-body)", display: "flex", alignItems: "center", whiteSpace: "nowrap" }}>
              <span>{r.date}</span>
              {r.extra > 0 && <DatesPill count={r.extra} />}
            </div>
            <div><PercentPill value={r.sold} /></div>
            <div style={{ textAlign: "right" }}>
              <button onClick={(e) => e.stopPropagation()} style={{
                appearance: "none", background: "transparent", border: "none",
                color: "var(--live-muted)", width: 28, height: 28, borderRadius: 6,
                cursor: "pointer", display: "inline-grid", placeItems: "center",
              }}>
                <LuIcon name="more-horizontal" size={14} />
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* Pagination */}
      <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" }}>
          <LuIcon name="chevron-left" size={14} /> Previous
        </span>
        {[1,2,3].map((n) => (
          <button key={n} onClick={() => setPage(n)} style={{
            width: 32, height: 32,
            background: page === n ? "var(--live-card)" : "transparent",
            border: page === n ? "1px solid var(--live-border)" : "1px solid transparent",
            borderRadius: 6, fontWeight: page === n ? 600 : 500,
            color: page === n ? "var(--live-heading)" : "var(--live-body)",
            cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 13,
          }}>{n}</button>
        ))}
        <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 <LuIcon name="chevron-right" size={14} />
        </span>
      </div>

      <DatesDrawer
        open={!!drawerArtist}
        artist={drawerArtist?.artist || ""}
        onClose={() => setDrawerArtist(null)}
        onSelectDate={(d) => { setDrawerArtist(null); setDetail({ artist: d.artist, date: d.date }); }}
      />
    </div>
  );
}

Object.assign(window, { TicketingPane });
