// Malbec Live — Calendar module
// Month grid + right sidebar that swaps between "Próximos shows" list and selected-show info.

const { useState: useStateCal, useEffect: useEffectCal } = React;

function CalMetricIcon({ 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 CalMetrics() {
  return (
    <div style={{
      background: "var(--live-banner-bg)",
      border: "1px solid var(--live-border)",
      borderTop: "3px solid var(--live-primary)",
      borderRadius: 10,
      padding: "20px 28px",
      marginBottom: 24,
      display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16,
    }}>
      {[
        { l: "Shows este mes", v: "8", i: "clock" },
        { l: "Tickets vendidos", v: "85.022", i: "ticket" },
        { 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)",
        }}>
          <CalMetricIcon 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>
  );
}

function CalSegmented({ value, onChange }) {
  return (
    <div style={{
      display: "inline-flex", padding: 3,
      background: "var(--live-banner-bg)",
      border: "1px solid var(--live-border)", borderRadius: 8,
    }}>
      {["Day", "Week", "Month"].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>
  );
}

// Build June 2026 grid: Mon-Sun header, grid starts Mon May 26.
// June 2026: 1st = Monday. So week 1 is Mon May 26 - Sun Jun 1? Actually image shows:
// Row1: 26-27-28-29-30-31-1  (top-left is 26 Mon May, top-right is 1 Jun Sun)
// Row2: 2-8
// Row3: 9-15
// Row4: 16-22
// Row5: 23-29
// Row6: 30-6 (Jul)
// So the grid is Mon-start weeks containing June.

const WEEK_HEADER = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];

function buildGrid() {
  // We'll hardcode to match the reference exactly.
  const cells = [];
  // Row 1: May 26-31 + June 1
  cells.push({ d: 26, other: true });
  cells.push({ d: 27, other: true });
  cells.push({ d: 28, other: true });
  cells.push({ d: 29, other: true });
  cells.push({ d: 30, other: true });
  cells.push({ d: 31, other: true });
  cells.push({ d: 1 });
  // Row 2: 2-8
  for (let d = 2; d <= 8; d++) cells.push({ d });
  // Row 3: 9-15
  for (let d = 9; d <= 15; d++) cells.push({ d });
  // Row 4: 16-22
  for (let d = 16; d <= 22; d++) cells.push({ d });
  // Row 5: 23-29
  for (let d = 23; d <= 29; d++) cells.push({ d });
  // Row 6: 30 + July 1-6
  cells.push({ d: 30 });
  for (let d = 1; d <= 6; d++) cells.push({ d, other: true, nextMonth: true });
  return cells;
}

// Events keyed by day-of-June (positive) or negative for May other days / 100+ for July
const EVENTS = {
  1:  [{ time: "21:00", title: "Airbag", color: "green" }],
  4:  [{ time: "21:00", title: "Bad Bunny", color: "yellow" }],
  5:  [{ time: "18:00", title: "Fito Paez", color: "pink" }],
  27: [{ time: "21:00", title: "Franco Roadshow", color: "green" }],
  28: [{ time: "21:00", title: "Lali", color: "green" }],
  29: [{ time: "21:00", title: "Lali", color: "yellow" }],
  // Row 6 July
  103: [
    { time: "21:00", title: "Nicki Nicole", color: "green" },
    { time: "18:00", title: "Fito Paez", color: "pink" },
  ],
  105: [{ time: "21:00", title: "Bad Bunny", color: "yellow" }],
  106: [{ time: "21:00", title: "Bad Bunny", color: "yellow" }],
};

function EventChip({ time, title, color }) {
  const map = {
    green:  { bg: "#DDE9D9", fg: "#2E5A2E" },
    yellow: { bg: "#F4E8C9", fg: "#6B5117" },
    pink:   { bg: "#F2D6D3", fg: "#7A3430" },
  };
  const s = map[color] || map.green;
  return (
    <div style={{
      background: s.bg, color: s.fg,
      fontSize: 10.5, fontWeight: 500,
      padding: "3px 6px", borderRadius: 3,
      whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
      marginTop: 3,
    }}>
      {time} - {title}
    </div>
  );
}

function CalendarGrid({ selectedKey, onSelectEvent }) {
  const cells = buildGrid();
  const today = 14;
  return (
    <div style={{
      background: "var(--live-card)",
      border: "1px solid var(--live-border)",
      borderRadius: 10,
      overflow: "hidden",
    }}>
      {/* Week header */}
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(7, 1fr)",
        background: "var(--live-banner-bg)",
        borderBottom: "1px solid var(--live-border)",
      }}>
        {WEEK_HEADER.map((w) => (
          <div key={w} style={{
            padding: "10px 12px", fontSize: 10.5, fontWeight: 500,
            color: "var(--live-muted)", letterSpacing: "0.08em",
          }}>{w}</div>
        ))}
      </div>
      {/* 6 rows of 7 cells */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(7, 1fr)",
        gridAutoRows: "minmax(88px, 1fr)",
      }}>
        {cells.map((c, idx) => {
          const eventKey = c.nextMonth ? 100 + c.d : (c.other ? -c.d : c.d);
          const evts = EVENTS[eventKey] || [];
          const isToday = !c.other && c.d === today;
          const rowIdx = Math.floor(idx / 7);
          const colIdx = idx % 7;
          return (
            <div key={idx} style={{
              padding: "6px 8px",
              borderRight: colIdx < 6 ? "1px solid var(--live-border)" : "none",
              borderTop: rowIdx > 0 ? "1px solid var(--live-border)" : "none",
              minHeight: 88,
              display: "flex", flexDirection: "column",
              opacity: c.other ? 0.45 : 1,
            }}>
              <div style={{
                display: "flex", alignItems: "center",
                fontSize: 11.5, fontWeight: 500,
                color: "var(--live-muted)",
                marginBottom: 2,
              }}>
                {isToday ? (
                  <span style={{
                    width: 22, height: 22, borderRadius: 999,
                    background: "var(--live-heading)", color: "var(--live-card)",
                    display: "grid", placeItems: "center",
                    fontSize: 11, fontWeight: 600,
                  }}>{c.d}</span>
                ) : (
                  <span>{c.d}</span>
                )}
              </div>
              {evts.map((e, i) => (
                <div key={i} onClick={(ev) => { ev.stopPropagation(); onSelectEvent({ ...e, day: c.d, key: `${eventKey}-${i}` }); }}
                  style={{ cursor: "pointer", outline: selectedKey === `${eventKey}-${i}` ? "2px solid var(--live-primary)" : "none", borderRadius: 3 }}
                >
                  <EventChip {...e} />
                </div>
              ))}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ShowAvatar({ name }) {
  const seeds = {
    "Fito Paez":     { bg: "#E3D4C2", fg: "#6B4E2E" },
    "Lali":          { bg: "#2D2A33", fg: "#F2E7D5" },
    "Rels B":        { bg: "#E9DCC9", fg: "#6B5A3F" },
    "Nicki Nicole":  { bg: "#F3D9C4", fg: "#8B5E3C" },
    "Alejo Igoa":    { bg: "#E4E2DF", fg: "#3F3F46" },
    "Airbag":        { bg: "#2D2A33", fg: "#F2E7D5" },
    "Bad Bunny":     { bg: "#F3D9C4", fg: "#8B5E3C" },
  };
  const s = seeds[name] || { bg: "#E4E2DF", fg: "#3F3F46" };
  const initials = name.split(" ").map((p) => p[0]).slice(0, 2).join("");
  return (
    <div style={{
      width: 34, height: 34, borderRadius: 999,
      background: s.bg, color: s.fg,
      display: "grid", placeItems: "center",
      fontSize: 11, fontWeight: 600, flexShrink: 0,
      border: "1px solid var(--live-border)",
    }}>{initials}</div>
  );
}

function UpcomingList({ onSelect }) {
  const shows = [
    { name: "Fito Paez",    venue: "River",         dates: "13/02/2026 - 14/02/2026" },
    { name: "Lali",         venue: "Velez",         dates: "13/02/2026 - 14/02/2026" },
    { name: "Rels B",       venue: "River",         dates: "13/02/2026 - 14/02/2026" },
    { name: "Nicki Nicole", venue: "River",         dates: "13/02/2026 - 14/02/2026" },
    { name: "Lali",         venue: "Velez",         dates: "13/02/2026 - 14/02/2026" },
    { name: "Lali",         venue: "Velez",         dates: "13/02/2026 - 14/02/2026" },
    { name: "Alejo Igoa",   venue: "Movistar Arena",dates: "13/02/2026 - 14/02/2026" },
    { name: "Airbag",       venue: "River",         dates: "13/02/2026 - 14/02/2026" },
    { name: "Lali",         venue: "Velez",         dates: "13/02/2026 - 14/02/2026" },
    { name: "Airbag",       venue: "River",         dates: "13/02/2026 - 14/02/2026" },
  ];
  return (
    <div>
      <div style={{ fontSize: 13, fontWeight: 600, color: "var(--live-heading)", marginBottom: 10 }}>Próximos shows</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        {shows.map((s, i) => (
          <div key={i} onClick={() => onSelect(s)} style={{
            display: "flex", alignItems: "center", gap: 10,
            padding: "7px 8px",
            background: "var(--live-card)",
            border: "1px solid var(--live-border)",
            borderRadius: 8,
            cursor: "pointer",
            transition: "background 120ms ease-out",
          }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--live-row-hover)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "var(--live-card)"}
          >
            <ShowAvatar name={s.name} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--live-heading)" }}>{s.name}</div>
              <div style={{ fontSize: 10.5, color: "var(--live-muted)", display: "flex", alignItems: "center", gap: 4, marginTop: 1 }}>
                <i data-lucide="map-pin" style={{ width: 10, height: 10 }} />
                {s.venue}
              </div>
              <div style={{ fontSize: 10.5, color: "var(--live-muted)", display: "flex", alignItems: "center", gap: 4, marginTop: 1 }}>
                <i data-lucide="calendar" style={{ width: 10, height: 10 }} />
                {s.dates}
              </div>
            </div>
            <span style={{
              padding: "2px 8px", background: "#E3F3E3", color: "#1F6B2F",
              fontSize: 10.5, fontWeight: 500, borderRadius: 4,
            }}>Active</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function ShowInfoSection({ icon, title, children }) {
  return (
    <div style={{ paddingBottom: 14, marginBottom: 14, borderBottom: "1px solid var(--live-border)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6, fontSize: 12, fontWeight: 600, color: "var(--live-heading)" }}>
        <i data-lucide={icon} style={{ width: 12, height: 12, color: "var(--live-muted)" }} />
        {title}
      </div>
      <div style={{ fontSize: 11.5, color: "var(--live-body)", lineHeight: 1.7 }}>{children}</div>
    </div>
  );
}

function InfoRow({ label, value }) {
  return (
    <div>
      <span style={{ color: "var(--live-muted)" }}>{label}: </span>
      <span style={{ color: "var(--live-heading)", fontWeight: 500 }}>{value}</span>
    </div>
  );
}

function SelectedShowInfo({ show, onClose }) {
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: "var(--live-heading)" }}>Información del show</div>
        <button onClick={onClose} style={{
          background: "transparent", border: "none", color: "var(--live-muted)",
          cursor: "pointer", width: 24, height: 24, borderRadius: 6,
          display: "grid", placeItems: "center",
        }}>
          <i data-lucide="edit-3" style={{ width: 13, height: 13 }} />
        </button>
      </div>

      {/* Show card */}
      <div style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: "8px 10px",
        background: "var(--live-card)",
        border: "1px solid var(--live-border)",
        borderRadius: 8, marginBottom: 16,
      }}>
        <ShowAvatar name={show.name} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--live-heading)" }}>{show.name}</div>
          <div style={{ fontSize: 10.5, color: "var(--live-muted)", display: "flex", alignItems: "center", gap: 4, marginTop: 1 }}>
            <i data-lucide="map-pin" style={{ width: 10, height: 10 }} />
            {show.venue}
          </div>
          <div style={{ fontSize: 10.5, color: "var(--live-muted)", display: "flex", alignItems: "center", gap: 4, marginTop: 1 }}>
            <i data-lucide="calendar" style={{ width: 10, height: 10 }} />
            {show.dates}
          </div>
        </div>
        <span style={{
          padding: "2px 8px", background: "#E3F3E3", color: "#1F6B2F",
          fontSize: 10.5, fontWeight: 500, borderRadius: 4,
        }}>Active</span>
      </div>

      <ShowInfoSection icon="credit-card" title="Información de preventa">
        <InfoRow label="Fecha Preventa" value="23/10/2025" />
        <InfoRow label="Hora Preventa" value="12:00" />
        <InfoRow label="Banco" value="Santander Rio" />
      </ShowInfoSection>

      <ShowInfoSection icon="ticket" title="Ticketera">
        <InfoRow label="Plataforma" value="All Access" />
      </ShowInfoSection>

      <ShowInfoSection icon="map-pin" title="Ubicación">
        <InfoRow label="Venue" value="Estadio River" />
        <InfoRow label="Ciudad" value="Buenos Aires" />
        <InfoRow label="País" value="Argentina" />
      </ShowInfoSection>

      <ShowInfoSection icon="users" title="Capacidad Venue">
        <InfoRow label="Cantidad" value="65.000 personas" />
      </ShowInfoSection>

      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6, fontSize: 12, fontWeight: 600, color: "var(--live-heading)" }}>
          <i data-lucide="info" style={{ width: 12, height: 12, color: "var(--live-muted)" }} />
          Información del sistema
        </div>
        <div style={{ fontSize: 11.5, color: "var(--live-body)", lineHeight: 1.7 }}>
          <InfoRow label="Creado" value="21/11/2025" />
          <InfoRow label="Última Actualización" value="24/02/2026" />
        </div>
      </div>
    </div>
  );
}

function CalendarPane() {
  const [view, setView] = useStateCal("Month");
  const [selected, setSelected] = useStateCal(null);
  const [wizOpen, setWizOpen] = useStateCal(false);

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

  const handleSelectEvent = (e) => {
    // Map event title to upcoming-show-like record
    setSelected({ name: e.title, venue: "River", dates: "13/02/2026 - 14/02/2026", fromEvent: true, key: e.key });
  };

  return (
    <div style={{ padding: "28px 36px 40px", overflow: "auto", height: "100%" }}>
      <CalMetrics />

      {/* Calendar toolbar */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        marginBottom: 16,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
            <button style={{
              width: 28, height: 28, borderRadius: 6,
              background: "transparent", border: "none", cursor: "pointer",
              display: "grid", placeItems: "center", color: "var(--live-muted)",
            }}><i data-lucide="chevron-left" style={{ width: 14, height: 14 }} /></button>
            <div style={{ fontSize: 17, fontWeight: 600, color: "var(--live-heading)", margin: "0 6px" }}>June 2026</div>
            <button style={{
              width: 28, height: 28, borderRadius: 6,
              background: "transparent", border: "none", cursor: "pointer",
              display: "grid", placeItems: "center", color: "var(--live-muted)",
            }}><i data-lucide="chevron-right" style={{ width: 14, height: 14 }} /></button>
          </div>
          <CalSegmented value={view} onChange={setView} />
        </div>
        <button onClick={() => setWizOpen(true)} style={{
          appearance: "none", border: "none",
          background: "var(--live-primary)", color: "#fff",
          height: 36, padding: "0 16px", fontSize: 13, fontWeight: 500,
          borderRadius: 8, cursor: "pointer",
          display: "inline-flex", alignItems: "center", gap: 6,
          fontFamily: "var(--font-sans)",
        }}>
          <i data-lucide="plus" style={{ width: 14, height: 14 }} />
          Create Show
        </button>
      </div>

      {/* Main grid + side column */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 280px", gap: 20 }}>
        <CalendarGrid selectedKey={selected && selected.key} onSelectEvent={handleSelectEvent} />
        <div>
          {selected ? (
            <SelectedShowInfo show={selected} onClose={() => setSelected(null)} />
          ) : (
            <UpcomingList onSelect={(s) => setSelected({ ...s, key: `upcoming-${s.name}-${s.venue}` })} />
          )}
        </div>
      </div>

      {window.CreateShowWizard && (
        <window.CreateShowWizard
          open={wizOpen}
          onClose={() => setWizOpen(false)}
          onCreate={() => {}}
        />
      )}
    </div>
  );
}

Object.assign(window, { CalendarPane });
