// admin-drafts.jsx — "Drafts" tab in the admin dashboard.
// Surfaces the same approval / audit / rollback flow that lives on the public
// homepage, so admins who live in the dashboard can review without leaving.

function DraftsView({ session }) {
  const isReviewer = ATS.roleAtLeast(session.role, 'admin');
  const [tab, setTab] = React.useState(isReviewer ? 'queue' : 'mine'); // queue | mine | history
  const [drafts, setDrafts] = React.useState([]);
  const [audit, setAudit]   = React.useState([]);
  const [reason, setReason] = React.useState({});
  const [ready, setReady] = React.useState(false);

  React.useEffect(() => {
    Promise.all([
      ContentEdit.listAllDrafts(),
      ContentEdit.loadAudit(),
    ]).then(([d, a]) => {
      setDrafts(d);
      setAudit(a);
      setReady(true);
    }).catch(() => setReady(true));
    const a = ContentEdit.onDraftsChange(setDrafts);
    const b = ContentEdit.onAuditChange(setAudit);
    return () => { a(); b(); };
  }, []);

  if (!ready) return null;

  const queue   = drafts.filter((d) => d.status === 'pending' && d.submitted_at);
  const mine    = drafts.filter((d) => d.author_id === session.id);
  const rejected= drafts.filter((d) => d.status === 'rejected');

  const tabs = [
    isReviewer && { id: 'queue',   label: 'Review queue', count: queue.length },
    { id: 'mine',    label: 'My drafts',     count: mine.filter((d) => d.status === 'pending').length },
    { id: 'history', label: 'Audit log',     count: 0 },
  ].filter(Boolean);

  return (
    <div className="admin-content">
      <div className="admin-page-head">
        <div>
          <h2 style={{ marginBottom: 4 }}>Page content drafts</h2>
          <p style={{ color: 'var(--text-dim)', fontSize: '0.92rem' }}>
            {isReviewer
              ? 'Review homepage content changes from web admins. Approve to publish; reject with a note.'
              : 'Track the homepage content edits you\'ve submitted for review.'}
          </p>
        </div>
        <a className="btn btn-ghost btn-sm" href="index.html">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12s-4 8-9 8-9-8-9-8 4-8 9-8 9 8 9 8z" /><circle cx="12" cy="12" r="3" /></svg>
          View live site
        </a>
      </div>

      <div className="seg-toggle" style={{ marginBottom: 16 }}>
        {tabs.map((t) => (
          <button key={t.id} className={tab === t.id ? 'on' : ''} onClick={() => setTab(t.id)}>
            {t.label} {t.count > 0 && <span style={{ marginLeft: 6, opacity: 0.7 }}>· {t.count}</span>}
          </button>
        ))}
      </div>

      {tab === 'queue' && isReviewer && (
        <ReviewQueue
          queue={queue}
          rejected={rejected.slice(0, 8)}
          reason={reason}
          setReason={setReason}
          session={session}
        />
      )}

      {tab === 'mine' && <MyDrafts mine={mine} session={session} />}

      {tab === 'history' && <AuditLogView audit={audit} session={session} />}
    </div>
  );
}

function ReviewQueue({ queue, rejected, reason, setReason, session }) {
  const onApprove = (id) => {
    ContentEdit.approveDraft(id, session.id, reason[id] || null);
    setReason((r) => ({ ...r, [id]: '' }));
  };
  const onReject = (id) => {
    if (!reason[id]) {
      alert('Add a short note so the web admin knows why.');
      return;
    }
    ContentEdit.rejectDraft(id, session.id, reason[id]);
    setReason((r) => ({ ...r, [id]: '' }));
  };

  if (queue.length === 0 && rejected.length === 0) {
    return (
      <div className="empty-state glass">
        <div style={{ fontSize: '2.4rem' }}>✓</div>
        <h3 style={{ marginTop: 6 }}>Inbox zero</h3>
        <p style={{ color: 'var(--text-dim)' }}>No content drafts waiting on you.</p>
      </div>
    );
  }

  return (
    <>
      {queue.length > 0 && (
        <div className="approval-list" style={{ maxHeight: 'none' }}>
          {queue.map((d) => (
            <div key={d.id} className="approval-item pending">
              <div className="approval-item-head">
                <div>
                  <div className="approval-item-label">{d.label}</div>
                  <div className="approval-item-meta">
                    by <b>{d.author_name}</b> · submitted {ATS.fmtAgo(d.submitted_at || d.created_at)}
                    <span className="approval-item-key">· {d.field_key}</span>
                  </div>
                </div>
                <span className="approval-status pending">pending</span>
              </div>
              <DraftDiff prior={d.prior_value} next={d.value} fieldType={d.field_type} />
              <div className="approval-item-actions">
                <input
                  placeholder="Optional note for the web admin…"
                  value={reason[d.id] || ''}
                  onChange={(e) => setReason((r) => ({ ...r, [d.id]: e.target.value }))}
                />
                <button className="btn btn-ghost btn-sm" onClick={() => onReject(d.id)}>Reject</button>
                <button className="btn btn-primary btn-sm" onClick={() => onApprove(d.id)}>Approve &amp; publish</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {rejected.length > 0 && (
        <>
          <h3 style={{ marginTop: 28, marginBottom: 12, fontSize: '0.95rem', color: 'var(--text-dim)' }}>
            Recently rejected
          </h3>
          <div className="approval-list" style={{ maxHeight: 'none' }}>
            {rejected.map((d) => (
              <div key={d.id} className="approval-item rejected">
                <div className="approval-item-head">
                  <div>
                    <div className="approval-item-label">{d.label}</div>
                    <div className="approval-item-meta">
                      by <b>{d.author_name}</b> · rejected by <b>{d.reviewer_name}</b> · {ATS.fmtAgo(d.updated_at)}
                    </div>
                  </div>
                  <span className="approval-status rejected">rejected</span>
                </div>
                <DraftDiff prior={d.prior_value} next={d.value} fieldType={d.field_type} />
                {d.review_note && <div className="approval-note">Note: {d.review_note}</div>}
              </div>
            ))}
          </div>
        </>
      )}
    </>
  );
}

function MyDrafts({ mine, session }) {
  if (mine.length === 0) {
    return (
      <div className="empty-state glass">
        <h3>No drafts yet</h3>
        <p style={{ color: 'var(--text-dim)', marginTop: 6 }}>
          Open the <a href="index.html" style={{ color: 'var(--ice)' }}>live site</a>, click
          the user pill, and choose <b>Edit this page</b> to start editing inline.
        </p>
      </div>
    );
  }
  const pending = mine.filter((d) => d.status === 'pending');
  const unsubmitted = pending.filter((d) => !d.submitted_at);
  return (
    <>
      {unsubmitted.length > 0 && (
        <div className="info-banner" style={{ marginBottom: 14 }}>
          You have <b>{unsubmitted.length}</b> draft{unsubmitted.length === 1 ? '' : 's'} not yet submitted for review.
          <button className="btn btn-primary btn-sm" style={{ marginLeft: 'auto' }}
                  onClick={() => ContentEdit.submitDraftsForReview(session.id)}>
            Submit all for review
          </button>
        </div>
      )}
      <div className="approval-list" style={{ maxHeight: 'none' }}>
        {mine.map((d) => (
          <div key={d.id} className={'approval-item ' + d.status}>
            <div className="approval-item-head">
              <div>
                <div className="approval-item-label">{d.label}</div>
                <div className="approval-item-meta">
                  {d.submitted_at ? <>submitted {ATS.fmtAgo(d.submitted_at)}</> : <>created {ATS.fmtAgo(d.created_at)}</>}
                  <span className="approval-item-key">· {d.field_key}</span>
                </div>
              </div>
              <span className={'approval-status ' + d.status}>
                {d.status === 'pending' && !d.submitted_at ? 'draft' : d.status}
              </span>
            </div>
            <DraftDiff prior={d.prior_value} next={d.value} fieldType={d.field_type} />
            {d.review_note && (
              <div className={'approval-note ' + (d.status === 'approved' ? 'approved' : '')}>
                {d.status === 'approved' ? 'Approved' : 'Reviewer note'}: {d.review_note}
              </div>
            )}
            {d.status === 'pending' && (
              <div className="approval-item-actions">
                <button className="link-btn" onClick={() => {
                  if (confirm('Withdraw this draft?')) ContentEdit.withdrawDraft(d.id, session.id);
                }}>Withdraw</button>
              </div>
            )}
          </div>
        ))}
      </div>
    </>
  );
}

function AuditLogView({ audit, session }) {
  const isReviewer = ATS.roleAtLeast(session.role, 'admin');
  if (audit.length === 0) {
    return (
      <div className="empty-state glass">
        <h3>No history yet</h3>
        <p style={{ color: 'var(--text-dim)', marginTop: 6 }}>
          The audit log lists every approved, rejected, or rolled-back change.
        </p>
      </div>
    );
  }
  return (
    <div className="audit-list" style={{ maxHeight: 'none' }}>
      {audit.map((e) => (
        <div key={e.id} className={'audit-item ' + e.action}>
          <div className="audit-item-head">
            <div>
              <span className={'audit-action ' + e.action}>{e.action}</span>
              <span className="audit-label"> {e.label}</span>
              <span className="audit-key">· {e.field_key}</span>
            </div>
            <span className="audit-when">{ATS.fmtDate(e.created_at)}</span>
          </div>
          <div className="audit-meta">
            {e.action === 'approve' && <>by <b>{e.author_name}</b> · approved by <b>{e.reviewer_name}</b></>}
            {e.action === 'reject'  && <>by <b>{e.author_name}</b> · rejected by <b>{e.reviewer_name}</b></>}
            {e.action === 'rollback' && <>rolled back by <b>{e.reviewer_name}</b></>}
          </div>
          <DraftDiff prior={e.from_value} next={e.to_value} fieldType={e.field_type} />
          {e.review_note && <div className="audit-note">"{e.review_note}"</div>}
          {e.can_restore && isReviewer && (
            <div className="audit-actions">
              <button className="link-btn" onClick={() => {
                if (confirm(`Roll back "${e.label}" to its previous value? A new audit entry will be created.`)) {
                  ContentEdit.rollbackTo(e.id, session.id);
                }
              }}>Restore "before" version</button>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

// Shared diff renderer — same shape as the one in inline-editor.jsx, kept
// here so the admin shell doesn't need to pull in EditModeProvider.
function DraftDiff({ prior, next, fieldType }) {
  if (fieldType === 'image') {
    let p = null, n = null;
    try { p = prior ? JSON.parse(prior) : null; } catch {}
    try { n = next ? JSON.parse(next) : null; } catch {}
    return (
      <div className="draft-diff img">
        <div className="draft-diff-side">
          <div className="draft-diff-tag">before</div>
          {p?.src ? <img src={p.src} alt="" /> : <div className="draft-diff-empty">no image</div>}
        </div>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" style={{ opacity: 0.5, alignSelf: 'center' }}><path d="M5 12h14M13 5l7 7-7 7" /></svg>
        <div className="draft-diff-side">
          <div className="draft-diff-tag">after</div>
          {n?.src ? <img src={n.src} alt={n.alt || ''} /> : <div className="draft-diff-empty">no image</div>}
        </div>
      </div>
    );
  }
  return (
    <div className="draft-diff text">
      <div className="draft-diff-prior">{prior || <span style={{ color: 'var(--text-faint)' }}>(no published value)</span>}</div>
      <div className="draft-diff-next">{next}</div>
    </div>
  );
}

Object.assign(window, { DraftsView });
