/* ============================================================
   ADMIN · WEEKLY NIGHTS — edit the 7 recurring nights live.
   Writes overrides to PPDB.nights (merged over PP.NIGHTS), so the
   home "Seven Nights" section + the Events calendar update with no
   code change. Reset returns a night to its built-in default.
   ============================================================ */
function useNights() {
  const [list, setList] = useState(() => window.PPDB.getNights());
  useEffect(() => {
    const f = () => setList(window.PPDB.getNights());
    window.addEventListener("pp:nights", f);
    return () => window.removeEventListener("pp:nights", f);
  }, []);
  return list;
}

function NightsModule() {
  const t = useT(); const { lang } = useLang();
  const list = useNights();
  const [editing, setEditing] = useState(null); // index
  const [draft, setDraft] = useState(null);
  const ov = window.PPDB.nights.ov();

  const startEdit = (i) => {
    const n = list[i];
    setDraft({ name: n.name || "", time: n.time || "", dj: n.dj || "", bottle: n.bottle || "", table: n.table || "", dEn: (n.d && n.d.en) || "", dEs: (n.d && n.d.es) || "" });
    setEditing(i);
  };
  const save = () => {
    window.PPDB.nights.update(editing, {
      name: draft.name.trim(), time: draft.time.trim(), dj: draft.dj.trim(),
      bottle: draft.bottle.trim(), table: draft.table.trim(),
      d: { en: draft.dEn.trim(), es: draft.dEs.trim() },
    });
    window.toast(t("Night updated.", "Noche actualizada."));
    setEditing(null); setDraft(null);
  };
  const reset = (i) => { if (confirm(t("Reset this night to its default?", "¿Restablecer esta noche al valor por defecto?"))) window.PPDB.nights.reset(i); };

  const IN = "w-full bg-ink border border-white/12 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35";
  const LB = "label text-white/45 text-[10px] block mb-1.5";

  return (
    <div>
      <div className="rounded-2xl border border-gold/25 bg-gold/5 p-4 mb-6 flex items-center gap-3">
        <Icon name="calendar-clock" className="w-5 h-5 text-gold-soft shrink-0" />
        <p className="text-white/65 text-sm">{t("These are the 7 recurring weekly nights shown on the home page and Events calendar. Edits go live instantly. Use one-off Events for special dates.", "Estas son las 7 noches semanales que se muestran en el inicio y el calendario de Eventos. Los cambios salen al instante. Usa Eventos para fechas especiales.")}</p>
      </div>

      <div className="space-y-2.5">
        {list.map((n, i) => {
          const edited = !!ov[i];
          return (
            <div key={i} className="rounded-2xl border border-white/10 bg-card p-4">
              <div className="flex items-center gap-3.5">
                <div className="w-12 h-12 rounded-xl bg-coral/12 border border-coral/30 flex flex-col items-center justify-center shrink-0 text-coral leading-none"><span className="text-[11px] font-extrabold">{L(n.day, lang)}</span></div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="font-bold text-sm truncate">{n.name}</span>
                    {edited && <span className="px-2 py-0.5 rounded-full bg-gold/15 text-gold-soft text-[9px] font-bold uppercase tracking-wider">{t("Edited", "Editada")}</span>}
                  </div>
                  <div className="text-white/50 text-[12px] mt-0.5 flex items-center gap-x-3 gap-y-0.5 flex-wrap">
                    <span className="inline-flex items-center gap-1"><Icon name="clock" className="w-3 h-3" />{n.time}</span>
                    <span className="inline-flex items-center gap-1"><Icon name="disc-3" className="w-3 h-3" />{n.dj}</span>
                    <span className="inline-flex items-center gap-1"><Icon name="wine" className="w-3 h-3" />{n.bottle}</span>
                  </div>
                </div>
                {edited && <button onClick={() => reset(i)} className="px-3 py-1.5 rounded-full border border-white/15 text-white/45 text-[10px] font-bold uppercase tracking-wider hover:text-white">{t("Reset", "Restablecer")}</button>}
                <button onClick={() => editing === i ? setEditing(null) : startEdit(i)} className="px-3 py-1.5 rounded-full bg-coral/15 border border-coral/40 text-coral text-[10px] font-bold uppercase tracking-wider hover:bg-coral hover:text-white transition-all">{editing === i ? t("Close", "Cerrar") : t("Edit", "Editar")}</button>
              </div>

              {editing === i && draft && (
                <div className="mt-4 pt-4 border-t border-white/8 fade-view grid sm:grid-cols-2 gap-3">
                  <div><span className={LB}>{t("Name", "Nombre")}</span><input value={draft.name} onChange={(e) => setDraft({ ...draft, name: e.target.value })} className={IN} /></div>
                  <div><span className={LB}>{t("Time", "Horario")}</span><input value={draft.time} onChange={(e) => setDraft({ ...draft, time: e.target.value })} placeholder="12PM – 5AM" className={IN} /></div>
                  <div><span className={LB}>DJ</span><input value={draft.dj} onChange={(e) => setDraft({ ...draft, dj: e.target.value })} className={IN} /></div>
                  <div className="grid grid-cols-2 gap-3">
                    <div><span className={LB}>{t("Bottles", "Botellas")}</span><input value={draft.bottle} onChange={(e) => setDraft({ ...draft, bottle: e.target.value })} placeholder="$150++" className={IN} /></div>
                    <div><span className={LB}>{t("Table", "Mesa")}</span><input value={draft.table} onChange={(e) => setDraft({ ...draft, table: e.target.value })} placeholder="$150++" className={IN} /></div>
                  </div>
                  <div className="sm:col-span-2"><span className={LB}>{t("Description (EN)", "Descripción (EN)")}</span><textarea value={draft.dEn} onChange={(e) => setDraft({ ...draft, dEn: e.target.value })} rows={2} className={IN + " resize-none"} /></div>
                  <div className="sm:col-span-2"><span className={LB}>{t("Description (ES)", "Descripción (ES)")}</span><textarea value={draft.dEs} onChange={(e) => setDraft({ ...draft, dEs: e.target.value })} rows={2} className={IN + " resize-none"} /></div>
                  <div className="sm:col-span-2 flex justify-end gap-2">
                    <button onClick={() => { setEditing(null); setDraft(null); }} className="px-5 py-2.5 rounded-full border border-white/15 text-white/65 text-[11px] font-bold uppercase tracking-wider hover:bg-white/5">{t("Cancel", "Cancelar")}</button>
                    <button onClick={save} className="gbtn px-6 py-2.5 rounded-full bg-coral hover:bg-coral-deep text-white text-[11px] font-bold uppercase tracking-wider">{t("Save", "Guardar")}</button>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { NightsModule, useNights });
