// Florio Analytics — Feedback tab (ported from js/pages/feedback.js).
// Lists in-app feedback from the `feedback` collection, split into Unread / Read.
// Each card can be toggled read/unread (writes `read` back to Firestore).
// Rebuilt in the new design kit. All queries / interactions preserved.
(function () {
  const NS = window.HyperChartsDesignSystem_e51a95;
  const I = window.HyperIcons;
  const { useState, useEffect, useCallback } = React;

  function fmt(n) { return (window.FlorioAPI && window.FlorioAPI.formatNumber) ? window.FlorioAPI.formatNumber(n) : String(n ?? 0); }

  function formatDate(item) {
    if (item.createdAt && typeof item.createdAt.toDate === 'function') {
      return item.createdAt.toDate().toLocaleDateString('en-GB', {
        day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit',
      });
    }
    return 'Unknown date';
  }

  function FeedbackCard({ item, isRead, onToggle, busy }) {
    return (
      <div style={{
        background: 'var(--surface-card)', border: '1px solid var(--border-subtle)',
        borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-card)', padding: 16,
        display: 'flex', flexDirection: 'column', gap: 10, opacity: isRead ? 0.7 : 1,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
          <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 13, color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.email || 'No email'}</span>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)', flexShrink: 0 }}>{formatDate(item)}</span>
        </div>
        <p style={{ fontFamily: 'var(--font-sans)', fontSize: 14, lineHeight: 1.45, color: 'var(--text-secondary)', margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{item.message}</p>
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <button disabled={busy} onClick={() => onToggle(item.id, !isRead)} style={{
            padding: '7px 13px', borderRadius: 'var(--radius-md)', cursor: busy ? 'default' : 'pointer',
            fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 12.5,
            border: '1px solid var(--border-default)',
            background: isRead ? 'var(--surface-card)' : 'var(--app-accent)',
            color: isRead ? 'var(--text-secondary)' : '#fff',
            opacity: busy ? 0.5 : 1,
          }}>{isRead ? 'Mark unread' : 'Mark read'}</button>
        </div>
      </div>
    );
  }

  function Feedback({ range }) {
    const P = window.PA;
    const [items, setItems] = useState(null);
    const [busyId, setBusyId] = useState(null);

    const load = useCallback(async () => {
      const { db, collection, query, orderBy, getDocs } = window.FlorioDB;
      // Data source: `feedback` collection, ordered by createdAt desc.
      const q = query(collection(db, 'feedback'), orderBy('createdAt', 'desc'));
      const snap = await getDocs(q);
      const out = [];
      snap.forEach((d) => out.push(Object.assign({ id: d.id }, d.data())));
      return out;
    }, []);

    useEffect(() => {
      let alive = true;
      (async () => {
        await window.FlorioReady;
        try {
          const out = await load();
          if (alive) setItems(out);
        } catch (e) {
          console.error('[Feedback] load failed:', e);
          if (alive) setItems([]);
        }
      })();
      return () => { alive = false; };
    }, [load]);

    // Toggle read state → write to Firestore, then update local list.
    const toggleRead = useCallback(async (id, markAsRead) => {
      const { db, doc, updateDoc } = window.FlorioDB;
      setBusyId(id);
      try {
        await updateDoc(doc(db, 'feedback', id), { read: markAsRead });
        setItems((cur) => (cur || []).map((it) => (it.id === id ? Object.assign({}, it, { read: markAsRead }) : it)));
      } catch (e) {
        console.error('[Feedback] toggle failed:', e);
        alert('Update failed: ' + e.message);
      } finally {
        setBusyId(null);
      }
    }, []);

    // Loading spinner while data null.
    if (!items) {
      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>;
    }

    const unread = items.filter((it) => !it.read);
    const read = items.filter((it) => it.read);

    const Empty = ({ note }) => (
      <div style={{ minHeight: 120, display: 'grid', placeItems: 'center', textAlign: 'center', gap: 8, padding: 22 }}>
        <span style={{ color: 'var(--text-muted)', display: 'flex' }}>{I.heart({ size: 24 })}</span>
        <span style={{ fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--text-muted)' }}>{note}</span>
      </div>
    );

    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, minmax(0,1fr))', gap: 20 }}>
        {/* KPI row */}
        <div style={{ gridColumn: 'span 12', display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16 }}>
          <P.StatTile icon={I.heart({ size: 18 })} label="Total feedback" value={fmt(items.length)} accent="#FF5C7A" />
          <P.StatTile icon={I.bell({ size: 18 })} label="Unread" value={fmt(unread.length)} accent="#FE7E07" />
          <P.StatTile icon={I.heart({ size: 18 })} label="Read" value={fmt(read.length)} accent="#2ACF56" />
        </div>

        <P.ChartCard title="Unread" eyebrow={'(' + unread.length + ') awaiting review'} span={6}>
          {unread.length === 0 ? <Empty note="No unread feedback" /> : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {unread.map((it) => <FeedbackCard key={it.id} item={it} isRead={false} onToggle={toggleRead} busy={busyId === it.id} />)}
            </div>
          )}
        </P.ChartCard>

        <P.ChartCard title="Read" eyebrow={'(' + read.length + ') resolved'} span={6}>
          {read.length === 0 ? <Empty note="No read feedback yet" /> : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {read.map((it) => <FeedbackCard key={it.id} item={it} isRead={true} onToggle={toggleRead} busy={busyId === it.id} />)}
            </div>
          )}
        </P.ChartCard>
      </div>
    );
  }

  (window.FlorioTabs = window.FlorioTabs || {}).feedback = Feedback;
})();
