/* ============================================================
   VKTR TCO — "My Library" panel (V1.7)
   ------------------------------------------------------------
   Design (Notion: Roadmap — Vehicle Library, Routes & 3-Tier Access):
   - One panel, three tabs (Profiles / Vehicles / Routes), one shared row
     pattern (name, last-edited, save-as, export, rename, delete) instead of
     three different CRUD UIs bolted onto three different screens.
   - Selection/use of a saved item stays at its normal point of use (the
     vehicle search dropdown already merges in custom vehicles via
     window.findVeh() -- see vehicle_library.jsx). This panel is for
     management only: browse, rename, export, delete, save-as.
   - Profiles get DUAL persistence: this panel adds Firestore save/load
     (users/{uid}/profiles/{id}) alongside the existing local file
     export/import in the header, which is untouched.
   - Signed-in gated (tier 2), not apiAccess-gated -- plain Firestore CRUD.
   - Routes tab is a placeholder until the routing feature itself is built
     (next phase) -- shipping an empty stub here would be more confusing
     than an honest "not built yet" state.
   ============================================================ */

function newProfileId() {
  return `p_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
}

function downloadJson(filename, payload) {
  const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

function slugify(str) {
  return (str || "untitled").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "") || "untitled";
}

function useSavedProfiles(user) {
  const [profiles, setProfiles] = React.useState({});
  React.useEffect(() => {
    if (!user || typeof firebase === "undefined" || !firebase.apps.length) { setProfiles({}); return; }
    const unsub = firebase.firestore().collection("users").doc(user.uid).collection("profiles")
      .onSnapshot((snap) => {
        const next = {};
        snap.forEach((doc) => { next[doc.id] = doc.data(); });
        setProfiles(next);
      });
    return unsub;
  }, [user]);
  return profiles;
}

function LibraryRow({ icon, name, subtitle, onSaveAs, onExport, onRename, onDelete }) {
  return (
    <div className="library-row">
      <span style={{ fontSize: 16, flex: "none" }} aria-hidden="true">{icon}</span>
      <div className="library-row-info">
        <div className="library-row-name">{name}</div>
        {subtitle && <div className="library-row-sub">{subtitle}</div>}
      </div>
      {onSaveAs && <button type="button" className="btn btn-ghost library-row-btn" title="Save as" onClick={onSaveAs}>📋</button>}
      {onExport && <button type="button" className="btn btn-ghost library-row-btn" title="Export" onClick={onExport}>⬇</button>}
      {onRename && <button type="button" className="btn btn-ghost library-row-btn" title="Rename" onClick={onRename}>✎</button>}
      {onDelete && <button type="button" className="btn btn-ghost library-row-btn library-row-danger" title="Delete" onClick={onDelete}>🗑</button>}
    </div>
  );
}

function LibraryProfilesTab({ s, user, onLoadProfile, onClose }) {
  const { lang } = useLang();
  const profiles = useSavedProfiles(user);
  const ids = Object.keys(profiles).sort((a, b) => (profiles[b].savedAt || 0) - (profiles[a].savedAt || 0));

  if (!user) {
    return (
      <div className="library-guest-note">
        <Tr en="Sign in to save profiles to your account. You can still export/import them as files from the header, no sign-in needed."
            id="Masuk untuk menyimpan profil ke akun Anda. Anda tetap bisa ekspor/impor sebagai file dari header, tanpa perlu masuk." />
      </div>
    );
  }

  // v1.9.9 (2026-07-21) audit fixes, both real: (1) saveCurrent/saveAs saved
  // `s`/`data.state` RAW, without the same PRESET_SAVE_EXCLUDE_KEYS filtering
  // screens.jsx's SaveAsPresetCard already applies (depotBom/depotMetrics --
  // Screen 4's Depot Design sync data -- can be large enough that a profile
  // with it saved could push a Firestore document over the 1MB limit).
  // (2) None of these four writes had ANY error handling -- a failed write
  // (oversized doc, network blip) was completely silent, no different from
  // success from the user's side. Both fixed: filter before saving, and
  // every write now surfaces a failure via alert() (matching the existing
  // pattern already used elsewhere in this app, e.g. admin_panel.jsx's
  // saveUser), instead of failing invisibly.
  const cleanStateForSave = (state) => {
    const clean = { ...state };
    (window.PRESET_SAVE_EXCLUDE_KEYS || []).forEach((k) => delete clean[k]);
    return clean;
  };
  const saveFailedAlert = (e) => alert(tr(lang, "Couldn't save — check your connection and try again.", "Gagal menyimpan — periksa koneksi Anda dan coba lagi.") + (e && e.message ? `\n(${e.message})` : ""));

  const saveCurrent = async () => {
    const name = window.prompt(tr(lang, "Name this profile", "Nama profil ini"), s.company || "Untitled");
    if (!name) return;
    try {
      await firebase.firestore().collection("users").doc(user.uid).collection("profiles").doc(newProfileId())
        .set({ name, state: cleanStateForSave(s), savedAt: Date.now() });
    } catch (e) { saveFailedAlert(e); }
  };

  const saveAs = async (data) => {
    const name = window.prompt(tr(lang, "Save as — new name", "Simpan sebagai — nama baru"), data.name + " (copy)");
    if (!name) return;
    try {
      await firebase.firestore().collection("users").doc(user.uid).collection("profiles").doc(newProfileId())
        .set({ name, state: cleanStateForSave(data.state), savedAt: Date.now() });
    } catch (e) { saveFailedAlert(e); }
  };

  const rename = async (id, data) => {
    const name = window.prompt(tr(lang, "Rename profile", "Ganti nama profil"), data.name);
    if (!name) return;
    try {
      await firebase.firestore().collection("users").doc(user.uid).collection("profiles").doc(id).update({ name });
    } catch (e) { saveFailedAlert(e); }
  };

  const remove = async (id) => {
    if (!window.confirm(tr(lang, "Delete this profile? This can't be undone.", "Hapus profil ini? Tidak dapat dibatalkan."))) return;
    try {
      await firebase.firestore().collection("users").doc(user.uid).collection("profiles").doc(id).delete();
    } catch (e) { saveFailedAlert(e); }
  };

  const exportDoc = (data) => downloadJson(`${slugify(data.name)}_tco-profile.json`, {
    app: "VKTR TCO Competitive Analysis Platform", schemaVersion: window.SCHEMA_VERSION,
    exportedAt: new Date().toISOString(), state: data.state,
  });

  const load = (data) => { onLoadProfile(data.state); onClose(); };

  return (
    <>
      <div className="library-toolbar">
        <button type="button" className="btn btn-primary" style={{ fontSize: 13 }} onClick={saveCurrent}>
          + <Tr en="Save current profile" id="Simpan profil saat ini" />
        </button>
      </div>
      {ids.length === 0 && (
        <div className="library-empty"><Tr en="No saved profiles yet." id="Belum ada profil tersimpan." /></div>
      )}
      {ids.map((id) => {
        const data = profiles[id];
        return (
          <div key={id} onClick={() => load(data)} style={{ cursor: "pointer" }}>
            <LibraryRow icon="📄"
              name={data.name}
              subtitle={data.savedAt ? new Date(data.savedAt).toLocaleDateString(lang === "en" ? "en-US" : "id-ID") : ""}
              onSaveAs={(e) => { e.stopPropagation(); saveAs(data); }}
              onExport={(e) => { e.stopPropagation(); exportDoc(data); }}
              onRename={(e) => { e.stopPropagation(); rename(id, data); }}
              onDelete={(e) => { e.stopPropagation(); remove(id); }}
            />
          </div>
        );
      })}
    </>
  );
}

function LibraryVehiclesTab({ user }) {
  const { lang } = useLang();
  const { customVehicles, deleteCustomVehicle } = useCustomVehicles();
  const ids = Object.keys(customVehicles);

  if (ids.length === 0) {
    return <div className="library-empty"><Tr en="No customized or added vehicles yet — edit any spec on the Vehicle Specifications tab (Screen 2) to see it here." id="Belum ada kendaraan yang disesuaikan atau ditambahkan — ubah spesifikasi apa pun di tab Spesifikasi Kendaraan (Layar 2) untuk melihatnya di sini." /></div>;
  }

  const exportDoc = (id, data) => downloadJson(`${slugify(data.name || id)}_vehicle.json`, { ...data, exportedAt: new Date().toISOString() });

  const rename = async (id, data) => {
    if (!data.isNew) return; // overrides are tied to a catalog vehicle, no independent name to rename
    const name = window.prompt(tr(lang, "Rename vehicle", "Ganti nama kendaraan"), data.name);
    if (!name) return;
    if (user && typeof firebase !== "undefined" && firebase.apps.length) {
      try {
        await firebase.firestore().collection("users").doc(user.uid).collection("customVehicles").doc(id).update({ name });
      } catch (e) {
        alert(tr(lang, "Couldn't save — check your connection and try again.", "Gagal menyimpan — periksa koneksi Anda dan coba lagi.") + (e && e.message ? `\n(${e.message})` : ""));
      }
    }
  };

  return (
    <>
      {ids.map((id) => {
        const data = customVehicles[id];
        const label = data.isNew ? data.name : `${tr(lang, "Override", "Perubahan")}: ${(window.VEHICLES.find(v => v.id === id) || {}).name || id}`;
        return (
          <LibraryRow key={id} icon="🚛"
            name={label}
            subtitle={data.isNew ? tr(lang, "Custom vehicle", "Kendaraan kustom") : tr(lang, "Modified from catalog default", "Diubah dari default katalog")}
            onExport={() => exportDoc(id, data)}
            onRename={data.isNew ? () => rename(id, data) : null}
            onDelete={() => deleteCustomVehicle(id)}
          />
        );
      })}
    </>
  );
}

function LibraryRoutesTab({ user }) {
  const { lang } = useLang();
  const routes = useSavedRoutes(user);
  const ids = Object.keys(routes).sort((a, b) => (routes[b].savedAt || 0) - (routes[a].savedAt || 0));

  if (!user) {
    return (
      <div className="library-guest-note">
        <Tr en="Sign in to save routes imported from KML/KMZ (Screen 3 → Track Profile → Import route). Guests can still import and preview a route, just not save it."
            id="Masuk untuk menyimpan rute yang diimpor dari KML/KMZ (Layar 3 → Profil Rute → Impor rute). Tamu tetap bisa mengimpor dan melihat pratinjau rute, hanya tidak bisa menyimpannya." />
      </div>
    );
  }

  const rename = async (id, data) => {
    const name = window.prompt(tr(lang, "Rename route", "Ganti nama rute"), data.name);
    if (!name) return;
    try {
      await renameRouteDoc(user, id, name);
    } catch (e) {
      alert(tr(lang, "Couldn't save — check your connection and try again.", "Gagal menyimpan — periksa koneksi Anda dan coba lagi.") + (e && e.message ? `\n(${e.message})` : ""));
    }
  };

  const remove = async (id) => {
    if (!window.confirm(tr(lang, "Delete this route? This can't be undone.", "Hapus rute ini? Tidak dapat dibatalkan."))) return;
    try {
      await deleteRouteDoc(user, id);
    } catch (e) {
      alert(tr(lang, "Couldn't save — check your connection and try again.", "Gagal menyimpan — periksa koneksi Anda dan coba lagi.") + (e && e.message ? `\n(${e.message})` : ""));
    }
  };

  const exportDoc = (data) => downloadJson(`${slugify(data.name)}_route.json`, { ...data, exportedAt: new Date().toISOString() });

  if (ids.length === 0) {
    return <div className="library-empty"><Tr en="No saved routes yet — import a KML/KMZ on Screen 3 → Track Profile, then Save to my library." id="Belum ada rute tersimpan — impor KML/KMZ di Layar 3 → Profil Rute, lalu Simpan ke perpustakaan saya." /></div>;
  }

  return (
    <>
      {ids.map((id) => {
        const data = routes[id];
        return (
          <LibraryRow key={id} icon="🗺"
            name={data.name}
            subtitle={`${fmt.num(data.distanceKm)} km · ${data.savedAt ? new Date(data.savedAt).toLocaleDateString(lang === "en" ? "en-US" : "id-ID") : ""}`}
            onExport={() => exportDoc(data)}
            onRename={() => rename(id, data)}
            onDelete={() => remove(id)}
          />
        );
      })}
    </>
  );
}

function MyLibraryPanel({ s, onLoadProfile, onClose }) {
  const { lang } = useLang();
  const { user } = useAuth();
  const [tab, setTab] = React.useState("profiles");

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-panel" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 560 }}>
        <div className="modal-head">
          <h2>📚 <Tr en="My library" id="Perpustakaan Saya" /></h2>
          <button type="button" className="modal-close" onClick={onClose}>✕</button>
        </div>

        <div className="library-tabs">
          {[
            { key: "profiles", en: "Profiles", id_: "Profil" },
            { key: "vehicles", en: "Vehicles", id_: "Kendaraan" },
            { key: "routes", en: "Routes", id_: "Rute" },
          ].map((t) => (
            <div key={t.key} className={"library-tab" + (tab === t.key ? " active" : "")} onClick={() => setTab(t.key)}>
              {tr(lang, t.en, t.id_)}
            </div>
          ))}
        </div>

        <div className="library-body">
          {tab === "profiles" && <LibraryProfilesTab s={s} user={user} onLoadProfile={onLoadProfile} onClose={onClose} />}
          {tab === "vehicles" && <LibraryVehiclesTab user={user} />}
          {tab === "routes" && <LibraryRoutesTab user={user} />}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MyLibraryPanel });
