// ============================================================
//  Polycall / SOPHON - Rappels programmes
//  - RemindersView : vue dediee (en retard / aujourd'hui / a venir)
//  - ReminderAlert : pop-up d'alerte 15 min avant l'heure
//  - useReminders  : hook de chargement + rafraichissement
// ============================================================

function reminderBucket(iso) {
  // Retourne : 'overdue' (passe), 'soon' (<15 min), 'today', 'upcoming'
  const now = new Date();
  const d = new Date(iso);
  const diffMin = (d - now) / 60000;
  if (diffMin < 0) return "overdue";
  if (diffMin <= 15) return "soon";
  const sameDay = d.toDateString() === now.toDateString();
  return sameDay ? "today" : "upcoming";
}

function fmtReminderTime(iso) {
  const d = new Date(iso);
  const now = new Date();
  const sameDay = d.toDateString() === now.toDateString();
  const time = d.toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" });
  if (sameDay) return "Aujourd'hui à " + time;
  return d.toLocaleDateString("fr-FR", { weekday: "short", day: "2-digit", month: "short" }) + " à " + time;
}

function reminderName(r) {
  return r.societe || [r.prenom, r.nom].filter(Boolean).join(" ") || r.tel || "Client";
}

// Hook : charge les rappels et les rafraichit toutes les 60 s.
function useReminders(active) {
  const [list, setList] = React.useState([]);
  const load = React.useCallback(async () => {
    try {
      const res = await PolycallAPI.reminders();
      setList((res && res.reminders) || []);
    } catch (e) { /* silencieux */ }
  }, []);
  React.useEffect(() => {
    if (!active) return;
    load();
    const t = setInterval(load, 60000);
    return () => clearInterval(t);
  }, [active, load]);
  return { list, reload: load };
}

// Compteur de rappels "dus" (en retard + dans les 15 min + aujourd'hui).
function dueCount(list) {
  return list.filter((r) => {
    const b = reminderBucket(r.recallAt);
    return b === "overdue" || b === "soon" || b === "today";
  }).length;
}

// ---- Vue dediee ----
function RemindersView({ list, onClose, onOpenFiche, isManager }) {
  const groups = { overdue: [], soon: [], today: [], upcoming: [] };
  list.forEach((r) => groups[reminderBucket(r.recallAt)].push(r));

  const Section = ({ title, items, color, icon }) => {
    if (!items.length) return null;
    return (
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontSize: 12, fontWeight: 700, color, marginBottom: 8, display: "flex", alignItems: "center", gap: 6, textTransform: "uppercase", letterSpacing: ".04em" }}>
          {icon} {title} <span style={{ opacity: .7 }}>({items.length})</span>
        </div>
        <div style={{ display: "grid", gap: 8 }}>
          {items.map((r) => (
            <div key={r.id} onClick={() => onOpenFiche && onOpenFiche(r)}
              style={{ border: "1px solid var(--line)", borderLeft: "3px solid " + color, borderRadius: 9, padding: "10px 13px", background: "var(--surface)", cursor: onOpenFiche ? "pointer" : "default", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
              <div>
                <div style={{ fontWeight: 600, fontSize: 13.5, color: "var(--ink)" }}>{reminderName(r)}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-soft)", marginTop: 2, display: "flex", gap: 10, flexWrap: "wrap" }}>
                  {r.tel && <span>{r.tel}</span>}
                  {isManager && r.agentName && <span>· {r.agentName}</span>}
                  {r.motif && <span style={{ opacity: .8 }}>· {r.motif.slice(0, 40)}{r.motif.length > 40 ? "…" : ""}</span>}
                </div>
              </div>
              <div style={{ fontSize: 12, fontWeight: 600, color, whiteSpace: "nowrap" }}>{fmtReminderTime(r.recallAt)}</div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className="dash-overlay" style={{ position: "fixed", inset: 0, zIndex: 150, background: "var(--bg)", display: "flex", flexDirection: "column" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "18px 24px", borderBottom: "1px solid var(--line)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <I.calendar s={22} />
          <div>
            <div style={{ fontWeight: 700, fontSize: 17 }}>Rappels programmés</div>
            <div style={{ fontSize: 12, color: "var(--ink-soft)" }}>{isManager ? "Tous les rappels de l'opération" : "Vos rappels"}</div>
          </div>
        </div>
        <button className="iconbtn" onClick={onClose} title="Fermer"><I.x s={18} /></button>
      </div>
      <div style={{ flex: 1, overflowY: "auto", padding: "20px 24px", maxWidth: 900, width: "100%", margin: "0 auto" }}>
        {list.length === 0
          ? <div style={{ textAlign: "center", color: "var(--ink-faint)", paddingTop: 60 }}>
              <I.calendar s={40} style={{ opacity: .3 }} />
              <div style={{ marginTop: 12, fontSize: 14 }}>Aucun rappel programmé.</div>
            </div>
          : <>
              <Section title="En retard" items={groups.overdue} color="#c0392b" icon={<I.info s={13} />} />
              <Section title="Imminent (< 15 min)" items={groups.soon} color="#b9760f" icon={<I.calendar s={13} />} />
              <Section title="Aujourd'hui" items={groups.today} color="#2a6fdb" icon={<I.calendar s={13} />} />
              <Section title="À venir" items={groups.upcoming} color="#6c6764" icon={<I.calendar s={13} />} />
            </>}
      </div>
    </div>
  );
}

// ---- Pop-up d'alerte (15 min avant) ----
function ReminderAlert({ reminder, onClose, onOpen }) {
  if (!reminder) return null;
  return (
    <>
      <div style={{ position: "fixed", inset: 0, zIndex: 300, background: "rgba(0,0,0,.4)" }} onClick={onClose} />
      <div style={{ position: "fixed", top: 24, right: 24, zIndex: 301, width: 340, maxWidth: "90vw", background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 14, padding: 18, boxShadow: "0 12px 40px rgba(0,0,0,.3)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 10 }}>
          <span style={{ width: 34, height: 34, borderRadius: 9, background: "var(--bad-tint, #fdecea)", color: "#c0392b", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><I.calendar s={18} /></span>
          <b style={{ fontSize: 14.5 }}>Rappel imminent</b>
        </div>
        <div style={{ fontSize: 13.5, color: "var(--ink)", marginBottom: 4 }}>
          <b>{reminderName(reminder)}</b>
        </div>
        <div style={{ fontSize: 12.5, color: "var(--ink-soft)", marginBottom: 14 }}>
          {fmtReminderTime(reminder.recallAt)}{reminder.tel ? " · " + reminder.tel : ""}
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="acct-item" onClick={onClose} style={{ flex: 1, justifyContent: "center" }}>Plus tard</button>
          <button className="acct-item" onClick={() => onOpen(reminder)} style={{ flex: 1, justifyContent: "center", background: "var(--solid)", color: "var(--on-solid)" }}>Ouvrir la fiche</button>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { RemindersView, ReminderAlert, useReminders, dueCount, reminderBucket });
