/* Ressources — Documentation, procédures, templates */

const RESOURCE_CATEGORIES = [
  { id: "ops",      label: "Opérations",      icon: "settings" },
  { id: "supply",   label: "Sourcing",        icon: "users"    },
  { id: "fin",      label: "Finance",         icon: "dollar"   },
  { id: "amazon",   label: "Amazon FBA",      icon: "box"      },
  { id: "legal",    label: "Légal & Fiscal",  icon: "shield"   },
];

const RESOURCES = [
  { cat: "ops",    title: "Onboarding cofondateur",         kind: "doc",      size: "12 pages",  updated: "8 mai 2026"  },
  { cat: "ops",    title: "Procédure Daily Digest",          kind: "doc",      size: "4 pages",   updated: "5 mai 2026"  },
  { cat: "ops",    title: "Template tâche Linear",           kind: "template", size: "—",         updated: "2 mai 2026"  },
  { cat: "supply", title: "Liste fournisseurs validés Q2",   kind: "sheet",    size: "47 lignes", updated: "9 mai 2026"  },
  { cat: "supply", title: "Template RFQ (Request For Quote)",kind: "template", size: "1 page",    updated: "1 avr 2026"  },
  { cat: "supply", title: "Checklist contrôle qualité",      kind: "checklist",size: "22 points", updated: "3 mai 2026"  },
  { cat: "supply", title: "Audit factory checklist",         kind: "checklist",size: "35 points", updated: "15 mars 2026"},
  { cat: "fin",    title: "Plan comptable KCC Holdings",     kind: "doc",      size: "8 pages",   updated: "1 jan 2026"  },
  { cat: "fin",    title: "Procédure réconciliation CIBC",   kind: "doc",      size: "3 pages",   updated: "4 mai 2026"  },
  { cat: "fin",    title: "Template P&L mensuel",            kind: "template", size: "—",         updated: "1 mai 2026"  },
  { cat: "amazon", title: "Guide Sponsored Ads ACOS<25%",    kind: "doc",      size: "16 pages",  updated: "20 avr 2026" },
  { cat: "amazon", title: "Liste KPIs Seller Central",       kind: "sheet",    size: "32 KPIs",   updated: "6 mai 2026"  },
  { cat: "amazon", title: "Template listing optimisé",       kind: "template", size: "—",         updated: "12 avr 2026" },
  { cat: "legal",  title: "Statuts KCC Holdings Inc.",       kind: "doc",      size: "24 pages",  updated: "1 jan 2026"  },
  { cat: "legal",  title: "Convention entre cofondateurs",   kind: "doc",      size: "12 pages",  updated: "1 jan 2026"  },
  { cat: "legal",  title: "Calendrier fiscal TPS/TVQ",       kind: "sheet",    size: "12 dates",  updated: "1 jan 2026"  },
];

const KIND_META = {
  doc:       { icon: "book",     tone: "muted"  },
  sheet:     { icon: "chart",    tone: "blue"   },
  template:  { icon: "copy",     tone: "amber"  },
  checklist: { icon: "check",    tone: "green"  },
};

const Resources = () => {
  const [cat, setCat] = useState("all");
  const [search, setSearch] = useState("");
  const [kind, setKind] = useState("all");
  const [items, setItems] = useState(RESOURCES);
  const [showNew, setShowNew] = useState(false);
  const [draft, setDraft] = useState({ title: "", cat: "ops", kind: "doc", size: "" });
  const toast = useToast();

  const filtered = items
    .filter(r => cat === "all" || r.cat === cat)
    .filter(r => kind === "all" || r.kind === kind)
    .filter(r => !search || r.title.toLowerCase().includes(search.toLowerCase()));

  const openResource = (r) => {
    toast({ message: `Ouverture · ${r.title}`, tone: "muted" });
    // Future: navigate to a resource detail page or fetch the file
  };

  const submitNew = () => {
    if (!draft.title.trim()) return;
    const today = new Date().toLocaleDateString("fr-CA", { day: "numeric", month: "short", year: "numeric" });
    const next = [{ ...draft, updated: today }, ...items];
    setItems(next);
    setShowNew(false);
    setDraft({ title: "", cat: "ops", kind: "doc", size: "" });
    toast({ message: `Ressource ajoutée: ${draft.title}`, tone: "green" });
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Ressources</div>
          <div className="page-sub">
            {items.length} documents · {RESOURCE_CATEGORIES.length} catégories ·
            procédures · templates · checklists
          </div>
        </div>
        <button className="btn" data-variant="primary" onClick={() => setShowNew(true)}>
          <Icon name="plus" size={12} /> Nouvelle ressource
        </button>
      </div>

      {showNew && (
        <div className="card" style={{ padding: 14, marginBottom: 14 }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Nouvelle ressource</div>
          <div className="grid" style={{ gridTemplateColumns: "2fr 1fr 1fr 1fr auto", gap: 8 }}>
            <input className="input" placeholder="Titre" value={draft.title}
                   onChange={e => setDraft(d => ({ ...d, title: e.target.value }))} />
            <select className="input" value={draft.cat} onChange={e => setDraft(d => ({ ...d, cat: e.target.value }))}>
              {RESOURCE_CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
            </select>
            <select className="input" value={draft.kind} onChange={e => setDraft(d => ({ ...d, kind: e.target.value }))}>
              <option value="doc">Document</option>
              <option value="sheet">Feuille</option>
              <option value="template">Template</option>
              <option value="checklist">Checklist</option>
            </select>
            <input className="input" placeholder="Taille (ex: 12 pages)" value={draft.size}
                   onChange={e => setDraft(d => ({ ...d, size: e.target.value }))} />
            <div className="row" style={{ gap: 6 }}>
              <button className="btn" data-variant="primary" onClick={submitNew}>Ajouter</button>
              <button className="btn" data-variant="ghost" onClick={() => setShowNew(false)}>Annuler</button>
            </div>
          </div>
        </div>
      )}

      <div className="card" style={{ padding: 10, marginBottom: 14 }}>
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          <div className="input" style={{ flex: 1, minWidth: 200 }}>
            <Icon name="search" size={12} style={{ marginRight: 6, color: "var(--text-dim)" }} />
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Chercher une ressource…"
              style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)" }}
            />
          </div>
          <select value={cat} onChange={(e) => setCat(e.target.value)} className="input" style={{ width: 180 }}>
            <option value="all">Toutes catégories</option>
            {RESOURCE_CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
          </select>
          <select value={kind} onChange={(e) => setKind(e.target.value)} className="input" style={{ width: 150 }}>
            <option value="all">Tous types</option>
            <option value="doc">Documents</option>
            <option value="sheet">Feuilles</option>
            <option value="template">Templates</option>
            <option value="checklist">Checklists</option>
          </select>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 10 }}>
        {filtered.map((r, i) => {
          const catObj = RESOURCE_CATEGORIES.find(c => c.id === r.cat);
          const meta = KIND_META[r.kind] || KIND_META.doc;
          const update = (patch) => {
            setItems(items.map((it) => it === r ? { ...it, ...patch } : it));
          };
          const remove = (e) => {
            e.stopPropagation();
            if (!confirm(`Supprimer "${r.title}" ?`)) return;
            setItems(items.filter((it) => it !== r));
            toast({ message: `Supprimé · ${r.title}`, tone: "muted" });
          };
          return (
            <div key={i} className="card" style={{ padding: 12, position: "relative" }}>
              <button
                className="icon-btn"
                onClick={remove}
                title="Supprimer"
                style={{ position: "absolute", top: 6, right: 6, width: 22, height: 22, opacity: 0.4 }}
              >
                <Icon name="x" size={11} />
              </button>
              <div className="row" style={{ gap: 10 }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--bg-3)", display: "grid", placeItems: "center", color: "var(--text-dim)" }}>
                  <Icon name={meta.icon} size={14} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 550, lineHeight: 1.3, marginBottom: 4 }}>
                    <EditableField value={r.title} onSave={(v) => update({ title: v })} width="100%"/>
                  </div>
                  <div className="row" style={{ gap: 6 }}>
                    <EditableField
                      value={r.kind}
                      onSave={(v) => update({ kind: v })}
                      options={[
                        { value: "doc", label: "doc" },
                        { value: "sheet", label: "sheet" },
                        { value: "template", label: "template" },
                        { value: "checklist", label: "checklist" },
                      ]}
                      format={(v) => <Badge tone={(KIND_META[v] || meta).tone}>{v}</Badge>}
                      width={90}
                    />
                    <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>
                      <EditableField value={r.size} onSave={(v) => update({ size: v })} width={80}/>
                    </span>
                  </div>
                  <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)", marginTop: 4 }}>
                    <EditableField
                      value={r.cat}
                      onSave={(v) => update({ cat: v })}
                      options={RESOURCE_CATEGORIES.map(c => ({ value: c.id, label: c.label }))}
                      format={(v) => RESOURCE_CATEGORIES.find(c => c.id === v)?.label || v}
                      width={100}
                    />
                    {" · maj "}
                    <EditableField value={r.updated} onSave={(v) => update({ updated: v })} width={90}/>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
        {filtered.length === 0 && (
          <div className="card" style={{ gridColumn: "1 / -1", padding: 30, textAlign: "center", color: "var(--text-faint)" }}>
            Aucune ressource trouvée
          </div>
        )}
      </div>
    </div>
  );
};

window.Resources = Resources;
