// Backup / restore: export & import full database as JSON
// Designed for "manual sync via Google Drive": user downloads JSON, uploads
// to their Drive, then on another device opens the file and imports it.

const BACKUP_VERSION = 1;

function buildBackup({ state, auth, tweaks }) {
  return {
    schema: "mab-quotes-backup",
    version: BACKUP_VERSION,
    exportedAt: new Date().toISOString(),
    appVersion: "1.2",
    payload: {
      state: { ...state, tweaksOpen: false },
      auth: auth || null,
      tweaks: tweaks || {},
    },
  };
}

function downloadBackup({ state, auth, tweaks }) {
  const backup = buildBackup({ state, auth, tweaks });
  const blob = new Blob([JSON.stringify(backup, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  const ts = new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-");
  a.href = url;
  a.download = `MAB-respaldo-${ts}.json`;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 0);
  // Mark last backup
  localStorage.setItem("mab_last_backup", new Date().toISOString());
}

function readBackupFile(file) {
  return new Promise((resolve, reject) => {
    const r = new FileReader();
    r.onload = () => {
      try {
        const data = JSON.parse(r.result);
        if (data.schema !== "mab-quotes-backup") {
          throw new Error("Archivo no es un respaldo MAB válido.");
        }
        resolve(data);
      } catch (e) { reject(e); }
    };
    r.onerror = () => reject(new Error("No se pudo leer el archivo."));
    r.readAsText(file);
  });
}

function BackupView({ state, setState, auth, setAuth, tweaks, session }) {
  const [msg, setMsg] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const fileRef = React.useRef(null);
  const lastBackup = localStorage.getItem("mab_last_backup");

  const stats = {
    quotes: (state.quotes || []).length,
    materials: (state.materials || []).length,
    roles: (state.roles || []).length,
    users: (auth?.users || []).length,
    items: (state.quote?.items || []).length,
  };

  const lastBackupHuman = lastBackup
    ? new Date(lastBackup).toLocaleString("es-CL")
    : "nunca";

  async function handleImport(file) {
    if (!file) return;
    setBusy(true); setMsg(null);
    try {
      const data = await readBackupFile(file);
      const p = data.payload || {};
      if (!confirm(
        `Vas a reemplazar la información de este dispositivo con el respaldo:\n\n` +
        `· Exportado: ${new Date(data.exportedAt).toLocaleString("es-CL")}\n` +
        `· Cotizaciones: ${(p.state?.quotes || []).length}\n` +
        `· Materiales: ${(p.state?.materials || []).length}\n` +
        `· Perfiles HH: ${(p.state?.roles || []).length}\n` +
        `· Usuarios: ${(p.auth?.users || []).length}\n\n` +
        `¿Continuar?`
      )) { setBusy(false); return; }

      if (p.state) setState(p.state);
      if (p.auth) setAuth(p.auth);
      // Tweaks: keep current visual prefs unless missing
      if (p.tweaks && Object.keys(p.tweaks).length) {
        applyTweaks(p.tweaks);
      }
      setMsg({ type: "ok", text: "Respaldo importado correctamente. Recarga la página si algo no se ve actualizado." });
    } catch (e) {
      setMsg({ type: "err", text: "Error: " + e.message });
    }
    setBusy(false);
    if (fileRef.current) fileRef.current.value = "";
  }

  return (
    <>
      <Topbar
        title="Respaldo y sincronización"
        crumb="Datos"
        actions={
          <button className="btn primary" onClick={() => downloadBackup({ state, auth, tweaks })}>
            <Icon.download /> Descargar respaldo
          </button>
        }
      />
      <div className="content narrow">
        <div className="card" style={{marginBottom: 16}}>
          <div className="card-head">
            <h2>Estado actual de este dispositivo</h2>
            <span className="hint">Último respaldo descargado: <b>{lastBackupHuman}</b></span>
          </div>
          <div className="card-body">
            <div className="grid-4" style={{gap: 12}}>
              {[
                ["Cotizaciones", stats.quotes],
                ["Materiales", stats.materials],
                ["Perfiles HH", stats.roles],
                ["Usuarios", stats.users],
              ].map(([k, v]) => (
                <div key={k} style={{padding:"14px 16px",background:"var(--surface-2)",borderRadius:8}}>
                  <div className="muted" style={{fontSize:11,textTransform:"uppercase",letterSpacing:".08em",fontWeight:600}}>{k}</div>
                  <div style={{fontSize:24,fontWeight:700,marginTop:4}} className="num">{v}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card" style={{marginBottom:16}}>
          <div className="card-head">
            <h2>📥 Descargar respaldo (subir a Google Drive)</h2>
          </div>
          <div className="card-body">
            <p style={{margin:"0 0 14px",fontSize:13,lineHeight:1.6,color:"var(--ink-2)"}}>
              Genera un archivo <b>.json</b> con <b>todo</b> tu trabajo: cotizaciones, materiales, HH, gastos, usuarios y configuración.
              Súbelo a tu Google Drive desde tu PC o teléfono.
            </p>
            <div className="row" style={{gap:10}}>
              <button className="btn primary" onClick={() => downloadBackup({ state, auth, tweaks })}>
                <Icon.download /> Generar respaldo .json
              </button>
            </div>
            <details style={{marginTop:14,fontSize:12.5,lineHeight:1.6,color:"var(--ink-2)"}}>
              <summary style={{cursor:"pointer",fontWeight:600}}>Cómo guardarlo en Google Drive</summary>
              <ol style={{paddingLeft:18,marginTop:8}}>
                <li><b>iPhone:</b> al descargarse, presiona "Compartir" → "Guardar en Drive".</li>
                <li><b>Android:</b> al descargarse, ábrelo en Drive desde el menú de descarga.</li>
                <li><b>PC:</b> arrastra el archivo descargado a tu carpeta de Google Drive (drive.google.com).</li>
                <li><b>Tip:</b> crea una carpeta "MAB Cotizaciones" en Drive para mantener todos los respaldos juntos.</li>
              </ol>
            </details>
          </div>
        </div>

        <div className="card" style={{marginBottom:16}}>
          <div className="card-head">
            <h2>📤 Importar respaldo (desde Google Drive)</h2>
          </div>
          <div className="card-body">
            <p style={{margin:"0 0 14px",fontSize:13,lineHeight:1.6,color:"var(--ink-2)"}}>
              Sube el archivo <b>.json</b> de respaldo. El selector de archivos te permite elegir directamente desde Google Drive en iPhone y Android.
              <b style={{color:"var(--danger)"}}> Esto reemplazará la información actual de este dispositivo.</b>
            </p>
            <input ref={fileRef} type="file" accept="application/json,.json"
                   style={{display:"none"}}
                   onChange={e => handleImport(e.target.files?.[0])} />
            <div className="row" style={{gap:10}}>
              <button className="btn" onClick={() => fileRef.current?.click()} disabled={busy}>
                <Icon.upload /> {busy ? "Importando…" : "Elegir archivo .json"}
              </button>
            </div>
            {msg && (
              <div style={{
                marginTop:14, padding:"10px 14px", borderRadius:8, fontSize:13,
                background: msg.type === "ok" ? "#e8f4ea" : "#fdecea",
                border: `1px solid ${msg.type === "ok" ? "#9bc8a3" : "#f5c6c3"}`,
                color: msg.type === "ok" ? "var(--ok)" : "var(--danger)",
              }}>{msg.text}</div>
            )}
          </div>
        </div>

        <div style={{padding:"14px 16px",background:"var(--accent-soft)",border:"1px solid #f2d89a",borderRadius:8,fontSize:13,lineHeight:1.6}}>
          <b>💡 Flujo recomendado para usar entre PC y celular:</b>
          <ol style={{paddingLeft:18,margin:"6px 0 0"}}>
            <li>Trabaja en tu PC normalmente.</li>
            <li>Al terminar, <b>descarga el respaldo</b> y guárdalo en Google Drive.</li>
            <li>En tu celular: <b>importa el respaldo</b> desde Drive antes de empezar a trabajar.</li>
            <li>Al terminar en el celular, descarga uno nuevo a Drive y reimporta en tu PC.</li>
          </ol>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { downloadBackup, readBackupFile, BackupView, buildBackup });
