// src/features/admin/ui/admin-ratings.jsx
//
// Admin view of the per-session feedback added in v72.
//
// Publishes two things on window:
//   AdminRatings              — the page component mounted from the
//                                admin-dashboard sidebar under "Ratings".
//   AdminBookingRatingChips   — reusable inline chip pair ("Student ★4 /
//                                Teacher ★3") meant to drop into existing
//                                lesson-row UIs (admin-students-card +
//                                admin-instructors-card on a follow-up).

// ── Shared inline chip pair (drop into any lesson row) ───────────────
const AdminBookingRatingChips = ({ booking, compact }) => {
  // Accept either the camelCase shape (data-mappers.js) or raw row.
  const s = booking?.studentRating ?? booking?.student_rating ?? null;
  const t = booking?.teacherRating ?? booking?.teacher_rating ?? null;
  if (s == null && t == null) return null;
  const chip = (label, n, color) => (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: compact ? '2px 8px' : '3px 10px',
      borderRadius: 999,
      background: color.bg, color: color.fg,
      fontSize: compact ? 10.5 : 11,
      fontWeight: 700, letterSpacing: '0.04em',
      whiteSpace: 'nowrap',
    }} title={`${label} rated ${n}/5`}>
      <span style={{ fontSize: compact ? 10 : 11, opacity: 0.7 }}>{label}</span>
      <span>★ {n}</span>
    </span>
  );
  return (
    <span style={{ display: 'inline-flex', gap: 6, flexWrap: 'wrap' }}>
      {s != null && chip('Student', s, { bg: 'oklch(95% 0.06 80)',  fg: 'oklch(36% 0.14 75)' })}
      {t != null && chip('Teacher', t, { bg: 'oklch(94% 0.05 265)', fg: 'oklch(28% 0.1 265)' })}
    </span>
  );
};
window.AdminBookingRatingChips = AdminBookingRatingChips;

// ── Star row for the log (read-only) ─────────────────────────────────
const StarRow = ({ value, label }) => {
  if (value == null) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <span style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'oklch(58% 0.03 265)', width: 60 }}>{label}</span>
        <span style={{ fontSize: 12, color: 'oklch(64% 0.03 265)', fontStyle: 'italic' }}>not rated</span>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <span style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'oklch(58% 0.03 265)', width: 60 }}>{label}</span>
      <span style={{ display: 'inline-flex', gap: 2 }}>
        {[1,2,3,4,5].map(n => (
          <svg key={n} width={13} height={13} viewBox="0 0 16 16">
            <path d="M8 1.5l1.8 3.7 4.1.6-3 2.9.7 4.1L8 10.8l-3.6 1.9.7-4.1-3-2.9 4.1-.6z"
              fill={n <= value ? 'oklch(72% 0.17 80)' : 'oklch(90% 0.015 60)'} />
          </svg>
        ))}
      </span>
      <span style={{ fontSize: 11, fontWeight: 600, color: 'oklch(40% 0.04 265)' }}>{value}/5</span>
    </div>
  );
};

// ── Single log row ───────────────────────────────────────────────────
const LogRow = ({ r }) => {
  const when = new Date(r.scheduledAt);
  const dateLabel = when.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' });
  const timeLabel = when.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
  return (
    <div style={{
      background: '#fff', border: '1px solid oklch(92% 0.01 265)', borderRadius: 12,
      padding: '14px 16px', marginBottom: 10,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap', marginBottom: 10 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'oklch(20% 0.04 265)', lineHeight: 1.3 }}>
            {r.studentName} <span style={{ color: 'oklch(58% 0.03 265)', fontWeight: 400 }}>with</span> {r.instructorName}
          </div>
          <div style={{ fontSize: 12, color: 'oklch(54% 0.03 265)', marginTop: 3 }}>
            {dateLabel} · {timeLabel}
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <StarRow value={r.studentRating} label="Student" />
        {r.studentRatingNote && (
          <div style={{ fontSize: 13, color: 'oklch(28% 0.05 265)', background: 'oklch(98% 0.02 80)', borderLeft: '3px solid oklch(72% 0.17 80)', padding: '8px 12px', borderRadius: 6, lineHeight: 1.55 }}>
            "{r.studentRatingNote}"
          </div>
        )}
        <StarRow value={r.teacherRating} label="Teacher" />
        {r.teacherNotes && (
          <div style={{ fontSize: 13, color: 'oklch(28% 0.05 265)', background: 'oklch(97% 0.02 265)', borderLeft: '3px solid oklch(60% 0.12 265)', padding: '8px 12px', borderRadius: 6, lineHeight: 1.55, whiteSpace: 'pre-wrap' }}>
            {r.teacherNotes}
          </div>
        )}
      </div>
    </div>
  );
};

// ── Tab page ─────────────────────────────────────────────────────────
const AdminRatings = () => {
  const [rows,    setRows]    = React.useState(null);  // null = loading
  const [summary, setSummary] = React.useState(null);
  const [filter,  setFilter]  = React.useState('any');  // 'any' | 'student' | 'teacher'
  const [error,   setError]   = React.useState(null);

  const refresh = React.useCallback(async () => {
    setError(null);
    try {
      const [list, sum] = await Promise.all([
        window.ADMIN_DATA.loadRatingLog({ limit: 100 }),
        window.ADMIN_DATA.loadRatingSummary(),
      ]);
      setRows(list);
      setSummary(sum);
    } catch (e) {
      setError(e.message || 'Failed to load');
      setRows([]);
    }
  }, []);

  React.useEffect(() => { refresh(); }, [refresh]);

  const filtered = React.useMemo(() => {
    if (!rows) return null;
    if (filter === 'student') return rows.filter(r => r.studentRating != null);
    if (filter === 'teacher') return rows.filter(r => r.teacherRating != null);
    return rows;
  }, [rows, filter]);

  const filterBtn = (key, label, count) => (
    <button onClick={() => setFilter(key)} style={{
      padding: '7px 12px', borderRadius: 999, fontSize: 12, fontWeight: 600,
      background: filter === key ? 'oklch(22% 0.06 265)' : '#fff',
      color:      filter === key ? '#fff'              : 'oklch(36% 0.04 265)',
      border:     filter === key ? 'none'              : '1px solid oklch(88% 0.01 265)',
      cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif",
    }}>
      {label}{typeof count === 'number' && <span style={{ marginLeft: 6, opacity: 0.65, fontWeight: 500 }}>{count}</span>}
    </button>
  );

  const stat = (label, value, sub) => (
    <div style={{
      background: '#fff', border: '1px solid oklch(92% 0.01 265)', borderRadius: 12,
      padding: '14px 16px', flex: '1 1 160px', minWidth: 0,
    }}>
      <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'oklch(58% 0.03 265)' }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
        <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 24, fontWeight: 700, color: 'oklch(18% 0.03 265)', lineHeight: 1 }}>{value ?? '—'}</div>
        {sub && <div style={{ fontSize: 12, color: 'oklch(58% 0.03 265)' }}>{sub}</div>}
      </div>
    </div>
  );

  return (
    <div style={{ padding: 'clamp(16px, 3vw, 24px)', maxWidth: 920, margin: '0 auto', fontFamily: "'Plus Jakarta Sans', sans-serif" }}>

      {/* KPI strip */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 18 }}>
        {stat('Student avg',    summary?.studentAvg, summary?.studentAvg != null ? '/ 5' : null)}
        {stat('Teacher avg',    summary?.teacherAvg, summary?.teacherAvg != null ? '/ 5' : null)}
        {stat('Student ratings', summary?.studentRatedCount, 'total')}
        {stat('Teacher ratings', summary?.teacherRatedCount, 'total')}
      </div>

      {/* Filter pills */}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 14, flexWrap: 'wrap' }}>
        <span style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'oklch(58% 0.03 265)', marginRight: 4 }}>Show</span>
        {filterBtn('any',     'All',           rows?.length)}
        {filterBtn('student', 'Student only',  rows?.filter(r => r.studentRating != null).length)}
        {filterBtn('teacher', 'Teacher only',  rows?.filter(r => r.teacherRating != null).length)}
        <span style={{ flex: 1 }} />
        <button onClick={refresh} title="Reload" style={{
          background: 'transparent', border: '1px solid oklch(88% 0.01 265)', borderRadius: 8,
          padding: '7px 10px', fontSize: 12, cursor: 'pointer', color: 'oklch(36% 0.04 265)',
          fontFamily: "'Plus Jakarta Sans', sans-serif",
        }}>Refresh</button>
      </div>

      {/* List */}
      {error && (
        <div style={{ background: 'oklch(96% 0.05 25)', color: 'oklch(40% 0.15 25)', padding: 12, borderRadius: 8, marginBottom: 12, fontSize: 13 }}>
          {error}
        </div>
      )}
      {filtered === null && (
        <div style={{ color: 'oklch(58% 0.03 265)', fontSize: 13, padding: 16, textAlign: 'center' }}>Loading…</div>
      )}
      {filtered && filtered.length === 0 && !error && (
        <div style={{ background: '#fff', border: '1px solid oklch(92% 0.01 265)', borderRadius: 12, padding: 28, textAlign: 'center', color: 'oklch(58% 0.03 265)', fontSize: 14 }}>
          No ratings yet.
        </div>
      )}
      {filtered && filtered.map(r => <LogRow key={r.id} r={r} />)}
    </div>
  );
};

window.AdminRatings = AdminRatings;
