// taches-re.jsx — Liste complète des tâches GHL dans RAYCAST (lecture via le relais sécurisé), avec urgences.
// Exposé : window.TachesRE ({ profile, compact, onNewFor })
//   onNewFor(prefill) (facultatif, sinon window.RaycastHandleNewFor) : bouton « Soumission » sur une tâche avec contact ;
//   la source du lead passée est celle de la tâche ou du contact GHL si connue, sinon vide.
(function () {
  const { useState, useEffect, useMemo, useRef } = React;
  // Éclair Raycom (défini par icons.jsx ou cloud/auth.jsx) ; repli local qui dessine la même silhouette quand ce module est chargé seul (tests, aperçus).
  const EclairRaycom = (p) => (window.EclairRaycom ? <window.EclairRaycom {...p} /> : <svg width={(p.size || 16) * 0.56} height={p.size || 16} viewBox="0 0 389 696" aria-hidden="true" className="rc-eclair" style={{ display: "inline-block", verticalAlign: "-0.15em", ...(p.style || {}) }}><polygon points="300,0 195,288 389,288 78,696 184,406 0,405" fill={p.couleur || "#0a6fc8"} /></svg>);
  const TZ = "America/Toronto";
  const LOC = "Ey6SB5epk8GFGgL5BfhX";
  const parseDate = (v) => { if (v == null || v === "") return null; const s = String(v).trim(); const d = new Date(/^\d{12,}$/.test(s) ? Number(s) : (/^\d{4}-\d{2}-\d{2}$/.test(s) ? s + "T12:00:00" : s)); return isNaN(d) ? null : d; };
  const quand = (iso) => { const d = parseDate(iso); return d ? d.toLocaleString("fr-CA", { timeZone: TZ, day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : ""; };
  // Même liste gardée 60 s en mémoire : le tableau de bord n'appelle pas /tasks à chaque passage.
  const CACHE_MS = 60000;
  const cache = {}; // "faites|limite" → { at, tasks }
  function TachesRE({ compact, onNewFor }) {
    const [etat, setEtat] = useState({ loading: true });
    const [voirFaites, setVoirFaites] = useState(false);
    const seq = useRef(0); // une réponse tardive (bascule « faites » rapide, démontage) n'écrase pas la liste courante
    const load = async (refresh) => {
      const id = ++seq.current;
      const cle = `${voirFaites ? 1 : 0}|${compact ? 25 : 100}`;
      const c = cache[cle];
      if (!refresh && c && Date.now() - c.at < CACHE_MS) { setEtat({ loading: false, tasks: c.tasks }); return; }
      setEtat(s => ({ ...s, loading: true, err: null }));
      try {
        if (!window.RaycastProxy) throw new Error("relais indisponible");
        const r = await window.RaycastProxy.fetch("ghl", "/tasks", { completed: voirFaites ? 1 : 0, limit: compact ? 25 : 100 }, { refresh });
        const tasks = Array.isArray(r && r.tasks) ? r.tasks : [];
        cache[cle] = { at: Date.now(), tasks };
        if (id === seq.current) setEtat({ loading: false, tasks });
      } catch (e) { if (id === seq.current) setEtat(s => ({ ...s, loading: false, err: String(e.message || e) })); }
    };
    useEffect(() => { load(false); }, [voirFaites]); // eslint-disable-line
    useEffect(() => () => { seq.current++; }, []);
    const tasks = useMemo(() => {
      const now = Date.now();
      // Urgentes d'abord, puis en retard, puis par échéance ; une tâche sans échéance va à la fin (et non en tête comme une date 0)
      return (etat.tasks || []).map((t, i) => { const d = parseDate(t.dueDate); const due = d ? d.getTime() : Infinity; return { ...t, _k: t.id || `tache-${i}`, _due: due, retard: d != null && due < now && !t.completed, urgent: /URGENT|panne|danger/i.test(String(t.title || "")) }; })
        .sort((a, b) => (b.urgent - a.urgent) || (b.retard - a.retard) || (a._due === b._due ? 0 : a._due - b._due));
    }, [etat.tasks]);
    const nRetard = tasks.filter(t => t.retard).length, nUrgent = tasks.filter(t => t.urgent).length;
    const lancer = onNewFor || window.RaycastHandleNewFor;
    const prefillDe = (t) => ({ name: t.contactName || "", ghl_contact_id: t.contactId || null, source: t.source || (t.contact && t.contact.source) || "" });
    return (
      <section className={"re-taches" + (compact ? " compact" : "")}>
        <div className="re-taches-head">
          <div><b>Tâches</b> <span className="re-taches-sub">{etat.loading && !etat.tasks ? "chargement…" : `${tasks.length} ${voirFaites ? "faite" : "à faire"}${tasks.length > 1 && voirFaites ? "s" : ""}${nRetard ? ` · ${nRetard} en retard` : ""}${nUrgent ? ` · ${nUrgent} urgente${nUrgent > 1 ? "s" : ""}` : ""}`}</span></div>
          <div className="re-taches-actions">
            <label className="re-check"><input type="checkbox" checked={voirFaites} onChange={e => setVoirFaites(e.target.checked)} /> faites</label>
            <button className="re-btn small" onClick={() => load(true)} disabled={!!etat.loading} title="Rafraîchir">↻</button>
          </div>
        </div>
        {etat.err && <div className="re-alert">Tâches indisponibles ({etat.err}).</div>}
        {!etat.loading && !etat.err && !tasks.length && <div className="re-vide">Aucune tâche {voirFaites ? "faite" : "en attente"}.</div>}
        <ul className="re-taches-liste">
          {tasks.map(t => (
            <li key={t._k} className={(t.urgent ? "urgent " : "") + (t.retard ? "retard" : "")}>
              <div className="re-tache-titre">{t.urgent && <span className="re-pastille rouge"><EclairRaycom size={9} couleur="#fff" style={{ marginRight: 4 }}/>URGENT</span>}{t.retard && !t.urgent && <span className="re-pastille orange"><EclairRaycom size={9} couleur="#fff" style={{ marginRight: 4 }}/>en retard</span>}<b>{t.title || "Tâche sans titre"}</b></div>
              <div className="re-tache-meta">{t.contactName && <span>{t.contactName}</span>}{t.dueDate && quand(t.dueDate) && <span>{quand(t.dueDate)}</span>}{t.contactId && <a href={`https://app.gohighlevel.com/v2/location/${LOC}/contacts/detail/${t.contactId}`} target="_blank" rel="noopener">ouvrir dans GHL</a>}{lancer && (t.contactName || t.contactId) && <button className="re-link" onClick={() => lancer(prefillDe(t))}><EclairRaycom size={10} style={{ marginRight: 3 }}/>soumission</button>}</div>
              {!compact && t.body && <div className="re-tache-corps">{t.body}</div>}
            </li>
          ))}
        </ul>
      </section>
    );
  }
  window.TachesRE = TachesRE;
})();
