/* QuickRegisterSheet (flujo motorista: panel 2x2 + teclado) → window. */
(function () {
  const { useState, useEffect, useRef } = React;
  const { useData, todayISO, fmt, fmtDiaCorto, fmtFechaLarga, Spinner, BackIcon, CloseIcon } = window;

  const FIELD_CONFIG = {
    ingreso:       { label: "Ingreso",      color: "#58CC02", shadow: "#46A302", bg: "#DFFBC2", emoji: "💰" },
    gasolina:      { label: "Gasolina",     color: "#FF4B4B", shadow: "#CC3B3B", bg: "#FFE3E3", emoji: "⛽" },
    mantenimiento: { label: "Mantenim.",    color: "#D4A200", shadow: "#AD8600", bg: "#FFF4C2", emoji: "🔧" },
  };

  function QuickRegisterSheet({ open, onClose }) {
    const { upsert, records } = useData();
    const [fecha, setFecha] = useState(todayISO());
    const [view, setView] = useState("panel"); // "panel" | "ingreso" | "gasolina" | "mantenimiento"
    const [amount, setAmount] = useState("");
    const [saving, setSaving] = useState(false);
    const [flash, setFlash] = useState("");
    const [error, setError] = useState("");
    const dateRef = useRef(null);

    useEffect(() => {
      if (open) {
        setView("panel");
        setAmount("");
        setFecha(todayISO());
        setFlash("");
        setError("");
      }
    }, [open]);

    useEffect(() => {
      if (!flash) return;
      const t = setTimeout(() => setFlash(""), 1600);
      return () => clearTimeout(t);
    }, [flash]);

    if (!open) return null;

    const existing = records.find(r => r.fecha === fecha) || { ingreso: 0, gasolina: 0, mantenimiento: 0, nota: "" };

    const pickDate = () => {
      const el = dateRef.current;
      if (!el) return;
      try { el.showPicker ? el.showPicker() : el.click(); }
      catch { el.click(); }
    };

    const press = (k) => {
      setError("");
      if (k === "C") { setAmount(""); return; }
      if (k === "⌫") { setAmount(s => s.slice(0, -1)); return; }
      if (amount === "0") { setAmount(k); return; }
      if (amount.length >= 9) return;
      setAmount(s => s + k);
    };

    const isField = view !== "panel";
    const fc = isField ? FIELD_CONFIG[view] : null;
    const n = Number(amount) || 0;
    const canSave = isField && n > 0 && !saving;

    const save = async () => {
      if (!canSave) return;
      setSaving(true);
      setError("");
      const next = {
        fecha,
        ingreso: Number(existing.ingreso) || 0,
        gasolina: Number(existing.gasolina) || 0,
        mantenimiento: Number(existing.mantenimiento) || 0,
        nota: existing.nota || "",
      };
      next[view] = (next[view] || 0) + n;
      try {
        await upsert(next);
        setFlash(`+${fmt(n)} agregado`);
        setAmount("");
      } catch (e) {
        console.warn("quick save error:", e);
        setError("No se pudo guardar. Revisa tu conexión.");
      } finally {
        setSaving(false);
      }
    };

    const totalField = isField ? (Number(existing[view]) || 0) : 0;

    return (
      <div className="fixed inset-0 z-50 flex items-end justify-center" style={{ background: "rgba(0,0,0,0.55)" }} onClick={onClose}>
        <div className="w-full max-w-[430px] bg-white rounded-t-3xl p-5 pb-7 sheet-enter max-h-[95vh] overflow-y-auto hide-scroll" onClick={e => e.stopPropagation()}>
          {/* HEADER */}
          <div className="flex justify-between items-center mb-4">
            {isField ? (
              <button onClick={() => { setView("panel"); setAmount(""); setFlash(""); }}
                      className="w-11 h-11 rounded-full bg-[#F0F0F0] flex items-center justify-center">
                <BackIcon />
              </button>
            ) : <div className="w-11 h-11" />}
            <h2 className="text-xl font-black text-[#3C3C3C]">
              {isField ? fc.label : "Registrar viaje"}
            </h2>
            <button onClick={onClose} className="w-11 h-11 rounded-full bg-[#F0F0F0] flex items-center justify-center">
              <CloseIcon />
            </button>
          </div>

          <input ref={dateRef} type="date" value={fecha}
                 onChange={e => setFecha(e.target.value || todayISO())}
                 style={{ position: "absolute", opacity: 0, pointerEvents: "none", width: 0, height: 0 }} />

          {!isField && (
            <>
              <p className="text-center text-xs font-black uppercase tracking-widest text-[#777] mb-4">
                {fmtFechaLarga(fecha)}
              </p>
              <div className="grid grid-cols-2 gap-4">
                <button onClick={() => setView("ingreso")}
                        className="btn-3d btn-green h-36 rounded-3xl text-white font-black flex flex-col items-center justify-center gap-2">
                  <span className="text-5xl leading-none">💰</span>
                  <span className="text-lg uppercase tracking-wide">Ingreso</span>
                </button>
                <button onClick={() => setView("gasolina")}
                        className="btn-3d btn-red h-36 rounded-3xl text-white font-black flex flex-col items-center justify-center gap-2">
                  <span className="text-5xl leading-none">⛽</span>
                  <span className="text-lg uppercase tracking-wide">Gasolina</span>
                </button>
                <button onClick={() => setView("mantenimiento")}
                        className="btn-3d h-36 rounded-3xl text-white font-black flex flex-col items-center justify-center gap-2"
                        style={{ background: "#FFC800", boxShadow: "0 4px 0 #D4A200" }}>
                  <span className="text-5xl leading-none">🔧</span>
                  <span className="text-lg uppercase tracking-wide">Mantenim.</span>
                </button>
                <button onClick={pickDate}
                        className="btn-3d btn-white h-36 rounded-3xl font-black text-[#3C3C3C] flex flex-col items-center justify-center gap-1">
                  <span className="text-5xl leading-none">📅</span>
                  <span className="text-base uppercase tracking-wide">Fecha</span>
                  <span className="text-[11px] font-bold text-[#58CC02] mt-1">{fmtDiaCorto(fecha)}</span>
                </button>
              </div>

              <div className="mt-6 grid grid-cols-3 gap-2 text-center bg-[#F9F9F9] rounded-2xl py-3 px-2">
                <div>
                  <div className="text-[10px] font-black uppercase text-[#777]">Ingreso</div>
                  <div className="text-sm font-black text-[#58CC02]">{fmt(existing.ingreso)}</div>
                </div>
                <div className="border-x border-[#EEE]">
                  <div className="text-[10px] font-black uppercase text-[#777]">Gasolina</div>
                  <div className="text-sm font-black text-[#FF4B4B]">{fmt(existing.gasolina)}</div>
                </div>
                <div>
                  <div className="text-[10px] font-black uppercase text-[#777]">Mantenim.</div>
                  <div className="text-sm font-black text-[#D4A200]">{fmt(existing.mantenimiento)}</div>
                </div>
              </div>
            </>
          )}

          {isField && (
            <>
              <div className="flex items-center justify-between mb-3">
                <button onClick={pickDate}
                        className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#F0F0F0] font-black text-sm text-[#3C3C3C] active:scale-[0.97] transition">
                  <span>📅</span><span>{fmtDiaCorto(fecha)}</span>
                </button>
                <div className="text-right">
                  <div className="text-[10px] font-black uppercase text-[#777]">Total {fc.label.toLowerCase()} hoy</div>
                  <div className="text-sm font-black" style={{ color: fc.color }}>{fmt(totalField)}</div>
                </div>
              </div>

              {/* Display */}
              <div className="rounded-2xl p-5 mb-4 text-center" style={{ background: fc.bg }}>
                <div className="text-[10px] font-black uppercase tracking-widest" style={{ color: fc.color, opacity: 0.7 }}>
                  Monto del viaje
                </div>
                <div className="text-4xl font-black mt-1" style={{ color: fc.color }}>
                  RD$ {amount === "" ? "0" : Number(amount).toLocaleString("es-DO")}
                </div>
                <div className="h-5 mt-1 text-sm font-black" style={{ color: fc.color, opacity: flash ? 1 : 0, transition: "opacity 200ms" }}>
                  {flash || "\u00A0"}
                </div>
              </div>

              {/* Teclado */}
              <div className="grid grid-cols-3 gap-3 mb-4">
                {["7","8","9","4","5","6","1","2","3","C","0","⌫"].map(k => (
                  <button key={k} onClick={() => press(k)}
                          className="btn-3d btn-white h-16 rounded-2xl font-black text-3xl text-[#3C3C3C] active:scale-[0.97] transition">
                    {k}
                  </button>
                ))}
              </div>

              {error && <p className="text-center text-sm text-[#FF4B4B] font-bold mb-3">{error}</p>}

              <button onClick={save} disabled={!canSave}
                      className="btn-3d w-full h-16 rounded-full text-white font-black uppercase tracking-wide flex items-center justify-center gap-2 text-lg"
                      style={{
                        background: canSave ? fc.color : "#CCC",
                        boxShadow: canSave ? `0 4px 0 ${fc.shadow}` : "0 4px 0 #AAA",
                      }}>
                {saving && <Spinner size={20} color="#FFFFFF" />}
                {saving ? "Guardando..." : `Guardar ${fc.label.toLowerCase()}`}
              </button>
            </>
          )}
        </div>
      </div>
    );
  }

  window.QuickRegisterSheet = QuickRegisterSheet;
})();
