// <AgendaAnimation /> — ambient calendar→agenda visual for the hero.
// Phase 0: month calendar view
// Phase 1: selected day pulses, swaps to agenda
// Phase 2: agenda fills via Sonaro tools (reminder, recovery, voice, retention, review)

const { useState: useAS, useEffect: useAE, useRef: useAR } = React;

// Tick = 100ms. 170 ticks = 17s loop.
const T_DAY_SELECT = 6;    // 0.6s — selected day pulses
const T_AGENDA_IN  = 18;   // 1.8s — agenda swaps in
const T_REMINDER   = 28;   // 2.8s — Sara reminder
const T_CANCEL     = 50;   // 5.0s — Marco R cancels
const T_RECOVER    = 72;   // 7.2s — slot recovered → Paola
const T_VOICE      = 94;   // 9.4s — Voice books 11:00 (Marco P)
const T_NOSHOW     = 116;  // 11.6s — Luca M reminder catches no-show
const T_RETENTION  = 138;  // 13.8s — Elisa F reactivated at 15:00
const T_REVIEW     = 156;  // 15.6s — Sara C review collected
const T_SETTLE     = 167;  // 16.7s — counter resolves at +€540

// Status colors and tool colors stay hard-coded (they're visual identity).
// Labels are pulled from window.CONTENT[lang].agenda at render time so the
// animation localizes correctly for /it/ pages.
const STATUS = {
  Confirmed:   { bg: "#E0F2FE", fg: "#075985" },
  Cancelled:   { bg: "#FECACA", fg: "#B91C1C" },
  Recovered:   { bg: "#D1FAE5", fg: "#047857" },
  Voice:       { bg: "#DBEAFE", fg: "#1D4ED8" },
  Reactivated: { bg: "#CCFBF1", fg: "#115E59" },
  Amber:       { bg: "#FEF3C7", fg: "#B45309" }
};

const TOOL_COLOR = {
  voice:     "#60A5FA",
  reminders: "#14B8A6",
  reviews:   "#F59E0B",
  recovery:  "#EF4444",
  retention: "#8B5CF6"
};

// Reads the current i18n agenda block. Falls back to EN if a key is missing.
function getAgendaContent() {
  const lang = (typeof window !== "undefined" && window.__sonaroLang) || "en";
  const dict = (typeof window !== "undefined" && window.CONTENT) || {};
  return (dict[lang] && dict[lang].agenda) || (dict.en && dict.en.agenda) || {};
}
const TOOL_ORDER = ["voice", "reminders", "reviews", "recovery", "retention"];

function AgendaAnimation() {
  const [tick, setTick] = useAS(0);
  const [reduced, setReduced] = useAS(false);
  const [visible, setVisible] = useAS(true);
  const ref = useAR(null);
  // i18n: every visible string comes from CONTENT[lang].agenda.
  const t = getAgendaContent();

  useAE(() => {
    if (typeof window === "undefined" || !window.matchMedia) return;
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(mq.matches);
    update();
    if (mq.addEventListener) mq.addEventListener("change", update);
    else mq.addListener(update);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener("change", update);
      else mq.removeListener(update);
    };
  }, []);

  useAE(() => {
    if (!ref.current || typeof IntersectionObserver === "undefined") return;
    const io = new IntersectionObserver(
      ([entry]) => setVisible(entry.isIntersecting),
      { threshold: 0 }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);

  useAE(() => {
    if (reduced || !visible) return;
    const id = setInterval(() => setTick(t => (t + 1) % 170), 100);
    return () => clearInterval(id);
  }, [reduced, visible]);

  // reduced motion → render resolved state
  const T = reduced ? 168 : tick;
  const inAgenda = T >= T_AGENDA_IN;

  return (
    <div
      ref={ref}
      role="img"
      aria-label={t.aria}
      style={{
        position: "relative",
        width: "100%",
        marginLeft: "auto", marginRight: "auto",
        maxWidth: 560
      }}
    >
      {/* card */}
      <div style={{
        position: "relative",
        height: "100%",
        minHeight: 540,
        background: "rgba(255, 255, 255, 0.96)",
        backdropFilter: "blur(24px) saturate(140%)",
        WebkitBackdropFilter: "blur(24px) saturate(140%)",
        border: "1px solid rgba(231, 228, 216, 0.55)",
        borderRadius: 24,
        overflow: "hidden",
        boxShadow:
          "0 30px 60px -30px rgba(0,0,0,0.55), " +
          "0 0 40px rgba(155, 201, 210, 0.28), " +
          "inset 0 1px 0 rgba(255,255,255,0.6)",
        display: "flex", flexDirection: "column"
      }}>
        <AgendaHeader inAgenda={inAgenda} t={t} />

        <div style={{
          position: "relative", flex: 1, minHeight: 0,
          overflow: "hidden"
        }}>
          {/* calendar layer */}
          <div style={{
            position: "absolute", inset: 0,
            opacity: inAgenda ? 0 : 1,
            transform: inAgenda ? "scale(0.97)" : "scale(1)",
            transition: "opacity 0.45s ease, transform 0.5s cubic-bezier(0.22, 1, 0.36, 1)",
            pointerEvents: inAgenda ? "none" : "auto"
          }}>
            <CalendarView T={T} t={t} />
          </div>

          {/* agenda layer */}
          <div style={{
            position: "absolute", inset: 0,
            opacity: inAgenda ? 1 : 0,
            transform: inAgenda ? "scale(1)" : "scale(1.04)",
            transition: "opacity 0.5s ease 0.05s, transform 0.55s cubic-bezier(0.22, 1, 0.36, 1) 0.05s",
            pointerEvents: inAgenda ? "auto" : "none"
          }}>
            <AgendaView T={T} reduced={reduced} t={t} />
          </div>
        </div>

        <AgendaFooter T={T} reduced={reduced} t={t} />
      </div>

      <RichToast T={T} t={t} />
    </div>
  );
}

// ============================================================================
// Header
// ============================================================================
function AgendaHeader({ inAgenda, t }) {
  const h = t.header || {};
  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "14px 18px",
      borderBottom: "1px solid #E7E4D8",
      background: "rgba(245,243,235,0.5)",
      flex: "none"
    }}>
      <div style={{ display: "flex", flexDirection: "column" }}>
        <span className="mono" style={{
          fontSize: 10.5, letterSpacing: "0.16em",
          textTransform: "uppercase", color: "#6B7280",
          whiteSpace: "nowrap"
        }}>
          {inAgenda ? h.agendaTitle : h.calendarTitle}
        </span>
        <span style={{
          fontSize: 11, color: "#9CA3AF", marginTop: 2,
          whiteSpace: "nowrap"
        }}>
          {inAgenda ? h.agendaSub : h.calendarSub}
        </span>
      </div>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}>
        <span className="agenda-live-dot" />
        <span className="mono" style={{ fontSize: 10, letterSpacing: "0.18em", color: "#10B981", fontWeight: 600 }}>
          {h.live}
        </span>
      </span>
    </div>
  );
}

// ============================================================================
// Calendar view (month grid, selects day 12)
// ============================================================================
function CalendarView({ T, t }) {
  // May 2026 — May 1 is a Friday. ISO week starts Monday.
  // Mon=0, Tue=1, Wed=2, Thu=3, Fri=4, Sat=5, Sun=6
  const startOffset = 4;
  const daysInMonth = 31;
  const selectedDay = 12;
  const cal = t.calendar || {};

  const cells = [];
  for (let i = 0; i < startOffset; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  const dayLabels = cal.dayLabels || ["M", "T", "W", "T", "F", "S", "S"];

  // Days that have appointments — small dot indicator
  const busyDays = new Set([2, 5, 6, 8, 9, 12, 13, 14, 15, 16, 19, 20, 22, 23, 26, 27, 28, 29, 30]);

  const dayPulses = T >= T_DAY_SELECT && T < T_AGENDA_IN;
  const daySelected = T >= T_DAY_SELECT;

  return (
    <div style={{
      height: "100%",
      padding: "20px 22px 14px",
      display: "flex", flexDirection: "column"
    }}>
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        marginBottom: 14
      }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
          <span className="display" style={{
            fontSize: 22, fontWeight: 700, letterSpacing: "-0.025em", color: "#0A0E12"
          }}>
            {cal.monthName}
          </span>
          <span className="mono" style={{ fontSize: 13, color: "#9CA3AF", fontWeight: 500 }}>{cal.year}</span>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <CalNavBtn>‹</CalNavBtn>
          <CalNavBtn>›</CalNavBtn>
        </div>
      </div>

      {/* day labels */}
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(7, 1fr)",
        gap: 4, marginBottom: 6
      }}>
        {dayLabels.map((l, i) => (
          <div key={i} className="mono" style={{
            textAlign: "center", fontSize: 10.5, letterSpacing: "0.12em",
            color: "#9CA3AF", fontWeight: 600, padding: "2px 0"
          }}>
            {l}
          </div>
        ))}
      </div>

      {/* day cells */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(7, 1fr)",
        gridAutoRows: "1fr",
        gap: 4,
        flex: 1
      }}>
        {cells.map((d, i) => {
          if (d === null) {
            return <div key={i} />;
          }
          const isSelected = d === selectedDay;
          const isBusy = busyDays.has(d);
          return (
            <div key={i} style={{
              position: "relative",
              borderRadius: 10,
              background: isSelected && daySelected ? "#0B0F14" : "transparent",
              color: isSelected && daySelected ? "#F5F3EB" : "#0A0E12",
              border: isSelected && daySelected
                ? "1px solid #0B0F14"
                : "1px solid transparent",
              display: "flex", alignItems: "center", justifyContent: "center",
              flexDirection: "column",
              padding: 4,
              transition: "background 0.4s ease, color 0.4s ease, transform 0.5s cubic-bezier(0.22, 1, 0.36, 1)",
              transform: isSelected && dayPulses ? "scale(1.06)" : "scale(1)",
              boxShadow: isSelected && daySelected
                ? "0 6px 20px -10px rgba(11,15,20,0.45)"
                : "none"
            }}>
              {/* selected glow ring */}
              {isSelected && dayPulses && (
                <div className="cal-day-glow" />
              )}
              <span style={{
                fontSize: 14.5, fontWeight: isSelected ? 700 : 500,
                fontVariantNumeric: "tabular-nums",
                lineHeight: 1
              }}>
                {d}
              </span>
              {isBusy && (
                <span style={{
                  width: 4, height: 4, borderRadius: 999,
                  background: isSelected && daySelected ? "#9BC9D2" : "#10B981",
                  marginTop: 4
                }} />
              )}
            </div>
          );
        })}
      </div>

      {/* footer hint */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        marginTop: 12, paddingTop: 10, borderTop: "1px solid #F3F2EA"
      }}>
        <span className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", color: "#9CA3AF", textTransform: "uppercase" }}>
          {daySelected ? cal.openingAgenda : cal.selecting}
        </span>
        <span style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          fontSize: 11, color: "#10B981", fontFamily: "var(--font-mono)", letterSpacing: "0.04em", fontWeight: 600
        }}>
          <span style={{ width: 5, height: 5, borderRadius: 999, background: "#10B981" }} />
          {cal.bookingsHint}
        </span>
      </div>
    </div>
  );
}

function CalNavBtn({ children }) {
  return (
    <button style={{
      width: 24, height: 24, borderRadius: 7,
      background: "#F3F2EA", border: "1px solid #E7E4D8",
      color: "#6B7280", fontSize: 14, lineHeight: 1,
      display: "grid", placeItems: "center", cursor: "default",
      padding: 0
    }}>
      {children}
    </button>
  );
}

// ============================================================================
// Agenda view (day rows that fill, cancel, recover, etc.)
// ============================================================================
function AgendaView({ T, reduced, t }) {
  const reminderFired   = T >= T_REMINDER;
  const cancelled       = T >= T_CANCEL && T < T_RECOVER;
  const recovered       = T >= T_RECOVER;
  const voiceBooked     = T >= T_VOICE;
  const noShowFlicker   = T >= T_NOSHOW && T < T_NOSHOW + 8;
  const noShowPrevented = T >= T_NOSHOW;
  const retentionFired  = T >= T_RETENTION;
  const reviewCollected = T >= T_REVIEW;
  // Each row keeps its semantic service key (Hygiene/Checkup/…) so we can
  // look up the localized service name + status label at render time.
  const svc = (t && t.services) || {};

  const row0900 = {
    time: "09:00",
    service: svc.Hygiene || "Hygiene", patient: "Sara C.",
    doctor: "Dr. Bianchi",
    status: "Confirmed",
    badge: reminderFired ? "✓" : null,
    review: reviewCollected
  };

  const row1000 = recovered
    ? { time: "10:00", service: svc.Checkup || "Checkup", patient: "Paola N.",
        doctor: "Dr. Bianchi", status: "Recovered", revenue: "+€120" }
    : cancelled
      ? { time: "10:00", service: svc.Checkup || "Checkup", patient: "Marco R.",
          doctor: "Dr. Bianchi", status: "Cancelled", strike: true, revenue: "−€120" }
      : { time: "10:00", service: svc.Checkup || "Checkup", patient: "Marco R.",
          doctor: "Dr. Bianchi", status: "Confirmed" };

  const row1100 = voiceBooked
    ? { time: "11:00", service: svc.Hygiene || "Hygiene", patient: "Marco P.",
        doctor: "Dr. Bianchi", status: "Voice",
        revenue: "+€90",
        phoneRing: T >= T_VOICE && T < T_VOICE + 18 }
    : { time: "11:00", empty: true };

  const row1200 = { time: "12:00", service: svc.Followup || "Followup", patient: "Anna B.",
                   doctor: "Dr. Rossi", status: "Confirmed" };

  const row1400 = {
    time: "14:00", service: svc.Implant || "Implant", patient: "Luca M.",
    doctor: "Dr. Verdi",
    status: noShowFlicker ? "Amber" : "Confirmed",
    badge: noShowPrevented && !noShowFlicker ? "+12h" : null
  };

  const row1500 = retentionFired
    ? { time: "15:00", service: svc.Followup || "Followup", patient: "Elisa F.",
        doctor: "Dr. Verdi", status: "Reactivated", revenue: "+€90" }
    : { time: "15:00", empty: true };

  const row1600 = { time: "16:00", service: svc.Cleaning || "Cleaning", patient: "Giulia T.",
                    doctor: "Dr. Rossi", status: "Confirmed" };

  const rows = [row0900, row1000, row1100, row1200, row1400, row1500, row1600];

  return (
    <div style={{ padding: "10px 8px 12px", height: "100%", overflow: "auto" }}>
      {rows.map((r, i) => <AgendaRow key={i} row={r} t={t} />)}
    </div>
  );
}

// row -----------------------------------------------------------------------
function AgendaRow({ row, t }) {
  const swapKey = `${row.time}-${row.patient || "empty"}-${row.status || ""}`;
  return (
    <div className="agenda-row" key={swapKey} style={{
      display: "grid",
      gridTemplateColumns: "52px 1fr auto",
      alignItems: "stretch",
      gap: 12, padding: "5px 10px",
      borderRadius: 12
    }}>
      <div className="mono" style={{
        fontSize: 12, color: "#6B7280", fontVariantNumeric: "tabular-nums",
        paddingTop: 12
      }}>
        {row.time}
      </div>

      {row.empty ? (
        // Active "filling" state: text + indeterminate progress bar. Conveys
        // that Sonaro is actively working to refill the slot, not just
        // showing a hole in the schedule. Once T_VOICE / T_RETENTION fire,
        // the row swaps to a real RowPill above.
        <div style={{
          minHeight: 52, borderRadius: 10,
          background: "#F3F4F6",
          border: "1px dashed #E5E7EB",
          display: "flex", flexDirection: "column",
          justifyContent: "center", gap: 6,
          padding: "8px 14px"
        }}>
          <div style={{
            fontSize: 12.5, color: "#6B7280", fontWeight: 500,
            display: "flex", alignItems: "center", gap: 6,
            whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"
          }}>
            <span style={{
              width: 6, height: 6, borderRadius: 999,
              background: "#14B8A6",
              animation: "agenda-fill-dot 1.4s ease-in-out infinite",
              flex: "none"
            }} />
            {(t && t.fillingSlot) || "Sonaro is trying to fill this slot…"}
          </div>
          <div style={{
            height: 3, borderRadius: 999,
            background: "rgba(11,15,20,0.06)",
            overflow: "hidden",
            position: "relative"
          }}>
            <div style={{
              position: "absolute", top: 0, bottom: 0,
              width: "40%",
              background: "linear-gradient(90deg, transparent, #14B8A6, transparent)",
              animation: "agenda-fill-bar 1.6s ease-in-out infinite"
            }} />
          </div>
        </div>
      ) : (
        <RowPill row={row} t={t} />
      )}

      <div style={{
        minWidth: 60, textAlign: "right",
        fontFamily: "var(--font-mono)", fontSize: 12,
        color: row.revenue && row.revenue.startsWith("−") ? "#B91C1C" : "#047857",
        fontWeight: 600,
        paddingTop: 12
      }}>
        {row.revenue || ""}
      </div>
    </div>
  );
}

function RowPill({ row, t }) {
  const status = STATUS[row.status] || STATUS.Confirmed;
  // Status label is localized; the chip background+fg colors stay constant.
  const statusLabel = ((t && t.status) || {})[row.status] || row.status;
  return (
    <div style={{
      minHeight: 52,
      borderRadius: 10,
      background: status.bg,
      color: status.fg,
      padding: "8px 12px 9px",
      display: "flex", flexDirection: "column", justifyContent: "center",
      overflow: "hidden", gap: 2
    }}>
      {/* line 1 */}
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        {row.phoneRing && (
          <span className="agenda-ring" style={{
            display: "inline-flex", color: "#1D4ED8", flex: "none"
          }}>
            {window.Icon ? <window.Icon.Phone size={12} /> : null}
          </span>
        )}

        <div style={{
          fontSize: 13.5, color: "#0A0E12", fontWeight: 600,
          textDecoration: row.strike ? "line-through" : "none",
          opacity: row.strike ? 0.7 : 1,
          whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
          flex: 1, letterSpacing: "-0.005em"
        }}>
          {row.service} · {row.patient}
          {row.review && (
            <span style={{ marginLeft: 6, color: "#F59E0B", letterSpacing: "0.05em", fontSize: 11 }}>
              ★★★★★
            </span>
          )}
        </div>

        <span style={{
          flex: "none",
          fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.12em",
          textTransform: "uppercase", fontWeight: 700,
          color: status.fg,
          background: "rgba(255,255,255,0.55)",
          padding: "3px 7px", borderRadius: 6,
          whiteSpace: "nowrap",
          display: "inline-flex", alignItems: "center", gap: 4
        }}>
          {statusLabel}
          {row.badge && <span style={{ opacity: 0.85 }}>· {row.badge}</span>}
        </span>
      </div>

      {/* line 2: doctor only */}
      <div style={{
        fontSize: 11.5, color: status.fg, opacity: 0.72,
        fontWeight: 500
      }}>
        {row.doctor}
      </div>
    </div>
  );
}

// ============================================================================
// Footer (revenue counter + tool chips)
// ============================================================================
function AgendaFooter({ T, reduced, t }) {
  const footer = (t && t.footer) || {};
  const toolPulses = {
    voice:      pulseWindow(T, T_VOICE),
    reminders:  pulseWindow(T, T_REMINDER) || pulseWindow(T, T_NOSHOW),
    reviews:    pulseWindow(T, T_REVIEW),
    recovery:   pulseWindow(T, T_CANCEL) || pulseWindow(T, T_RECOVER),
    retention:  pulseWindow(T, T_RETENTION)
  };

  const targetRev =
    T >= T_SETTLE     ? 540 :
    T >= T_REVIEW     ? 540 :
    T >= T_RETENTION  ? 420 :
    T >= T_VOICE      ? 330 :
    T >= T_RECOVER    ? 240 :
    T >= T_CANCEL     ? 120 :
    T >= T_AGENDA_IN  ? 240 :
    0;

  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      gap: 16, padding: "14px 18px",
      borderTop: "1px solid #E7E4D8",
      background: "rgba(245,243,235,0.5)",
      flex: "none"
    }}>
      <div style={{ minWidth: 140 }}>
        <div className="mono" style={{
          fontSize: 9.5, letterSpacing: "0.18em", color: "#6B7280",
          textTransform: "uppercase", whiteSpace: "nowrap"
        }}>
          {footer.revenueToday || "Revenue today"}
        </div>
        <div className="display" style={{
          fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em",
          color: "#0A0E12", marginTop: 2,
          fontVariantNumeric: "tabular-nums",
          display: "inline-flex", alignItems: "baseline", gap: 6,
          whiteSpace: "nowrap"
        }}>
          <CountUp target={targetRev} reduced={reduced} />
          {T >= T_SETTLE && (
            <span style={{
              fontSize: 12, color: "#10B981", fontWeight: 600,
              display: "inline-flex", alignItems: "center", gap: 2
            }}>
              {footer.todayTag || "↑ TODAY"}
            </span>
          )}
        </div>
      </div>

      <div style={{ display: "flex", gap: 6 }}>
        {TOOL_ORDER.map(key => (
          <ToolChip key={key} toolKey={key} active={toolPulses[key]} t={t} />
        ))}
      </div>
    </div>
  );
}

function pulseWindow(T, eventTick) {
  return T >= eventTick && T < eventTick + 8;
}

function ToolChip({ toolKey, active, t }) {
  const color = TOOL_COLOR[toolKey] || "#6B7280";
  const label = ((t && t.tools) || {})[toolKey] || toolKey.toUpperCase();
  const tool = { color, label };
  const iconFor = (key) => {
    if (!window.Icon) return null;
    if (key === "voice")     return <window.Icon.Phone size={11} />;
    if (key === "reminders") return <window.Icon.Chat size={11} />;
    if (key === "reviews")   return <window.Icon.Star size={11} />;
    if (key === "recovery")  return <window.Icon.Arrow size={11} />;
    if (key === "retention") return <window.Icon.Spark size={11} />;
    return null;
  };
  return (
    <div
      title={tool.label.toLowerCase()}
      className={active ? "agenda-tool-pulse" : ""}
      style={{
        width: 26, height: 26, borderRadius: 8,
        display: "grid", placeItems: "center",
        background: active ? `${tool.color}22` : "#F3F4F6",
        color: active ? tool.color : "#9CA3AF",
        border: `1px solid ${active ? `${tool.color}55` : "#E5E7EB"}`,
        transition: "background 0.2s ease, color 0.2s ease, border-color 0.2s ease"
      }}
    >
      {iconFor(toolKey)}
    </div>
  );
}

// CountUp -------------------------------------------------------------------
function CountUp({ target, reduced }) {
  const [val, setVal] = useAS(reduced ? 540 : 0);
  useAE(() => {
    if (reduced) { setVal(540); return; }
    let v = val;
    if (Math.abs(target - v) < 1) return;
    const id = setInterval(() => {
      v += (target - v) * 0.22;
      if (Math.abs(target - v) < 0.5) {
        v = target;
        setVal(Math.round(v));
        clearInterval(id);
      } else {
        setVal(Math.round(v));
      }
    }, 30);
    return () => clearInterval(id);
  }, [target, reduced]);

  return <span style={{ fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>€ {val.toLocaleString("it-IT")}</span>;
}

// ============================================================================
// Rich toast — bleeds outside the card on the right
// ============================================================================
function RichToast({ T, t: agenda }) {
  // Pull localized copy. Each toast is identified by a semantic key
  // (reminder / cancel / recover / voice / noShow / retention / review)
  // that maps both to its lang-aware strings and to its tool+row metadata.
  const localized = (agenda && agenda.toasts) || {};
  const TOAST_META = [
    { key: "reminder",  win: [T_REMINDER, 20], tool: "reminders", rowIdx: 0 },
    { key: "cancel",    win: [T_CANCEL,    21], tool: "recovery",  rowIdx: 1 },
    { key: "recover",   win: [T_RECOVER,   21], tool: "recovery",  rowIdx: 1 },
    { key: "voice",     win: [T_VOICE,     21], tool: "voice",     rowIdx: 2 },
    { key: "noShow",    win: [T_NOSHOW,    21], tool: "reminders", rowIdx: 4 },
    { key: "retention", win: [T_RETENTION, 18], tool: "retention", rowIdx: 5 },
    { key: "review",    win: [T_REVIEW,    18], tool: "reviews",   rowIdx: 0 }
  ];

  let toast = null;
  for (const meta of TOAST_META) {
    if (T >= meta.win[0] && T < meta.win[0] + meta.win[1]) {
      const copy = localized[meta.key] || {};
      toast = {
        tool: meta.tool,
        rowIdx: meta.rowIdx,
        title:  copy.title  || "",
        detail: copy.detail || "",
        impact: copy.impact || ""
      };
      break;
    }
  }

  const key = toast ? `${toast.tool}-${toast.rowIdx}-${toast.title}` : null;
  const [resident, setResident] = useAS(null);
  const [visible,  setVisible]  = useAS(false);

  useAE(() => {
    if (key) {
      setResident(toast);
      setVisible(true);
    } else {
      setVisible(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [key]);

  const t = resident;
  // header ~58px, each row ~62px (52 minHeight + 5+5 padding); cap so it doesn't run past footer
  const rowY = t ? Math.min(70 + t.rowIdx * 62, 380) : 0;
  // Resolve current tool color (lookup table) for the toast accent stripe.
  const tool = t ? { color: TOOL_COLOR[t.tool] || "#6B7280" } : null;

  const toolIcon = (k) => {
    if (!window.Icon || !k) return null;
    if (k === "voice")     return <window.Icon.Phone size={12} />;
    if (k === "reminders") return <window.Icon.Chat size={12} />;
    if (k === "reviews")   return <window.Icon.Star size={12} />;
    if (k === "recovery")  return <window.Icon.Arrow size={12} />;
    if (k === "retention") return <window.Icon.Spark size={12} />;
    return null;
  };

  return (
    <>
      <div
        className={`agenda-rich-toast${visible ? " is-visible" : ""}`}
        style={{ top: rowY }}
      >
        {t && tool && (
          <div style={{
            background: "#0B0F14",
            color: "#F5F3EB",
            borderRadius: 14,
            border: `1px solid ${tool.color}55`,
            padding: "12px 13px 11px",
            boxShadow: `0 20px 40px -18px rgba(0,0,0,0.6), 0 6px 14px -8px rgba(0,0,0,0.35), 0 0 0 1px ${tool.color}22`,
            position: "relative"
          }}>
            <span style={{
              position: "absolute", left: -7, top: 18,
              width: 14, height: 14,
              background: "#0B0F14",
              borderLeft: `1px solid ${tool.color}55`,
              borderBottom: `1px solid ${tool.color}55`,
              transform: "rotate(45deg)"
            }} />

            <div style={{
              display: "inline-flex", alignItems: "center", gap: 7,
              padding: "3px 9px 3px 6px",
              background: `${tool.color}1f`,
              border: `1px solid ${tool.color}55`,
              borderRadius: 999,
              marginBottom: 8
            }}>
              <span style={{
                width: 18, height: 18, borderRadius: 999,
                display: "grid", placeItems: "center",
                background: `${tool.color}33`, color: tool.color
              }}>
                {toolIcon(t.tool)}
              </span>
              <span className="mono" style={{
                fontSize: 9.5, letterSpacing: "0.18em",
                color: tool.color, fontWeight: 700
              }}>
                SONARO · {tool.label}
              </span>
            </div>

            <div style={{
              fontSize: 14, fontWeight: 600, lineHeight: 1.3,
              color: "#F5F3EB", letterSpacing: "-0.01em", marginBottom: 4
            }}>
              {t.title}
            </div>

            <div style={{
              fontSize: 12, lineHeight: 1.4,
              color: "#A1A8B3", marginBottom: 8
            }}>
              {t.detail}
            </div>

            <div style={{
              display: "inline-flex", alignItems: "center", gap: 6,
              padding: "4px 8px",
              background: "rgba(16, 185, 129, 0.12)",
              border: "1px solid rgba(16, 185, 129, 0.28)",
              color: "#34d399",
              borderRadius: 6,
              fontSize: 11, fontWeight: 600,
              fontFamily: "var(--font-mono)", letterSpacing: "0.04em"
            }}>
              <span style={{ width: 4, height: 4, borderRadius: 999, background: "#34d399" }} />
              {t.impact}
            </div>
          </div>
        )}
      </div>

      <style>{`
        .agenda-rich-toast {
          position: absolute;
          right: calc(-1 * var(--toast-bleed, 240px));
          width: 304px;
          opacity: 0;
          transform: translateX(20px);
          pointer-events: none;
          transition:
            opacity 0.35s ease-out,
            transform 0.4s cubic-bezier(0.22, 1, 0.36, 1),
            top 0.45s cubic-bezier(0.22, 1, 0.36, 1);
          z-index: 5;
        }
        .agenda-rich-toast.is-visible {
          opacity: 1;
          transform: translateX(0);
        }
        .agenda-rich-toast { --toast-bleed: 240px; }
        @media (max-width: 1200px) { .agenda-rich-toast { --toast-bleed: 140px; width: 280px; } }
        @media (max-width: 1024px) { .agenda-rich-toast { --toast-bleed: 50px;  width: 260px; } }
        @media (max-width: 720px)  { .agenda-rich-toast { --toast-bleed: 8px;   width: 240px; } }

        @keyframes agenda-live-pulse {
          0%, 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.55); }
          50%      { box-shadow: 0 0 0 5px rgba(16, 185, 129, 0); }
        }
        .agenda-live-dot {
          width: 7px; height: 7px; border-radius: 999px;
          background: #10B981;
          animation: agenda-live-pulse 2s ease-out infinite;
        }
        @keyframes agenda-row-in {
          from { opacity: 0; transform: translateY(4px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        .agenda-row { animation: agenda-row-in 0.3s ease-out both; }
        @keyframes agenda-tool-pulse {
          0%   { transform: scale(1); }
          50%  { transform: scale(1.14); }
          100% { transform: scale(1); }
        }
        .agenda-tool-pulse { animation: agenda-tool-pulse 0.6s ease-out; }
        @keyframes agenda-ring {
          0%, 100% { transform: rotate(0); }
          25%      { transform: rotate(-8deg); }
          75%      { transform: rotate(8deg); }
        }
        .agenda-ring { animation: agenda-ring 0.6s ease-in-out infinite; }
        @keyframes cal-day-glow-anim {
          0%, 100% { box-shadow: 0 0 0 0 rgba(11,15,20,0.0); }
          50%      { box-shadow: 0 0 0 6px rgba(11,15,20,0.12); }
        }
        .cal-day-glow {
          position: absolute; inset: 0; border-radius: 10px;
          animation: cal-day-glow-anim 1.4s ease-out infinite;
          pointer-events: none;
        }
        /* Empty-slot "filling" indicator: a teal ribbon sliding inside a
           thin track, paired with a soft pulsing dot. Communicates that
           Sonaro is actively trying to refill the slot. */
        @keyframes agenda-fill-bar {
          0%   { transform: translateX(-100%); }
          100% { transform: translateX(260%); }
        }
        @keyframes agenda-fill-dot {
          0%, 100% { opacity: 0.55; }
          50%      { opacity: 1; }
        }
      `}</style>
    </>
  );
}

window.AgendaAnimation = AgendaAnimation;
