// Feedback & suggestions — submit modal (all users) + monitor view (admin/owner).
// Schema:
//   feedback/{id}: { type, title, details, submittedBy{uid,name,role}, fromView,
//                    status, needsReplyFrom, createdAt, updatedAt, commentCount }
//   feedback/{id}/comments/{cid}: { authorUid, authorName, authorRole, body, createdAt }
const FB_TYPES = [
  { id: 'bug',        label: 'Bug',        color: 'var(--bad)',  hint: 'Something is broken or wrong.' },
  { id: 'suggestion', label: 'Suggestion', color: 'var(--brand-700)', hint: 'An idea to improve the app.' },
  { id: 'question',   label: 'Question',   color: 'var(--ink-600)', hint: 'Not sure how something works.' },
];
const FB_STATUSES = [
  { id: 'open',      label: 'Open',      color: 'var(--bad)' },
  { id: 'reviewing', label: 'Reviewing', color: 'var(--warn)' },
  { id: 'planned',   label: 'Planned',   color: 'var(--brand-700)' },
  { id: 'done',      label: 'Done',      color: 'var(--good)' },
  { id: 'wont-do',   label: "Won't do",  color: 'var(--ink-500)' },
];

function FeedbackButton({ collapsed, onClick }) {
  return (
    <button onClick={onClick} title="Send feedback" style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: collapsed ? '9px' : '9px 12px',
      justifyContent: collapsed ? 'center' : 'flex-start',
      background: 'var(--card-alt, #f5f7f8)',
      border: '1px solid var(--line-strong)',
      color: 'var(--ink-700)', borderRadius: 9, fontSize: 12.5,
      fontWeight: 600, cursor: 'pointer', width: '100%',
    }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
        strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M3 11a8 8 0 0 1 16 0v3l2 4H5l-2-4z"/>
        <path d="M9 18a3 3 0 0 0 6 0"/>
      </svg>
      {!collapsed && <span>Send feedback</span>}
    </button>
  );
}

function FeedbackModal({ open, onClose, authUser, fromView }) {
  const [type, setType] = React.useState('suggestion');
  const [title, setTitle] = React.useState('');
  const [details, setDetails] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [err, setErr] = React.useState(null);

  React.useEffect(() => {
    if (open) { setType('suggestion'); setTitle(''); setDetails(''); setDone(false); setErr(null); }
  }, [open]);

  if (!open) return null;

  const submit = async (e) => {
    e.preventDefault();
    if (!title.trim()) { setErr('Add a short summary.'); return; }
    setBusy(true); setErr(null);
    try {
      const db = firebase.firestore();
      const u = firebase.auth().currentUser;
      if (!u) throw new Error('Not signed in.');
      await db.collection('feedback').add({
        type,
        title: title.trim(),
        details: details.trim(),
        submittedBy: {
          uid: u.uid,
          name: authUser?.name || u.email || 'Unknown',
          role: authUser?.role || 'member',
        },
        fromView: fromView || null,
        status: 'open',
        needsReplyFrom: null,
        commentCount: 0,
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
        updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
      setDone(true);
      setTimeout(onClose, 1200);
    } catch (e) {
      setErr(e.message || 'Could not send feedback.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,32,0.42)',
      zIndex: 10000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }}>
      <form onClick={(e) => e.stopPropagation()} onSubmit={submit} style={{
        width: 'min(520px, 100%)', background: 'var(--card)', borderRadius: 14,
        boxShadow: '0 20px 60px rgba(0,0,0,0.25)', padding: 22,
        display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--ink-900)', letterSpacing: -0.01 }}>
              Send feedback
            </div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-500)', marginTop: 3 }}>
              Goes to Dave & Olie. They'll triage and reply if needed.
            </div>
          </div>
          <button type="button" onClick={onClose} style={{
            background: 'none', border: 'none', color: 'var(--ink-500)', cursor: 'pointer', padding: 4,
          }}><Icon.close/></button>
        </div>

        {done ? (
          <div style={{
            padding: 14, borderRadius: 10, fontSize: 13, fontWeight: 600,
            background: 'var(--good-bg, #E6F4EA)', color: 'var(--good, #1B9A4B)',
          }}>Thanks — feedback sent.</div>
        ) : (
          <>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-500)',
                letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 6 }}>Type</div>
              <div style={{ display: 'flex', gap: 8 }}>
                {FB_TYPES.map(t => {
                  const active = t.id === type;
                  return (
                    <button key={t.id} type="button" onClick={() => setType(t.id)} style={{
                      flex: 1, padding: '8px 10px', borderRadius: 9,
                      border: '1px solid ' + (active ? t.color : 'var(--line-strong)'),
                      background: active ? t.color : 'var(--card)',
                      color: active ? '#fff' : 'var(--ink-700)',
                      fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
                    }}>{t.label}</button>
                  );
                })}
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-500)', marginTop: 6 }}>
                {FB_TYPES.find(t => t.id === type)?.hint}
              </div>
            </div>

            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-500)',
                letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 6 }}>Summary</div>
              <input value={title} onChange={(e) => setTitle(e.target.value)}
                placeholder="One-line summary" maxLength={140}
                style={{ width: '100%', padding: '9px 11px', fontSize: 13.5,
                  border: '1px solid var(--line-strong)', borderRadius: 9,
                  background: 'var(--card)', color: 'var(--ink-900)', fontFamily: 'inherit' }}/>
            </div>

            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-500)',
                letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 6 }}>Details (optional)</div>
              <textarea value={details} onChange={(e) => setDetails(e.target.value)}
                placeholder="Steps, context, screenshots URL, anything that helps."
                rows={5} maxLength={2000}
                style={{ width: '100%', padding: '9px 11px', fontSize: 13,
                  border: '1px solid var(--line-strong)', borderRadius: 9, resize: 'vertical',
                  background: 'var(--card)', color: 'var(--ink-900)', fontFamily: 'inherit', lineHeight: 1.45 }}/>
            </div>

            {fromView && (
              <div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>
                Submitted from screen: <strong style={{ color: 'var(--ink-700)' }}>{fromView}</strong>
              </div>
            )}

            {err && (
              <div style={{ padding: '9px 11px', borderRadius: 9, fontSize: 12.5,
                background: 'var(--bad-bg, #fee2e2)', color: 'var(--bad)' }}>{err}</div>
            )}

            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
              <button type="button" onClick={onClose} disabled={busy} style={{
                padding: '9px 14px', borderRadius: 9,
                border: '1px solid var(--line-strong)', background: 'var(--card)',
                fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', cursor: 'pointer',
              }}>Cancel</button>
              <button type="submit" disabled={busy || !title.trim()} style={{
                padding: '9px 16px', borderRadius: 9, border: 'none',
                background: 'linear-gradient(135deg, var(--brand-700), var(--brand-500))',
                color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
                opacity: (busy || !title.trim()) ? 0.6 : 1,
              }}>{busy ? 'Sending…' : 'Send feedback'}</button>
            </div>
          </>
        )}
      </form>
    </div>
  );
}

// ─── Monitor (admin/owner only) ──────────────────────────────────────────
function FeedbackMonitor({ authUser }) {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState(null);
  const [filter, setFilter] = React.useState('all');
  const [openId, setOpenId] = React.useState(null);

  React.useEffect(() => {
    const db = firebase.firestore();
    const unsub = db.collection('feedback')
      .orderBy('createdAt', 'desc')
      .onSnapshot(
        (snap) => {
          setItems(snap.docs.map(d => ({ id: d.id, ...d.data() })));
          setLoading(false);
        },
        (e) => { setErr(e.message); setLoading(false); }
      );
    return () => unsub();
  }, []);

  const myRole = authUser?.role; // 'admin' | 'owner'
  const counts = React.useMemo(() => {
    const c = { all: items.length, open: 0, reviewing: 0, planned: 0, done: 0, 'wont-do': 0, awaitingMe: 0 };
    items.forEach(i => {
      c[i.status] = (c[i.status] || 0) + 1;
      if (i.needsReplyFrom && i.needsReplyFrom === myRole) c.awaitingMe++;
    });
    return c;
  }, [items, myRole]);

  const filtered = items.filter(i => {
    if (filter === 'all') return true;
    if (filter === 'awaitingMe') return i.needsReplyFrom === myRole;
    return i.status === filter;
  });

  const tabs = [
    { id: 'all', label: 'All' },
    { id: 'awaitingMe', label: 'Awaiting you', badge: counts.awaitingMe || null, accent: true },
    { id: 'open', label: 'Open' },
    { id: 'reviewing', label: 'Reviewing' },
    { id: 'planned', label: 'Planned' },
    { id: 'done', label: 'Done' },
    { id: 'wont-do', label: "Won't do" },
  ];

  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 14, maxWidth: 980 }}>
      <div>
        <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--ink-900)', letterSpacing: -0.01 }}>Feedback</div>
        <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: 4 }}>
          Bug reports, suggestions, and questions from the team. Reply, change status, or flag for the other admin.
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {tabs.map(t => {
          const active = filter === t.id;
          const count = t.id === 'all' ? counts.all
                      : t.id === 'awaitingMe' ? counts.awaitingMe
                      : counts[t.id];
          return (
            <button key={t.id} onClick={() => setFilter(t.id)} style={{
              padding: '7px 12px', borderRadius: 99, fontSize: 12.5, fontWeight: 600,
              border: '1px solid ' + (active ? 'var(--brand-700)' : 'var(--line-strong)'),
              background: active ? 'var(--brand-700)' : 'var(--card)',
              color: active ? '#fff' : (t.accent && count ? 'var(--warn, #d97706)' : 'var(--ink-700)'),
              cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
            }}>
              {t.label}
              {count > 0 && (
                <span style={{
                  fontSize: 11, padding: '0 6px', borderRadius: 99, fontWeight: 700,
                  background: active ? 'rgba(255,255,255,0.22)' : (t.accent ? 'var(--warn, #d97706)' : 'var(--ink-100)'),
                  color: active ? '#fff' : (t.accent ? '#fff' : 'var(--ink-700)'),
                }}>{count}</span>
              )}
            </button>
          );
        })}
      </div>

      {err && (
        <div style={{ padding: '9px 12px', borderRadius: 9, fontSize: 12.5,
          background: 'var(--bad-bg, #fee2e2)', color: 'var(--bad)' }}>{err}</div>
      )}

      {loading && <div style={{ fontSize: 13, color: 'var(--ink-500)' }}>Loading…</div>}

      {!loading && filtered.length === 0 && (
        <div style={{ padding: 28, border: '1px dashed var(--line-strong)', borderRadius: 12,
          textAlign: 'center', fontSize: 13, color: 'var(--ink-500)' }}>
          No feedback in this view.
        </div>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {filtered.map(item => (
          <FeedbackRow
            key={item.id}
            item={item}
            authUser={authUser}
            isOpen={openId === item.id}
            onToggle={() => setOpenId(openId === item.id ? null : item.id)}
          />
        ))}
      </div>
    </div>
  );
}

function FeedbackRow({ item, authUser, isOpen, onToggle }) {
  const t = FB_TYPES.find(x => x.id === item.type) || FB_TYPES[1];
  const s = FB_STATUSES.find(x => x.id === item.status) || FB_STATUSES[0];
  const created = item.createdAt?.toDate ? item.createdAt.toDate() : null;
  const awaitingMe = item.needsReplyFrom && item.needsReplyFrom === authUser?.role;

  return (
    <div className="card" style={{
      padding: 0, overflow: 'hidden',
      borderLeft: '3px solid ' + t.color,
      background: awaitingMe ? 'var(--warn-bg, #fef3c7)' : 'var(--card)',
    }}>
      <button onClick={onToggle} style={{
        width: '100%', padding: '14px 16px', background: 'transparent', border: 'none',
        textAlign: 'left', cursor: 'pointer',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <span style={{
          fontSize: 10.5, fontWeight: 700, padding: '2px 8px', borderRadius: 99,
          background: t.color + '22', color: t.color, letterSpacing: 0.04, textTransform: 'uppercase',
        }}>{t.label}</span>
        <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-900)', flex: 1, minWidth: 0,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.title}</span>
        {awaitingMe && (
          <span style={{ fontSize: 10.5, fontWeight: 700, padding: '2px 8px', borderRadius: 99,
            background: 'var(--warn, #d97706)', color: '#fff', letterSpacing: 0.04, textTransform: 'uppercase' }}>
            Awaiting you
          </span>
        )}
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5,
          fontSize: 11, color: s.color, fontWeight: 600 }}>
          <span className="dot" style={{ background: s.color, width: 7, height: 7 }}/>
          {s.label}
        </span>
        <span style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>
          {item.submittedBy?.name?.split(' ')[0] || '—'} · {fmtDate(created)}
        </span>
        {item.commentCount > 0 && (
          <span style={{ fontSize: 11, padding: '1px 7px', borderRadius: 99,
            background: 'var(--ink-100)', color: 'var(--ink-700)', fontWeight: 600 }}>
            {item.commentCount} 💬
          </span>
        )}
      </button>
      {isOpen && <FeedbackDetail item={item} authUser={authUser}/>}
    </div>
  );
}

function FeedbackDetail({ item, authUser }) {
  const [comments, setComments] = React.useState([]);
  const [reply, setReply] = React.useState('');
  const [needsReply, setNeedsReply] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  React.useEffect(() => {
    const db = firebase.firestore();
    const unsub = db.collection('feedback').doc(item.id)
      .collection('comments').orderBy('createdAt', 'asc')
      .onSnapshot(
        (snap) => setComments(snap.docs.map(d => ({ id: d.id, ...d.data() }))),
        (e) => setErr(e.message)
      );
    return () => unsub();
  }, [item.id]);

  const otherRole = authUser?.role === 'admin' ? 'owner' : 'admin';
  const otherLabel = otherRole === 'admin' ? 'Dave' : 'Olie';

  const setStatus = async (status) => {
    try {
      await firebase.firestore().collection('feedback').doc(item.id).update({
        status,
        updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
    } catch (e) { setErr(e.message); }
  };

  const postComment = async (e) => {
    e.preventDefault();
    if (!reply.trim()) return;
    setBusy(true); setErr(null);
    try {
      const db = firebase.firestore();
      const u = firebase.auth().currentUser;
      const docRef = db.collection('feedback').doc(item.id);
      await docRef.collection('comments').add({
        authorUid: u.uid,
        authorName: authUser?.name || u.email,
        authorRole: authUser?.role,
        body: reply.trim(),
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
      await docRef.update({
        needsReplyFrom: needsReply ? otherRole : null,
        commentCount: firebase.firestore.FieldValue.increment(1),
        updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
      setReply(''); setNeedsReply(false);
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const clearAwaiting = async () => {
    try {
      await firebase.firestore().collection('feedback').doc(item.id).update({
        needsReplyFrom: null,
        updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
    } catch (e) { setErr(e.message); }
  };

  return (
    <div style={{ padding: '0 16px 16px', borderTop: '1px solid var(--line)' }}>
      {item.details && (
        <div style={{
          margin: '12px 0', padding: 12, background: 'var(--ink-50)', borderRadius: 9,
          fontSize: 13, color: 'var(--ink-700)', lineHeight: 1.5, whiteSpace: 'pre-wrap',
        }}>{item.details}</div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', margin: '10px 0' }}>
        <span style={{ fontSize: 11, color: 'var(--ink-500)', fontWeight: 600,
          textTransform: 'uppercase', letterSpacing: 0.06 }}>Status:</span>
        {FB_STATUSES.map(s => {
          const active = item.status === s.id;
          return (
            <button key={s.id} onClick={() => setStatus(s.id)} style={{
              padding: '5px 10px', borderRadius: 99, fontSize: 11.5, fontWeight: 600,
              border: '1px solid ' + (active ? s.color : 'var(--line-strong)'),
              background: active ? s.color : 'var(--card)',
              color: active ? '#fff' : 'var(--ink-700)', cursor: 'pointer',
            }}>{s.label}</button>
          );
        })}
        {item.needsReplyFrom && (
          <button onClick={clearAwaiting} style={{
            marginLeft: 'auto', padding: '5px 10px', borderRadius: 99, fontSize: 11.5, fontWeight: 600,
            border: '1px solid var(--line-strong)', background: 'var(--card)', color: 'var(--ink-700)', cursor: 'pointer',
          }}>Clear "awaiting {item.needsReplyFrom === 'admin' ? 'Dave' : 'Olie'}"</button>
        )}
      </div>

      {comments.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, margin: '10px 0 14px' }}>
          {comments.map(c => (
            <div key={c.id} style={{
              padding: 10, background: 'var(--card-alt, #f5f7f8)', borderRadius: 9,
              fontSize: 13, color: 'var(--ink-800)', lineHeight: 1.5,
            }}>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-600)', marginBottom: 3 }}>
                {c.authorName} <span style={{ color: 'var(--ink-400)', fontWeight: 500 }}>·
                  {c.authorRole === 'admin' ? ' Admin' : c.authorRole === 'owner' ? ' Owner' : ' Member'}
                  {' · '}{fmtDate(c.createdAt?.toDate?.())}</span>
              </div>
              <div style={{ whiteSpace: 'pre-wrap' }}>{c.body}</div>
            </div>
          ))}
        </div>
      )}

      <form onSubmit={postComment} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <textarea value={reply} onChange={(e) => setReply(e.target.value)}
          placeholder={'Reply as ' + (authUser?.name || 'admin') + '…'} rows={2}
          style={{ width: '100%', padding: '9px 11px', fontSize: 13,
            border: '1px solid var(--line-strong)', borderRadius: 9, resize: 'vertical',
            background: 'var(--card)', color: 'var(--ink-900)', fontFamily: 'inherit', lineHeight: 1.45 }}/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: 6,
            fontSize: 12, color: 'var(--ink-700)', cursor: 'pointer' }}>
            <input type="checkbox" checked={needsReply} onChange={(e) => setNeedsReply(e.target.checked)}/>
            Needs reply from {otherLabel}
          </label>
          <span style={{ flex: 1 }}/>
          {err && <span style={{ fontSize: 12, color: 'var(--bad)' }}>{err}</span>}
          <button type="submit" disabled={busy || !reply.trim()} style={{
            padding: '8px 14px', borderRadius: 9, border: 'none',
            background: 'linear-gradient(135deg, var(--brand-700), var(--brand-500))',
            color: '#fff', fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
            opacity: (busy || !reply.trim()) ? 0.6 : 1,
          }}>{busy ? 'Posting…' : 'Post comment'}</button>
        </div>
      </form>
    </div>
  );
}

function fmtDate(d) {
  if (!d) return '—';
  const now = new Date();
  const sameDay = d.toDateString() === now.toDateString();
  if (sameDay) return d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
  return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
}

Object.assign(window, { FeedbackButton, FeedbackModal, FeedbackMonitor });
