/* ResourceStore.jsx — localStorage CRUD layer for resource documents.
 * Exposed as window.ResourceStore. Must load before ResourceCenter or adminRecursosApp.
 */
const ResourceStore = (() => {
  const KEY = "hondulegal_resources";

  function _read() {
    try { return JSON.parse(localStorage.getItem(KEY)) || []; }
    catch { return []; }
  }
  function _write(docs) { localStorage.setItem(KEY, JSON.stringify(docs)); }
  function _uuid() {
    if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID();
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
      const r = Math.random() * 16 | 0;
      return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16);
    });
  }

  return {
    getAll(type) {
      return _read()
        .filter(d => d.type === type)
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    },

    getById(id) {
      return _read().find(d => d.id === id) || null;
    },

    add(doc) {
      const docs = _read();
      const newDoc = {
        id: _uuid(),
        name: doc.name || "",
        category: doc.category || "General",
        tags: doc.tags || [],
        type: doc.type || "legal",
        fileUrl: doc.fileUrl || "",
        downloads: 0,
        views: 0,
        createdAt: new Date().toISOString(),
      };
      docs.push(newDoc);
      _write(docs);
      return newDoc;
    },

    update(id, updates) {
      const docs = _read();
      const idx = docs.findIndex(d => d.id === id);
      if (idx === -1) return null;
      Object.assign(docs[idx], updates);
      _write(docs);
      return docs[idx];
    },

    remove(id) {
      const docs = _read();
      const filtered = docs.filter(d => d.id !== id);
      _write(filtered);
    },

    search(type, query) {
      const q = query.toLowerCase().trim();
      if (!q) return this.getAll(type);
      return this.getAll(type).filter(d => d.name.toLowerCase().includes(q));
    },

    getCategories(type) {
      const cats = new Set(this.getAll(type).map(d => d.category));
      return [...cats].sort();
    },

    getAllTags(type) {
      const tags = new Set();
      this.getAll(type).forEach(d => (d.tags || []).forEach(t => tags.add(t)));
      return [...tags].sort();
    },

    getMostDownloaded(type, limit = 5) {
      return this.getAll(type)
        .sort((a, b) => b.downloads - a.downloads)
        .slice(0, limit)
        .filter(d => d.downloads > 0);
    },

    getMostViewed(type, limit = 5) {
      return this.getAll(type)
        .sort((a, b) => b.views - a.views)
        .slice(0, limit)
        .filter(d => d.views > 0);
    },

    incrementDownloads(id) {
      const docs = _read();
      const doc = docs.find(d => d.id === id);
      if (doc) { doc.downloads++; _write(docs); }
    },

    incrementViews(id) {
      const docs = _read();
      const doc = docs.find(d => d.id === id);
      if (doc) { doc.views++; _write(docs); }
    },

    getAllDocs() {
      return _read().sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    },

    seedIfEmpty() {
      if (_read().length > 0) return;

      const legalDocs = [
        { name: "Guia de Apostilla de Documentos", category: "Documentos Civiles", tags: ["apostilla", "tramites", "documentos"], type: "legal", downloads: 47, views: 182 },
        { name: "Requisitos para Constitucion de Empresa", category: "Documentos Civiles", tags: ["empresa", "constitucion", "mercantil"], type: "legal", downloads: 38, views: 156 },
        { name: "Proceso de Divorcio en Honduras — Guia Completa", category: "Familia", tags: ["divorcio", "familia", "proceso"], type: "legal", downloads: 65, views: 234 },
        { name: "Formulario de Solicitud de Visa de Residencia", category: "Migratorio", tags: ["visa", "residencia", "migracion"], type: "legal", downloads: 52, views: 198 },
        { name: "Modelo de Contrato de Compraventa de Inmueble", category: "Inmobiliario", tags: ["contrato", "inmueble", "compraventa"], type: "legal", downloads: 41, views: 145 },
        { name: "Checklist de Documentos para Tramites Judiciales", category: "Tramites Judiciales", tags: ["checklist", "judicial", "documentos"], type: "legal", downloads: 29, views: 112 },
        { name: "Guia de Reagrupacion Familiar", category: "Migratorio", tags: ["familia", "reagrupacion", "migracion"], type: "legal", downloads: 33, views: 127 },
        { name: "Manual de Gestiones Notariales Basicas", category: "General", tags: ["notarial", "gestiones", "manual"], type: "legal", downloads: 22, views: 89 },
        { name: "Escritura Publica de Sociedad Mercantil", category: "Documentos Civiles", tags: ["escritura", "sociedad", "mercantil"], type: "legal", downloads: 35, views: 140 },
        { name: "Procedimiento de Adopcion Nacional", category: "Familia", tags: ["adopcion", "familia", "menores"], type: "legal", downloads: 18, views: 95 },
        { name: "Guia de Tramites de Herencia y Sucesiones", category: "Familia", tags: ["herencia", "sucesion", "testamento"], type: "legal", downloads: 44, views: 175 },
        { name: "Modelo de Poder General de Administracion", category: "General", tags: ["poder", "administracion", "notarial"], type: "legal", downloads: 31, views: 120 },
        { name: "Proceso de Naturalizacion para Extranjeros", category: "Migratorio", tags: ["naturalizacion", "ciudadania", "extranjeros"], type: "legal", downloads: 27, views: 108 },
        { name: "Formato de Demanda Civil Ordinaria", category: "Tramites Judiciales", tags: ["demanda", "civil", "litigio"], type: "legal", downloads: 36, views: 148 },
        { name: "Guia de Registro de Propiedad Inmueble", category: "Inmobiliario", tags: ["registro", "propiedad", "catastro"], type: "legal", downloads: 25, views: 102 },
        { name: "Contrato de Arrendamiento Comercial", category: "Inmobiliario", tags: ["arrendamiento", "comercial", "contrato"], type: "legal", downloads: 20, views: 85 },
      ];

      const tecnicoDocs = [
        { name: "Marco Logico — Plantilla Estandar", category: "Planificacion", tags: ["marco logico", "planificacion", "plantilla"], type: "tecnico", downloads: 34, views: 145 },
        { name: "Guia de Indicadores KPI para Proyectos", category: "M&E", tags: ["KPI", "indicadores", "monitoreo"], type: "tecnico", downloads: 28, views: 118 },
        { name: "Formato de Informe de Evaluacion Externa", category: "M&E", tags: ["evaluacion", "informe", "formato"], type: "tecnico", downloads: 19, views: 87 },
        { name: "Propuesta Tipo para Donantes Internacionales", category: "Cooperacion", tags: ["propuesta", "donantes", "cooperacion"], type: "tecnico", downloads: 42, views: 167 },
        { name: "Diagnostico Institucional — Metodologia", category: "Planificacion", tags: ["diagnostico", "institucional", "metodologia"], type: "tecnico", downloads: 15, views: 72 },
        { name: "Guia de Politicas Publicas Basada en Evidencia", category: "Gobernanza", tags: ["politicas", "evidencia", "gobernanza"], type: "tecnico", downloads: 21, views: 94 },
        { name: "Plantilla de Teoria de Cambio", category: "Planificacion", tags: ["teoria de cambio", "impacto", "diseño"], type: "tecnico", downloads: 26, views: 110 },
        { name: "Manual de Outcome Harvesting", category: "M&E", tags: ["outcome harvesting", "evaluacion", "resultados"], type: "tecnico", downloads: 17, views: 78 },
        { name: "Formato de Informe Financiero para Donantes", category: "Cooperacion", tags: ["financiero", "donantes", "informe"], type: "tecnico", downloads: 30, views: 125 },
        { name: "Guia de Dialogo Multiactor", category: "Gobernanza", tags: ["dialogo", "multiactor", "participacion"], type: "tecnico", downloads: 12, views: 65 },
        { name: "Encuesta de Satisfaccion de Beneficiarios", category: "M&E", tags: ["encuesta", "beneficiarios", "satisfaccion"], type: "tecnico", downloads: 14, views: 70 },
        { name: "Modelo de Plan Estrategico Institucional", category: "Planificacion", tags: ["plan estrategico", "institucional", "gobernanza"], type: "tecnico", downloads: 23, views: 98 },
        { name: "Guia de Gestion de Grants Multilaterales", category: "Cooperacion", tags: ["grants", "multilateral", "gestion"], type: "tecnico", downloads: 18, views: 82 },
        { name: "Metodologia de Analisis de Riesgos", category: "Gobernanza", tags: ["riesgos", "analisis", "gestion"], type: "tecnico", downloads: 16, views: 75 },
      ];

      const now = new Date();
      [...legalDocs, ...tecnicoDocs].forEach((doc, i) => {
        const d = new Date(now);
        d.setDate(d.getDate() - i * 3);
        const newDoc = {
          id: _uuid(),
          name: doc.name,
          category: doc.category,
          tags: doc.tags,
          type: doc.type,
          fileUrl: "",
          downloads: doc.downloads,
          views: doc.views,
          createdAt: d.toISOString(),
        };
        const docs = _read();
        docs.push(newDoc);
        _write(docs);
      });
    },
  };
})();

Object.assign(window, { ResourceStore });
