// Create Show wizard — 5-step modal triggered from the Calendar "Create Show" button.

const { useState: useStateWiz, useEffect: useEffectWiz } = React;

// ────────────────────────────── Atoms ──────────────────────────────

function WizField({ label, children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: "var(--live-heading)", letterSpacing: "-0.005em" }}>
        {label}
      </div>
      {children}
    </div>
  );
}

function WizSelect({ value, onChange, placeholder = "Select", options = [] }) {
  return (
    <div style={{ position: "relative" }}>
      <select
        value={value || ""}
        onChange={(e) => onChange && onChange(e.target.value)}
        style={{
          width: "100%",
          appearance: "none", WebkitAppearance: "none", MozAppearance: "none",
          border: "1px solid var(--live-border-strong)",
          borderRadius: 8,
          padding: "10px 14px",
          fontSize: 13,
          color: value ? "var(--live-heading)" : "var(--live-muted)",
          background: "var(--live-card)",
          fontFamily: "var(--font-sans)",
          outline: "none",
          cursor: "pointer",
        }}
      >
        <option value="" disabled>{placeholder}</option>
        {options.map((o) => (
          <option key={o} value={o}>{o}</option>
        ))}
      </select>
      <span style={{
        position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)",
        color: "var(--live-muted)", pointerEvents: "none",
        display: "inline-flex", flexDirection: "column", lineHeight: 0.6, fontSize: 10,
      }}>
        <span>▴</span><span style={{ marginTop: 2 }}>▾</span>
      </span>
    </div>
  );
}

function WizInput({ value, onChange, placeholder = "" , type = "text" }) {
  return (
    <input
      type={type}
      value={value || ""}
      onChange={(e) => onChange && onChange(e.target.value)}
      placeholder={placeholder}
      style={{
        width: "100%",
        border: "1px solid var(--live-border-strong)",
        borderRadius: 8,
        padding: "10px 14px",
        fontSize: 13,
        color: "var(--live-heading)",
        background: "var(--live-card)",
        fontFamily: "var(--font-sans)",
        outline: "none",
        boxSizing: "border-box",
      }}
    />
  );
}

function WizDateTime({ value, onChange, placeholder = "dd/mm/aaaa, --:-- ----" }) {
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 10,
      border: "1px solid var(--live-border-strong)",
      borderRadius: 8,
      padding: "10px 14px",
      background: "var(--live-card)",
    }}>
      <i data-lucide="calendar" style={{ width: 14, height: 14, color: "var(--live-muted)", flexShrink: 0 }} />
      <input
        value={value || ""}
        onChange={(e) => onChange && onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          flex: 1, border: "none", outline: "none", background: "transparent",
          fontSize: 13, color: value ? "var(--live-heading)" : "var(--live-muted)",
          fontFamily: "var(--font-sans)",
        }}
      />
    </div>
  );
}

// ────────────────────────────── Stepper ──────────────────────────────

function WizStepper({ step, total }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${total}, 1fr)`, gap: 6 }}>
      {Array.from({ length: total }).map((_, i) => {
        const active = i <= step;
        return (
          <div key={i} style={{
            height: 3, borderRadius: 999,
            background: active ? "var(--live-primary)" : "#E4E2DF",
          }} />
        );
      })}
    </div>
  );
}

// ────────────────────────────── Steps ──────────────────────────────

function Step1Show({ data, set }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <WizField label="Artist">
        <WizSelect
          value={data.artist}
          onChange={(v) => set({ artist: v })}
          options={["Bad Bunny", "Fito Páez", "Wos", "Trueno", "María Becerra"]}
        />
      </WizField>
      <WizField label="Show status">
        <WizSelect
          value={data.status}
          onChange={(v) => set({ status: v })}
          options={["Active", "Borrador", "Pendiente", "Confirmado"]}
        />
      </WizField>
      <WizField label="Tipo de show">
        <WizSelect
          value={data.tipo}
          onChange={(v) => set({ tipo: v })}
          options={["Estadio", "Arena", "Teatro", "Festival", "Club"]}
        />
      </WizField>
      <WizField label="Venue">
        <WizSelect
          value={data.venue}
          onChange={(v) => set({ venue: v })}
          options={["River Plate", "Vélez Sarsfield", "Movistar Arena", "Luna Park", "Estadio Único"]}
        />
      </WizField>
    </div>
  );
}

function Step2Dates({ data, set }) {
  const dates = data.dates && data.dates.length ? data.dates : [""];
  const updateDate = (i, v) => {
    const next = [...dates];
    next[i] = v;
    set({ dates: next });
  };
  const addDate = () => set({ dates: [...dates, ""] });

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {dates.map((d, i) => (
        <WizField key={i} label={i === 0 ? "Fecha del show" : `Fecha ${i + 1}`}>
          <WizDateTime value={d} onChange={(v) => updateDate(i, v)} />
        </WizField>
      ))}
      <button
        onClick={addDate}
        style={{
          alignSelf: "flex-start",
          background: "transparent", border: "none", padding: "4px 0",
          color: "var(--live-primary)", fontSize: 13, fontWeight: 500,
          cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6,
          fontFamily: "var(--font-sans)",
        }}
      >
        <i data-lucide="plus" style={{ width: 12, height: 12 }} />
        Agregar fecha
      </button>
    </div>
  );
}

function Step3PerDate({ data, set }) {
  const dates = (data.dates && data.dates.length ? data.dates : ["Vie 5 feb 2027, 22:00"])
    .map((d) => d || "Vie 5 feb 2027, 22:00");
  const [openIdx, setOpenIdx] = useStateWiz(0);
  useEffectWiz(() => { if (window.lucide) window.lucide.createIcons(); });

  const perDate = data.perDate || {};
  const updatePerDate = (i, key, v) => {
    const next = { ...perDate, [i]: { ...(perDate[i] || {}), [key]: v } };
    set({ perDate: next });
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {dates.map((label, i) => {
        const open = openIdx === i;
        const d = perDate[i] || {};
        return (
          <div key={i} style={{
            background: "var(--live-banner-bg)",
            border: "1px solid var(--live-border)",
            borderRadius: 10,
            padding: open ? "12px 14px 14px" : "12px 14px",
          }}>
            <div
              onClick={() => setOpenIdx(open ? -1 : i)}
              style={{
                display: "flex", alignItems: "center", justifyContent: "space-between",
                cursor: "pointer", marginBottom: open ? 10 : 0,
              }}
            >
              <div style={{ fontSize: 13, fontWeight: 700, color: "var(--live-heading)", letterSpacing: "-0.005em" }}>
                {label}
              </div>
              <i data-lucide={open ? "chevron-up" : "chevron-down"}
                 style={{ width: 13, height: 13, color: "var(--live-muted)" }} />
            </div>

            {open && (
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <WizField label="Inicio de venta">
                  <WizDateTime
                    value={d.venta}
                    onChange={(v) => updatePerDate(i, "venta", v)}
                  />
                </WizField>
                <WizField label="Inicio de preventa">
                  <WizDateTime
                    value={d.preventa}
                    onChange={(v) => updatePerDate(i, "preventa", v)}
                  />
                </WizField>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <WizField label="Banco de preventa">
                    <WizInput
                      placeholder="Santander"
                      value={d.banco}
                      onChange={(v) => updatePerDate(i, "banco", v)}
                    />
                  </WizField>
                  <WizField label="Cupo de preventa">
                    <WizInput
                      placeholder="1500"
                      value={d.cupo}
                      onChange={(v) => updatePerDate(i, "cupo", v)}
                    />
                  </WizField>
                </div>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function Step4Ticketing({ data, set }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <WizField label="Ticketing Platform">
        <WizSelect
          value={data.platform}
          onChange={(v) => set({ platform: v })}
          options={["Tu Entrada", "Ticketek", "AllAccess", "Eventbrite"]}
        />
      </WizField>
      <WizField label="Ticketing Account">
        <WizSelect
          value={data.account}
          onChange={(v) => set({ account: v })}
          placeholder={data.platform ? "Select" : "Select a platform first"}
          options={data.platform ? ["Cuenta Principal", "Cuenta Secundaria"] : []}
        />
      </WizField>
      <WizField label="Moneda">
        <WizSelect
          value={data.moneda}
          onChange={(v) => set({ moneda: v })}
          options={["ARS", "USD", "EUR"]}
        />
      </WizField>
      <WizField label="Streaming">
        <WizSelect
          value={data.streaming}
          onChange={(v) => set({ streaming: v })}
          options={["Sí", "No"]}
        />
      </WizField>
    </div>
  );
}

function Step5More({ data, set }) {
  return (
    <div>
      <WizField label="Observaciones">
        <textarea
          value={data.observaciones || ""}
          onChange={(e) => set({ observaciones: e.target.value })}
          placeholder="Write here"
          style={{
            width: "100%",
            border: "1px solid var(--live-border-strong)",
            borderRadius: 8,
            padding: "12px 14px",
            fontSize: 13,
            color: "var(--live-heading)",
            background: "var(--live-card)",
            fontFamily: "var(--font-sans)",
            outline: "none",
            minHeight: 140,
            resize: "vertical",
            boxSizing: "border-box",
          }}
        />
      </WizField>
    </div>
  );
}

// ────────────────────────────── Wizard ──────────────────────────────

const WIZ_STEPS = [
  { title: "Complete your show's data", subtitle: null,
    Comp: Step1Show },
  { title: "Complete your show's data",
    subtitle: "Agregá todas las fechas del show. Luego configurás venta y preventa por cada fecha.",
    Comp: Step2Dates },
  { title: "Complete your show's data",
    subtitle: "Abrí cada fecha y completá inicio de venta, preventa y cupo si aplica.",
    Comp: Step3PerDate },
  { title: "Complete your show's data",
    subtitle: "Ticketera, moneda y streaming valen para todo el show.",
    Comp: Step4Ticketing },
  { title: "More about the show", subtitle: null, Comp: Step5More },
];

function CreateShowWizard({ open, onClose, onCreate }) {
  const [step, setStep] = useStateWiz(0);
  const [data, setData] = useStateWiz({});
  useEffectWiz(() => { if (window.lucide) window.lucide.createIcons(); }, [step, open]);

  // Reset on open
  useEffectWiz(() => {
    if (open) {
      setStep(0);
      setData({});
    }
  }, [open]);

  if (!open) return null;
  const total = WIZ_STEPS.length;
  const cur = WIZ_STEPS[step];
  const Comp = cur.Comp;
  const isLast = step === total - 1;
  const isFirst = step === 0;

  const set = (patch) => setData((d) => ({ ...d, ...patch }));

  const back = () => {
    if (isFirst) onClose && onClose();
    else setStep(step - 1);
  };
  const next = () => {
    if (isLast) {
      onCreate && onCreate(data);
      onClose && onClose();
    } else {
      setStep(step + 1);
    }
  };

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{
          position: "fixed", inset: 0,
          background: "rgba(15,18,28,0.32)",
          zIndex: 80,
        }}
      />
      {/* Modal */}
      <div style={{
        position: "fixed", inset: 0, zIndex: 81,
        display: "grid", placeItems: "center",
        pointerEvents: "none",
      }}>
        <div style={{
          pointerEvents: "auto",
          width: 440,
          maxHeight: "min(86vh, 640px)",
          background: "var(--live-card)",
          border: "1px solid var(--live-border)",
          borderRadius: 14,
          boxShadow: "0 24px 64px rgba(15,18,28,0.18)",
          padding: "22px 24px 20px",
          display: "flex", flexDirection: "column",
          fontFamily: "var(--font-sans)",
        }}>
          {/* Stepper */}
          <WizStepper step={step} total={total} />

          {/* Header */}
          <div style={{ marginTop: 16 }}>
            <div style={{
              fontSize: 18, fontWeight: 700, color: "var(--live-heading)",
              letterSpacing: "-0.012em",
            }}>
              {cur.title}
            </div>
            {cur.subtitle && (
              <div style={{
                fontSize: 12.5, color: "var(--live-muted)",
                marginTop: 5, lineHeight: 1.5,
              }}>
                {cur.subtitle}
              </div>
            )}
          </div>

          {/* Body */}
          <div style={{
            marginTop: 16,
            flex: 1,
            overflowY: "auto",
            paddingRight: 4,
            minHeight: 160,
          }}>
            <Comp data={data} set={set} />
          </div>

          {/* Footer */}
          <div style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            marginTop: 18, paddingTop: 14,
          }}>
            <button
              onClick={back}
              style={{
                background: "var(--live-card)",
                border: "1.25px solid var(--live-primary)",
                color: "var(--live-primary)",
                borderRadius: 8,
                padding: "8px 18px",
                fontSize: 13, fontWeight: 600,
                cursor: "pointer", fontFamily: "var(--font-sans)",
              }}
            >
              {isFirst ? "Cancel" : "Back"}
            </button>
            <button
              onClick={next}
              style={{
                background: "var(--live-primary)",
                border: "1.25px solid var(--live-primary)",
                color: "#fff",
                borderRadius: 8,
                padding: "8px 22px",
                fontSize: 13, fontWeight: 600,
                cursor: "pointer", fontFamily: "var(--font-sans)",
              }}
            >
              {isLast ? "Create" : "Next"}
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { CreateShowWizard });
