// Sidebar y Topbar

// ── Hash util (SHA-256 via Web Crypto API) ─────────────────────────────────
async function sha256(str) {
  const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(str));
  return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, "0")).join("");
}

// PIN dueño por defecto: "1234"
const DEFAULT_PIN_HASH = "03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4";
const PIN_KEY          = "taller_pin_hash";
const SESSION_KEY      = "taller_owner";

// PIN admin — sin default: el dueño debe configurarlo la primera vez
const ADMIN_PIN_KEY     = "taller_admin_pin_hash";
const ADMIN_SESSION_KEY = "taller_admin";

function getStoredHash() {
  return localStorage.getItem(PIN_KEY) || DEFAULT_PIN_HASH;
}
function getAdminHash() {
  return localStorage.getItem(ADMIN_PIN_KEY) || null;
}

// ── LoginScreen ────────────────────────────────────────────────────────────
function LoginScreen({ onLogin }) {
  const [pin,   setPin]   = React.useState("");
  const [error, setError] = React.useState("");
  const [shake, setShake] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => { ref.current?.focus(); }, []);

  async function submit() {
    const h = await sha256(pin);
    if (h === getStoredHash()) {
      onLogin(true);  // dueño
    } else {
      const adminHash = getAdminHash();
      if (adminHash && h === adminHash) {
        onLogin(false); // admin
      } else {
        setError(getAdminHash() ? "PIN incorrecto" : "PIN incorrecto — el dueño debe configurar el PIN del administrativo");
        setShake(true);
        setPin("");
        setTimeout(() => { setShake(false); ref.current?.focus(); }, 500);
      }
    }
  }

  return (
    <div className="pin-overlay" style={{ background: "var(--bg)" }}>
      <div className={`pin-modal${shake ? " pin-modal--shake" : ""}`}>
        <div className="pin-modal__icon"><Icon.lock width="28" height="28" /></div>
        <h3 className="pin-modal__title">Sistema de Gestión</h3>
        <p className="pin-modal__sub">Ingresá tu PIN para acceder</p>
        <input
          ref={ref}
          type="password"
          className={`pin-modal__input${error ? " pin-modal__input--error" : ""}`}
          value={pin}
          onChange={e => { setPin(e.target.value); setError(""); }}
          onKeyDown={e => { if (e.key === "Enter" && pin.length >= 4) submit(); }}
          placeholder="PIN"
          maxLength={8}
          autoComplete="off"
        />
        {error && <p className="pin-modal__error">{error}</p>}
        <div className="pin-modal__actions">
          <button className="pin-modal__submit" onClick={submit}
            disabled={pin.length < 4} style={{ flex: 1 }}>
            Ingresar
          </button>
        </div>
      </div>
    </div>
  );
}

// ── PinModal ───────────────────────────────────────────────────────────────
function PinModal({ mode, onSuccess, onCancel }) {
  const isChange = mode === "change" || mode === "change-admin";
  const isChangeAdmin = mode === "change-admin";
  const [pin,     setPin]     = React.useState("");
  const [confirm, setConfirm] = React.useState("");
  const [error,   setError]   = React.useState("");
  const [shake,   setShake]   = React.useState(false);
  const ref1 = React.useRef(null);

  React.useEffect(() => { ref1.current?.focus(); }, []);

  function triggerError(msg) {
    setError(msg);
    setShake(true);
    setPin("");
    setConfirm("");
    setTimeout(() => { setShake(false); ref1.current?.focus(); }, 500);
  }

  async function submit() {
    if (isChange) {
      if (pin.length < 4)   return triggerError("El PIN debe tener al menos 4 caracteres");
      if (pin !== confirm)  return triggerError("Los PINs no coinciden");
      localStorage.setItem(isChangeAdmin ? ADMIN_PIN_KEY : PIN_KEY, await sha256(pin));
      onSuccess();
    } else {
      const h = await sha256(pin);
      if (h === getStoredHash()) onSuccess();
      else                       triggerError("PIN incorrecto");
    }
  }

  function onKey(e) {
    if (e.key === "Escape") { onCancel(); return; }
    if (e.key !== "Enter")  return;
    const ready = isChange ? (pin.length >= 4 && confirm.length >= 4) : pin.length >= 4;
    if (ready) submit();
  }

  return ReactDOM.createPortal(
    <div className="pin-overlay" onClick={(e) => { if (e.target === e.currentTarget) onCancel(); }}>
      <div className={`pin-modal${shake ? " pin-modal--shake" : ""}`}>
        <div className="pin-modal__icon">
          <Icon.lock width="24" height="24" />
        </div>
        <h3 className="pin-modal__title">
          {isChangeAdmin ? "PIN del administrativo" : isChange ? "Cambiar PIN" : "Área restringida"}
        </h3>
        <p className="pin-modal__sub">
          {isChangeAdmin ? "Establecé el PIN de acceso del administrativo" : isChange ? "Establecé tu nuevo PIN de acceso" : "Ingresá tu PIN para continuar"}
        </p>

        <input
          ref={ref1}
          type="password"
          className={`pin-modal__input${error ? " pin-modal__input--error" : ""}`}
          value={pin}
          onChange={e => { setPin(e.target.value); setError(""); }}
          onKeyDown={onKey}
          placeholder={isChange ? "Nuevo PIN" : "PIN"}
          maxLength={8}
          autoComplete="off"
        />

        {isChange && (
          <input
            type="password"
            className={`pin-modal__input${error ? " pin-modal__input--error" : ""}`}
            style={{ marginTop: 10 }}
            value={confirm}
            onChange={e => { setConfirm(e.target.value); setError(""); }}
            onKeyDown={onKey}
            placeholder="Confirmar nuevo PIN"
            maxLength={8}
            autoComplete="off"
          />
        )}

        {error && <p className="pin-modal__error">{error}</p>}

        <div className="pin-modal__actions">
          <button className="pin-modal__cancel" onClick={onCancel}>Cancelar</button>
          <button
            className="pin-modal__submit"
            onClick={submit}
            disabled={isChange ? (pin.length < 4 || confirm.length < 4) : pin.length < 4}
          >
            {isChange ? "Guardar PIN" : "Ingresar"}
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}

// ── ConfirmLogoutModal ─────────────────────────────────────────────────────
function ConfirmLogoutModal({ onConfirm, onCancel }) {
  return ReactDOM.createPortal(
    <div className="pin-overlay" onClick={(e) => { if (e.target === e.currentTarget) onCancel(); }}>
      <div className="pin-modal pin-modal--danger">
        <div className="confirm-lock-wrap">
          <Icon.lock width="24" height="24" />
        </div>
        <h3 className="pin-modal__title">Cerrar sesión</h3>
        <p className="pin-modal__sub">¿Salir del modo dueño?<br/>Las secciones privadas quedarán ocultas.</p>
        <div className="pin-modal__actions">
          <button className="pin-modal__cancel" onClick={onCancel}>Cancelar</button>
          <button className="confirm-danger-btn" onClick={onConfirm}>Cerrar sesión</button>
        </div>
      </div>
    </div>,
    document.body
  );
}

// ── Sidebar ────────────────────────────────────────────────────────────────
function Sidebar({ current, setCurrent, ordenesActivas, isOwner, setIsOwner, setIsAuthenticated, anios, anio, setAnio, mesNum, setMesNum, open, onClose }) {
  const [modal, setModal] = React.useState(null); // null | "unlock" | "change" | "change-admin"
  const [showConfirm, setShowConfirm] = React.useState(false);

  const items = [
    { id: "dashboard", icon: Icon.dashboard, label: "Panel" },
    { id: "ordenes",   icon: Icon.orders,    label: "Órdenes", badge: ordenesActivas },
    { id: "turnos",    icon: Icon.calendar,  label: "Turnos" },
    { id: "clientes",  icon: Icon.clients,   label: "Clientes" },
    { id: "historial", icon: Icon.history,   label: "Historial" },
    { id: "cuentas",    icon: Icon.accounts,  label: "Cuentas corrientes" },
    { id: "costosvar",  icon: Icon.cash,      label: "Costos variables" },
  ];
  const items2 = [
    { id: "objetivos", icon: Icon.goals,   label: "Objetivos" },
  ];
  const items4 = [
    { id: "tecnicos", icon: Icon.wrench, label: "Técnicos" },
  ];
  const itemsCostos = [
    { id: "costos", icon: Icon.receipt, label: "Costos fijos" },
  ];
  const items5 = [
    { id: "contabilidad", icon: Icon.trend, label: "Contabilidad" },
  ];

  const RESTRICTED = ["contabilidad", "objetivos", "tecnicos", "costos"];

  function nav(list) {
    return list.map(it => {
      const I = it.icon;
      return (
        <div key={it.id} className={`nav-item ${current === it.id ? "active" : ""}`} onClick={() => { setCurrent(it.id); onClose?.(); }}>
          <I className="nav-item__icon" />
          <span>{it.label}</span>
          {it.badge != null && <span className="nav-item__badge">{it.badge}</span>}
        </div>
      );
    });
  }

  function handleUnlock() {
    sessionStorage.setItem(SESSION_KEY, "1");
    setIsOwner(true);
    setModal(null);
  }

  function handleLock() {
    sessionStorage.removeItem(SESSION_KEY);
    setIsOwner(false);
    setShowConfirm(false);
    if (RESTRICTED.includes(current)) setCurrent("dashboard");
  }

  function handleAdminLogout() {
    sessionStorage.removeItem(SESSION_KEY);
    sessionStorage.removeItem(ADMIN_SESSION_KEY);
    setIsOwner(false);
    setIsAuthenticated(false);
  }

  return (
    <>
    {open && <div className="sidebar-backdrop sidebar-backdrop--visible" onClick={onClose} />}
    <aside className={`sidebar${open ? " sidebar--open" : ""}`}>
      <div className="sidebar__brand">
        <div className="sidebar__brand-mark" onClick={() => location.reload()} style={{cursor:"pointer"}} title="Recargar">
          <img src="logo-nuevo.png" alt="Automecánica San Jorge" />
        </div>
      </div>

      <nav className="sidebar__nav">
        <div className="sidebar__section">Operación</div>
        {nav(items)}

        {isOwner && (
          <>
            <div className="sidebar__section">Control</div>
            <div className="sidebar__mes">
              <CustomSelect value={String(anio)} onChange={e => setAnio(Number(e.target.value))} style={{ width: 76 }}>
                {anios.map(a => <option key={a} value={String(a)}>{a}</option>)}
              </CustomSelect>
              <CustomSelect value={String(mesNum)} onChange={e => setMesNum(Number(e.target.value))} style={{ flex: 1 }}>
                {MESES_TEC.map((m, i) => <option key={i} value={String(i + 1)}>{m}</option>)}
              </CustomSelect>
            </div>
            {nav(items5)}
            {nav(items2)}
            {nav(items4)}
            {nav(itemsCostos)}
          </>
        )}
      </nav>

      {!isOwner && (
        <button className="sidebar__unlock" onClick={() => setModal("unlock")}>
          <div className="sidebar__unlock-icon">
            <Icon.lock width="13" height="13" />
          </div>
          <span className="sidebar__unlock-label">Área privada</span>
          <Icon.chevronRight width="12" height="12" className="sidebar__unlock-chevron" />
        </button>
      )}

      <div className={`sidebar__footer${isOwner ? " sidebar__footer--owner" : ""}`}>
        {isOwner ? (
          <>
            <div className="owner-mode-badge">
              <Icon.lockOpen width="11" height="11" />
              <span>Dueño</span>
            </div>
            <button className="owner-pin-btn" onClick={() => setModal("change")}>
              Mi PIN
            </button>
            <button className="owner-pin-btn" onClick={() => setModal("change-admin")} title="Establecer PIN del administrativo">
              PIN admin
            </button>
            <button className="owner-exit" onClick={() => setShowConfirm(true)} title="Cerrar sesión dueño">
              <Icon.logOut />
            </button>
          </>
        ) : (
          <>
            <div style={{width:8, height:8, borderRadius:"50%", background:"var(--ok)", flexShrink:0, boxShadow:"0 0 6px rgba(111,204,139,0.6)"}} />
            <div className="user-info">
              <b style={{fontWeight:600}}>Sistema activo</b><br/>
              <span>{new Date().toLocaleDateString("es-AR", {day:"numeric", month:"short", year:"numeric"})}</span>
            </div>
            <button className="owner-exit" onClick={handleAdminLogout} title="Cerrar sesión">
              <Icon.logOut />
            </button>
          </>
        )}
      </div>

      {modal && (
        <PinModal
          mode={modal}
          onSuccess={modal === "unlock" ? handleUnlock : () => setModal(null)}
          onCancel={() => setModal(null)}
        />
      )}

      {showConfirm && (
        <ConfirmLogoutModal
          onConfirm={handleLock}
          onCancel={() => setShowConfirm(false)}
        />
      )}
    </aside>
    </>
  );
}

// ── Topbar ─────────────────────────────────────────────────────────────────
function Topbar({ title, crumb, action, search, setSearch, onMenuOpen }) {
  const today = new Date();
  const dateStr = today.toLocaleDateString("es-AR", { weekday: "long", day: "numeric", month: "long", year: "numeric" });
  return (
    <div className="topbar">
      <button className="topbar__menu-btn" onClick={onMenuOpen} aria-label="Abrir menú">
        <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
          <line x1="2" y1="4.5" x2="16" y2="4.5"/><line x1="2" y1="9" x2="16" y2="9"/><line x1="2" y1="13.5" x2="16" y2="13.5"/>
        </svg>
      </button>
      <div className="topbar__info">
        <div className="topbar__crumb">{crumb}</div>
        <div className="topbar__title">{title}</div>
      </div>
      <div className="topbar__spacer" />
      {setSearch && (
        <input className="topbar__search" placeholder="Buscar cliente, patente, N° orden..." value={search} onChange={e => setSearch(e.target.value)} />
      )}
      <div className="topbar__date">{dateStr}</div>
      {action}
    </div>
  );
}

Object.assign(window, { LoginScreen, Sidebar, Topbar });
