// Florio Analytics — Notifications tab (ported from js/pages/notifications.js).
// Shows every notification variant (from the `notification_analytics` collection)
// as a styled card sorted by success rate, plus KPI tiles and a day-late filter.
// Rebuilt in the new design kit. All queries / metrics / interactions preserved.
(function () {
  const NS = window.HyperChartsDesignSystem_e51a95;
  const { Badge } = NS;
  const I = window.HyperIcons;
  const { useState, useEffect } = React;

  // formatNumber from the data layer (lazy — FlorioAPI may not be ready at def time).
  function fmt(n) { return (window.FlorioAPI && window.FlorioAPI.formatNumber) ? window.FlorioAPI.formatNumber(n) : String(n ?? 0); }

  // ── range-independent fetch cache (the page is NOT date-range based) ──
  const _cache = {};
  async function cached(key, fn, fallback) {
    if (key in _cache) return _cache[key];
    try { const v = await fn(); _cache[key] = v; return v; }
    catch (e) { console.error('[Notifications] ' + key + ' failed:', e); return fallback; }
  }

  const SORTS = [
    { key: 'rate', label: 'Success rate' },
    { key: 'sent', label: 'Most sent' },
    { key: 'success', label: 'Most watered' },
  ];
  const RANGES = [
    { key: 'all', label: 'All' },
    { key: 'day0', label: 'Day 0' },
    { key: 'day1-3', label: 'Day 1-3' },
    { key: 'day4+', label: 'Day 4+' },
  ];

  function rangeLabel(n) {
    if (n.minDaysLate === 0 && n.maxDaysLate === 0) return 'Day 0';
    if (n.minDaysLate === 1 && n.maxDaysLate === 3) return 'Day 1-3';
    if (n.minDaysLate >= 4) return 'Day 4+';
    return 'Day ' + n.minDaysLate + '-' + n.maxDaysLate;
  }
  function rangeBadgeColor(n) {
    if (n.minDaysLate >= 4) return '#FE7E07';   // accent
    if (n.minDaysLate >= 1) return '#2ACF56';   // green
    return 'var(--text-muted)';                 // muted
  }

  // iOS-style Florio app icon (carried over from the old page).
  function AppIcon() {
    return (
      <svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
        <rect width="28" height="28" rx="7" fill="#4E5D42" />
        <path d="M14 7c-2.5 0-4.5 1.8-4.5 4.2 0 1.4.7 2.6 1.8 3.4-.1.5-.3 1-.6 1.5-.2.3 0 .6.3.6.8-.1 1.6-.4 2.2-.9.3 0 .5.1.8.1 2.5 0 4.5-1.8 4.5-4.2S16.5 7.5 14 7z" fill="#8AAC6B" />
        <ellipse cx="14" cy="18.5" rx="4" ry="1.5" fill="#8AAC6B" opacity=".3" />
        <path d="M14 14v5" stroke="#8AAC6B" strokeWidth="1.2" strokeLinecap="round" />
        <path d="M12 17.5c1-.8 3-.8 4 0" stroke="#8AAC6B" strokeWidth="1" strokeLinecap="round" fill="none" />
      </svg>
    );
  }

  // One notification variant: iOS-style push bubble + delivery stats card.
  function NotifCard({ n }) {
    const hasSent = n.totalSent > 0;
    const rate = hasSent ? (n.successRate * 100).toFixed(1) : '--';
    const barWidth = hasSent ? Math.round(n.successRate * 100) : 0;
    const barColor = n.successRate >= 0.3 ? '#2ACF56' : '#FE7E07';
    const badgeColor = rangeBadgeColor(n);
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {/* push bubble */}
        <div style={{ background: 'var(--surface-sunken)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', padding: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span style={{ display: 'flex', flexShrink: 0 }}><AppIcon /></span>
            <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 12.5, letterSpacing: '.02em', textTransform: 'uppercase', color: 'var(--text-secondary)', flex: 1 }}>Florio</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--text-muted)' }}>now</span>
          </div>
          <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 14, color: 'var(--text-primary)', marginBottom: 3 }}>{n.title}</div>
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, lineHeight: 1.35, color: 'var(--text-secondary)' }}>{n.body}</div>
        </div>
        {/* stats card */}
        <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', padding: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
            {[
              { v: fmt(n.totalSent), l: 'sent', c: 'var(--text-primary)' },
              { v: fmt(n.totalSuccess), l: 'watered', c: '#2ACF56' },
              { v: rate + '%', l: 'rate', c: '#FE7E07' },
            ].map((s, i) => (
              <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, flex: 1 }}>
                <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 18, letterSpacing: '-.02em', color: s.c }}>{s.v}</span>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--text-muted)' }}>{s.l}</span>
              </div>
            ))}
          </div>
          <div style={{ height: 8, background: 'var(--surface-sunken)', borderRadius: 99, overflow: 'hidden' }}>
            <div style={{ width: barWidth + '%', height: '100%', borderRadius: 99, background: barColor }} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em', color: badgeColor, padding: '3px 8px', borderRadius: 99, background: 'color-mix(in srgb, ' + badgeColor + ' 14%, transparent)' }}>{rangeLabel(n)}</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{n.id}</span>
          </div>
        </div>
      </div>
    );
  }

  function Notifications({ range }) {
    const P = window.PA;
    const [notifs, setNotifs] = useState(null);
    const [sort, setSort] = useState('rate');
    const [dayRange, setDayRange] = useState('all');

    useEffect(() => {
      let alive = true;
      (async () => {
        await window.FlorioReady;
        const { db, collection, getDocs } = window.FlorioDB;
        // Data source: `notification_analytics` collection (global per-variant stats).
        const list = await cached('notifs', async () => {
          const snap = await getDocs(collection(db, 'notification_analytics'));
          const out = [];
          snap.forEach((doc) => {
            const data = doc.data();
            const totalSent = data.totalSent ?? 0;
            const totalSuccess = data.totalSuccess ?? 0;
            out.push({
              id: doc.id,
              title: data.title ?? doc.id,
              body: data.body ?? '',
              emotion: data.emotion ?? '',
              category: data.category ?? '',
              minDaysLate: data.minDaysLate ?? 0,
              maxDaysLate: data.maxDaysLate ?? 0,
              totalSent,
              totalSuccess,
              lastSentDate: data.lastSentDate ?? '',
              successRate: totalSent > 0 ? totalSuccess / totalSent : 0, // guard /0
            });
          });
          return out;
        }, []);
        if (!alive) return;
        setNotifs(list);
      })();
      return () => { alive = false; };
    }, []);

    // Loading spinner while data null.
    if (!notifs) {
      return <div style={{ display: 'grid', placeItems: 'center', minHeight: '60vh' }}><div className="pa-spin" style={{ width: 38, height: 38, borderRadius: '50%', border: '3px solid var(--border-default)', borderTopColor: 'var(--app-accent)' }} /></div>;
    }

    // ── KPI stats (all variants) ──
    const totalVariants = notifs.length;
    const totalSent = notifs.reduce((s, n) => s + n.totalSent, 0);
    const totalSuccess = notifs.reduce((s, n) => s + n.totalSuccess, 0);
    const avgRate = totalSent > 0 ? ((totalSuccess / totalSent) * 100).toFixed(1) : '0.0'; // guard /0

    // ── filter by day-late range ──
    let filtered;
    if (dayRange === 'day0') filtered = notifs.filter((n) => n.minDaysLate === 0 && n.maxDaysLate === 0);
    else if (dayRange === 'day1-3') filtered = notifs.filter((n) => n.minDaysLate === 1 && n.maxDaysLate === 3);
    else if (dayRange === 'day4+') filtered = notifs.filter((n) => n.minDaysLate >= 4);
    else filtered = notifs.slice();

    // ── sort ──
    if (sort === 'rate') filtered.sort((a, b) => b.successRate - a.successRate);
    else if (sort === 'sent') filtered.sort((a, b) => b.totalSent - a.totalSent);
    else if (sort === 'success') filtered.sort((a, b) => b.totalSuccess - a.totalSuccess);

    const Toggle = ({ options, value, onChange }) => (
      <div style={{ display: 'flex', gap: 4, background: 'var(--surface-sunken)', border: '1px solid var(--border-subtle)', borderRadius: 99, padding: 3 }}>
        {options.map((o) => {
          const active = o.key === value;
          return (
            <button key={o.key} onClick={() => onChange(o.key)} style={{
              padding: '6px 13px', borderRadius: 99, border: 'none', cursor: 'pointer',
              fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 12.5,
              background: active ? 'var(--surface-card)' : 'transparent',
              color: active ? 'var(--text-primary)' : 'var(--text-muted)',
              boxShadow: active ? 'var(--shadow-card)' : 'none',
            }}>{o.label}</button>
          );
        })}
      </div>
    );

    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, minmax(0,1fr))', gap: 20 }}>
        {/* KPI row — 4 stat tiles */}
        <div style={{ gridColumn: 'span 12', display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16 }}>
          <P.StatTile icon={I.bell({ size: 18 })} label="Notification variants" value={fmt(totalVariants)} accent="#2ACF56" />
          <P.StatTile icon={I.bell({ size: 18 })} label="Total sent" value={fmt(totalSent)} accent="#FE7E07" />
          <P.StatTile icon={I.leaf ? I.leaf({ size: 18 }) : I.heart({ size: 18 })} label="Total waterings" value={fmt(totalSuccess)} accent="#2ACF56" />
          <P.StatTile icon={I.target({ size: 18 })} label="Avg success rate" value={avgRate + '%'} accent="#5B8DEF" />
        </div>

        {/* Controls + variant grid */}
        <P.ChartCard
          title="Notification variants"
          eyebrow="Per-variant delivery & watering outcomes"
          span={12}
          action={
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
              <Toggle options={RANGES} value={dayRange} onChange={setDayRange} />
              <Toggle options={SORTS} value={sort} onChange={setSort} />
            </div>
          }
        >
          {filtered.length === 0 ? (
            <div style={{ minHeight: 160, display: 'grid', placeItems: 'center', textAlign: 'center', gap: 8, padding: 22 }}>
              <span style={{ color: 'var(--text-muted)', display: 'flex' }}>{I.bell({ size: 26 })}</span>
              <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 15, color: 'var(--text-secondary)' }}>No notification data yet</div>
              <div style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--text-muted)', maxWidth: 360 }}>Notification analytics will appear once the hourly function starts running.</div>
            </div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 18 }}>
              {filtered.map((n) => <NotifCard key={n.id} n={n} />)}
            </div>
          )}
        </P.ChartCard>
      </div>
    );
  }

  (window.FlorioTabs = window.FlorioTabs || {}).notifications = Notifications;
})();
