// admin-applications.jsx — Admin tab listing teachers whose application is
// IN ANY pre-approval state: draft (still in the wizard), pending_review
// (submitted, awaiting decision), or rejected (decided no).
//
// Backed by admin_list_pending_applications() RPC (v74). The v74 rewrite
// of v68 widens the filter to include draft rows so admin can see every
// teacher from the moment they enter their email, surface a 6-step
// progress strip, and send a follow-up "finish your application" nudge
// directly from each draft row.
//
// Sort: pending_review first (actionable), drafts second (nudgeable),
// rejected last (historical). Within each bucket, newest signup first.

const AA_MUTED = 'oklch(50% 0.03 265)';
const AA_INK   = 'oklch(22% 0.06 265)';

// Status -> pill colour. v74 returns one of: 'pending_review', 'rejected',
// 'draft', or 'in_progress' (legacy review_status value used by some rows
// where progress.review_status was set but profile_status still 'draft').
// 'in_progress' is treated identically to 'draft' visually.
const AAStatusPill = ({ status, currentStep }) => {
  const conf = {
    pending_review: { bg: 'oklch(94% 0.07 250)', fg: 'oklch(35% 0.16 250)', label: 'Awaiting review' },
    rejected:       { bg: 'oklch(95% 0.06 25)',  fg: 'oklch(40% 0.15 25)',  label: 'Rejected' },
    draft:          { bg: 'oklch(95% 0.09 80)',  fg: 'oklch(40% 0.16 80)',  label: `Started — Step ${currentStep || 1}` },
    in_progress:    { bg: 'oklch(95% 0.09 80)',  fg: 'oklch(40% 0.16 80)',  label: `Started — Step ${currentStep || 1}` },
  }[status] || { bg: 'oklch(96% 0.01 265)', fg: AA_MUTED, label: status };
  return (
    <span style={{
      display: 'inline-block', padding: '4px 10px', borderRadius: 14, fontSize: 11, fontWeight: 700,
      background: conf.bg, color: conf.fg, textTransform: 'uppercase', letterSpacing: '0.04em',
    }}>{conf.label}</span>
  );
};

const AAFormatRel = (ts) => {
  if (!ts) return '—';
  const d = new Date(ts);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 60) return 'just now';
  if (diff < 3600) return `${Math.round(diff / 60)} min ago`;
  if (diff < 86400) return `${Math.round(diff / 3600)} h ago`;
  return `${Math.round(diff / 86400)} d ago`;
};

const AA_STEPS = [
  { k: 'step_subjects',     label: 'Subjects'      },
  { k: 'step_how_it_works', label: 'How it works'  },
  { k: 'step_basic_info',   label: 'Basic info'    },
  { k: 'step_profile',      label: 'Personalize'   },
  { k: 'step_agreement',    label: 'Terms'         },
  { k: 'step_submitted',    label: 'Submitted'     },
];

const AAStepChips = ({ row }) => (
  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
    {AA_STEPS.map((s) => {
      const done = !!row[s.k];
      return (
        <span key={s.k} title={s.label} style={{
          display: 'inline-flex', alignItems: 'center', gap: 5,
          padding: '3px 9px', borderRadius: 11, fontSize: 10.5, fontWeight: 600,
          background: done ? 'oklch(94% 0.07 145)' : 'oklch(96% 0.01 265)',
          color:      done ? 'oklch(35% 0.15 145)' : AA_MUTED,
          border: done ? '1px solid oklch(86% 0.10 145)' : '1px solid oklch(91% 0.02 265)',
          textTransform: 'uppercase', letterSpacing: '0.03em',
        }}>
          <span style={{
            display: 'inline-block', width: 6, height: 6, borderRadius: '50%',
            background: done ? 'oklch(55% 0.18 145)' : 'oklch(78% 0.02 265)',
          }}/>
          {s.label}
        </span>
      );
    })}
  </div>
);

const AA_BASIC_INFO_FIELDS = [
  { k:'rate',                  label:'Hourly rate' },
  { k:'address_city',          label:'City' },
  { k:'address_state',         label:'State' },
  { k:'address_line1',         label:'Address line 1' },
  { k:'address_zip',           label:'ZIP code' },
  { k:'phone',                 label:'Phone' },
  { k:'gender',                label:'Gender' },
  { k:'time_zone',             label:'Time zone' },
  { k:'cancellation_notice',   label:'Cancellation notice' },
  { k:'undergrad_college',     label:'Undergrad college' },
  { k:'undergrad_major',       label:'Undergrad major' },
  { k:'grad_college_1',        label:'Grad college 1' },
  { k:'grad_degree_1',         label:'Grad degree 1' },
  { k:'teaching_certification',label:'Teaching certification' },
  { k:'privacy_radius_miles',  label:'Privacy radius' },
  { k:'travel_radius_miles',   label:'Travel radius' },
  { k:'modality',              label:'Online / In-person' },
];

const AA_NUDGE_DEFAULT_SUBJECT = 'Finish your tutor application — we saved your progress';
const AA_NUDGE_DEFAULT_BODY = (firstName) => (
  '<div style="font-family:system-ui,-apple-system,sans-serif;max-width:560px;margin:0 auto;padding:24px;color:#1a1d24">'
+ '<h2 style="margin:0 0 12px;font-family:Georgia,serif;font-weight:600;font-size:22px">Hey ' + (firstName || 'there') + ' — want a hand finishing your application?</h2>'
+ '<p style="font-size:15px;line-height:1.6;margin:0 0 14px">I saw you started signing up to teach with us and didn\'t quite finish. Your progress is saved — you can pick up exactly where you left off.</p>'
+ '<p style="margin:24px 0;text-align:center">'
+ '<a href="https://coachingforall.co/?page=become-instructor" style="display:inline-block;padding:12px 24px;background:#1a1d24;color:#fff;text-decoration:none;border-radius:8px;font-weight:600">Finish your application →</a></p>'
+ '<p style="font-size:15px;line-height:1.6;margin:0 0 14px">If anything in the form is unclear or there\'s a reason you stopped, just reply to this email — I read every one personally.</p>'
+ '<p style="font-size:13px;color:#5a606f;margin:24px 0 0">Joe · hello@coachingforall.co</p>'
+ '</div>'
);

// Modal for sending a "finish your application" nudge to a draft teacher.
const AANudgeModal = ({ row, onClose, onSent }) => {
  const firstName = (row.full_name || '').split(' ')[0] || '';
  const [subject, setSubject] = React.useState(AA_NUDGE_DEFAULT_SUBJECT);
  const [body,    setBody]    = React.useState(AA_NUDGE_DEFAULT_BODY(firstName));
  const [sending, setSending] = React.useState(false);
  const [error,   setError]   = React.useState(null);

  const send = async () => {
    setSending(true); setError(null);
    try {
      const { error: e } = await window.supa.rpc('admin_send_followup_email', {
        p_instructor_id: row.instructor_id, p_subject: subject, p_html: body,
      });
      if (e) throw e;
      onSent && onSent();
      onClose && onClose();
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not send') : (e.message || String(e)));
      setSending(false);
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', zIndex: 1000,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: '#fff', borderRadius: 14, padding: 24, maxWidth: 640, width: '100%',
        maxHeight: '90vh', overflow: 'auto', fontFamily: "'Plus Jakarta Sans', sans-serif",
      }}>
        <div style={{ marginBottom: 16 }}>
          <h3 style={{ margin: 0, fontFamily: "'Cormorant Garamond', serif", fontWeight: 700, fontSize: 22, color: AA_INK }}>
            Send nudge to {row.full_name || row.email}
          </h3>
          <div style={{ fontSize: 13, color: AA_MUTED, marginTop: 4 }}>
            Going to {row.email}
          </div>
        </div>

        <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: AA_INK, marginBottom: 6 }}>Subject</label>
        <input value={subject} onChange={(e) => setSubject(e.target.value)} style={{
          width: '100%', padding: '10px 12px', fontSize: 14, borderRadius: 8,
          border: '1px solid oklch(88% 0.02 265)', marginBottom: 14, boxSizing: 'border-box',
        }}/>

        <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: AA_INK, marginBottom: 6 }}>Email body (HTML)</label>
        <textarea value={body} onChange={(e) => setBody(e.target.value)} rows={12} style={{
          width: '100%', padding: '10px 12px', fontSize: 13, fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
          borderRadius: 8, border: '1px solid oklch(88% 0.02 265)', resize: 'vertical', boxSizing: 'border-box',
        }}/>

        {error && (
          <div style={{ background: 'oklch(96% 0.03 25)', color: 'oklch(40% 0.15 25)',
            padding: '10px 14px', borderRadius: 8, fontSize: 13, marginTop: 12,
            border: '1px solid oklch(88% 0.06 25)' }}>{error}</div>
        )}

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 18 }}>
          <button onClick={onClose} disabled={sending} style={{
            background: '#fff', color: AA_INK, border: '1.5px solid oklch(85% 0.02 265)',
            borderRadius: 8, padding: '9px 18px', fontWeight: 600, fontSize: 13,
            cursor: sending ? 'wait' : 'pointer',
          }}>Cancel</button>
          <button onClick={send} disabled={sending || !subject.trim() || !body.trim()} style={{
            background: 'oklch(35% 0.12 265)', color: '#fff', border: 'none', borderRadius: 8,
            padding: '9px 20px', fontWeight: 700, fontSize: 13,
            cursor: sending ? 'wait' : 'pointer', opacity: (sending || !subject.trim() || !body.trim()) ? 0.6 : 1,
          }}>{sending ? 'Sending…' : 'Send nudge'}</button>
        </div>
      </div>
    </div>
  );
};

const AdminApplications = () => {
  const isMobile = window.useIsMobile();
  const [rows, setRows] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [openInstr, setOpenInstr] = React.useState(null);
  const [nudgeRow, setNudgeRow]   = React.useState(null);
  const [nudgeSentFor, setNudgeSentFor] = React.useState(null);
  const [showSettings, setShowSettings] = React.useState(false);
  const [requiredFields, setRequiredFields] = React.useState([]);
  const [savingSettings, setSavingSettings] = React.useState(false);

  const load = React.useCallback(async () => {
    setLoading(true); setError(null);
    try {
      const { data, error: e } = await window.supa.rpc('admin_list_pending_applications');
      if (e) throw e;
      setRows(data || []);
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not load applications') : (e.message || String(e)));
      setRows([]);
    } finally { setLoading(false); }
  }, []);

  const loadSettings = React.useCallback(async () => {
    const { data } = await window.supa.from('signup_config').select('payload').eq('key', 'step.basic_info').maybeSingle();
    const req = (data && data.payload && data.payload.required_fields) || [];
    setRequiredFields(req);
  }, []);

  const toggleRequired = (k) => {
    setRequiredFields(prev => prev.includes(k) ? prev.filter(x => x !== k) : [...prev, k]);
  };

  const saveSettings = async () => {
    setSavingSettings(true); setError(null);
    try {
      const { error: e } = await window.supa.rpc('admin_update_required_fields', {
        p_step: 'step.basic_info', p_required: requiredFields,
      });
      if (e) throw e;
      setShowSettings(false);
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not save settings') : e.message);
    } finally { setSavingSettings(false); }
  };

  React.useEffect(() => {
    load();
    loadSettings();
    const t = setInterval(load, 60_000);
    return () => clearInterval(t);
  }, [load, loadSettings]);

  const isDraftRow = (r) => r.review_status === 'draft' || r.review_status === 'in_progress';

  const pendingCount  = rows.filter(r => r.review_status === 'pending_review').length;
  const draftCount    = rows.filter(isDraftRow).length;
  const rejectedCount = rows.filter(r => r.review_status === 'rejected').length;

  if (loading) return <div style={{ padding: 24, color: AA_MUTED }}>Loading applications…</div>;

  return (
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: isMobile ? '14px 14px 80px' : '24px 28px 80px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <h2 style={{ fontFamily: "'Cormorant Garamond', serif", fontWeight: 700, fontSize: 26, color: AA_INK, margin: 0 }}>Applications</h2>
          <div style={{ fontSize: 13, color: AA_MUTED, marginTop: 4 }}>
            {pendingCount} pending · {draftCount} in progress · {rejectedCount} rejected
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={() => setShowSettings(s => !s)} style={{
            background: '#fff', color: AA_INK, border: '1px solid oklch(88% 0.02 265)',
            borderRadius: 8, padding: '8px 14px', fontSize: 13, fontWeight: 600, cursor: 'pointer',
          }}>{showSettings ? 'Hide settings' : 'Required fields'}</button>
          <button onClick={load} style={{
            background: '#fff', color: AA_INK, border: '1px solid oklch(88% 0.02 265)',
            borderRadius: 8, padding: '8px 14px', fontSize: 13, fontWeight: 600, cursor: 'pointer',
          }}>Refresh</button>
        </div>
      </div>

      {showSettings && (
        <div style={{ background:'#fff', border:'1px solid oklch(94% 0.01 265)', borderRadius:12, padding: isMobile ? 14 : 18, marginBottom: 18 }}>
          <div style={{ fontSize:13, fontWeight:700, color: AA_INK, marginBottom:8 }}>Which basic-info fields are required?</div>
          <div style={{ fontSize:12, color: AA_MUTED, marginBottom:12 }}>
            Teachers must fill these in to advance past step 3. Toggle to change.
          </div>
          <div style={{ display:'flex', flexWrap:'wrap', gap:8, marginBottom:14 }}>
            {AA_BASIC_INFO_FIELDS.map(f => {
              const on = requiredFields.includes(f.k);
              return (
                <button key={f.k} onClick={() => toggleRequired(f.k)} style={{
                  padding: '6px 12px', borderRadius: 14, fontSize: 12, fontWeight: 600,
                  border: on ? '1.5px solid oklch(45% 0.13 265)' : '1.5px solid oklch(88% 0.02 265)',
                  background: on ? 'oklch(45% 0.13 265)' : '#fff',
                  color: on ? '#fff' : 'oklch(40% 0.04 265)',
                  cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif",
                }}>{on ? '✓ ' : ''}{f.label}</button>
              );
            })}
          </div>
          <div style={{ display:'flex', justifyContent:'flex-end', gap:8 }}>
            <button onClick={() => { loadSettings(); setShowSettings(false); }} style={{
              background: '#fff', color: AA_INK, border: '1.5px solid oklch(85% 0.02 265)',
              borderRadius: 8, padding: '8px 16px', fontWeight: 600, fontSize: 13, cursor: 'pointer',
            }}>Cancel</button>
            <button onClick={saveSettings} disabled={savingSettings} style={{
              background: 'oklch(35% 0.12 265)', color: '#fff', border: 'none', borderRadius: 8,
              padding: '8px 18px', fontWeight: 700, fontSize: 13, cursor: savingSettings ? 'wait' : 'pointer',
            }}>{savingSettings ? 'Saving…' : 'Save'}</button>
          </div>
        </div>
      )}

      {error && (
        <div style={{ background: 'oklch(96% 0.03 25)', color: 'oklch(40% 0.15 25)',
          padding: '12px 16px', borderRadius: 8, fontSize: 14, marginBottom: 16,
          border: '1px solid oklch(88% 0.06 25)' }}>{error}</div>
      )}

      {rows.length === 0 && !error && (
        <div style={{ background: '#fff', border: '1px solid oklch(94% 0.01 265)', borderRadius: 12,
          padding: '40px 28px', textAlign: 'center', color: AA_MUTED, fontSize: 15 }}>
          No applications to review.
        </div>
      )}

      <div style={{ display: 'grid', gap: 10 }}>
        {rows.map(r => {
          const draft = isDraftRow(r);
          const nameOrEmail = r.full_name || r.email || '(unknown teacher)';
          // Every row opens the full AdminSignupReview drawer — that's the
          // only surface that exposes the "Edit fields" button (which mounts
          // AdminOnboardingEdit and writes admin_save_onboarding). Drafts
          // were previously short-circuited to the nudge modal, which Joe
          // flagged because it gave admins no way to edit a stalled draft's
          // hourly rate / address / education before nudging.
          const onCardClick = () => setOpenInstr({ id: r.instructor_id, name: nameOrEmail });
          return (
            <div key={r.instructor_id}
              style={{
                background: '#fff', border: '1px solid oklch(94% 0.01 265)', borderRadius: 12,
                padding: isMobile ? 14 : 18,
                fontFamily: "'Plus Jakarta Sans', sans-serif",
              }}>
              <button
                onClick={onCardClick}
                style={{
                  display: 'grid', gridTemplateColumns: isMobile ? 'auto 1fr' : 'auto 1fr auto',
                  gap: isMobile ? 12 : 16, alignItems: 'flex-start', width: '100%',
                  background: 'transparent', border: 'none', padding: 0,
                  textAlign: 'left', cursor: 'pointer', font: 'inherit', color: 'inherit',
                }}>

                <div style={{ width: 48, height: 48, borderRadius: '50%', background: 'oklch(92% 0.02 265)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden',
                  flexShrink: 0 }}>
                  {r.photo_url
                    ? <img src={r.photo_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    : <span style={{ fontWeight: 700, fontSize: 16, color: AA_MUTED }}>
                        {(r.full_name || r.email || '?').split(' ').map(s => s[0]).slice(0, 2).join('').toUpperCase()}
                      </span>}
                </div>

                <div style={{ minWidth: 0 }}>
                  <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', marginBottom: 4 }}>
                    <span style={{ fontWeight: 700, fontSize: 15, color: AA_INK }}>
                      {r.full_name || '(no name yet)'}
                    </span>
                    <AAStatusPill status={r.review_status} currentStep={r.current_step} />
                    {nudgeSentFor === r.instructor_id && (
                      <span style={{ fontSize: 11, fontWeight: 600, color: 'oklch(40% 0.16 145)' }}>
                        Nudge sent
                      </span>
                    )}
                  </div>
                  <div style={{ fontSize: 12.5, color: AA_MUTED, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {r.email || '(no email)'}
                  </div>
                  {r.headline && (
                    <div style={{ fontSize: 13, color: 'oklch(35% 0.04 265)', marginTop: 6,
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {r.headline}
                    </div>
                  )}
                  <div style={{ fontSize: 12, color: AA_MUTED, marginTop: 6, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                    <span>Signed up {AAFormatRel(r.created_at)}</span>
                    {r.submitted_at && <span>· Submitted {AAFormatRel(r.submitted_at)}</span>}
                    {r.last_edited_at && r.submitted_at && new Date(r.last_edited_at) > new Date(r.submitted_at) && (
                      <span style={{ color: 'oklch(45% 0.14 80)', fontWeight: 600 }}>
                        · Edited {AAFormatRel(r.last_edited_at)}
                      </span>
                    )}
                    {r.rate ? <span>· ${r.rate}/hr</span> : null}
                    {r.subject_count ? <span>· {r.subject_count} subject{r.subject_count !== 1 ? 's' : ''}</span> : null}
                    {r.city ? <span>· {r.city}{r.state ? `, ${r.state}` : ''}</span> : null}
                  </div>
                  <AAStepChips row={r} />
                </div>

                {!isMobile && (
                  <div style={{ color: 'oklch(45% 0.13 265)', fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', alignSelf: 'center' }}>
                    Review →
                  </div>
                )}
              </button>

              {draft && (
                <div style={{ marginTop: 12, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <button
                    onClick={() => setNudgeRow(r)}
                    style={{
                      background: 'oklch(96% 0.04 265)', color: 'oklch(35% 0.13 265)',
                      border: '1px solid oklch(86% 0.04 265)', borderRadius: 8,
                      padding: '7px 14px', fontSize: 12.5, fontWeight: 700, cursor: 'pointer',
                      fontFamily: "'Plus Jakarta Sans', sans-serif",
                    }}>Send nudge email</button>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {openInstr && window.AdminSignupReview && (
        <window.AdminSignupReview
          instructor={openInstr}
          onClose={() => { setOpenInstr(null); load(); }}
        />
      )}

      {nudgeRow && (
        <AANudgeModal
          row={nudgeRow}
          onClose={() => setNudgeRow(null)}
          onSent={() => { setNudgeSentFor(nudgeRow.instructor_id); load(); }}
        />
      )}
    </div>
  );
};

window.AdminApplications = AdminApplications;
