
// ── Counselor review console — DEMO ONLY ─────────────────────────────────────
// This is a lightweight demo surface for the YC application video. It is NOT a
// production system: there is NO real authentication, NO counselor accounts, NO
// permissions model, and NO email/notification/queue infra. The "passcode"
// below is a hardcoded demo gate, intentionally trivial — do NOT treat it as
// security (it ships in plaintext in the bundle). A real deployment would gate
// this behind the institution's SSO and back it with a real submissions store.
//
// It reuses the student's OWN profile (the single demo plan in localStorage) and
// the REAL PlanView rendering, so the counselor sees exactly what the student
// sees. Suggestions + approval write back through the same onUpdateProfile the
// student uses, so notes appear on the student's cards with no sync plumbing.

const { useState } = React;

// DEMO passcode — NOT authentication. Anyone can read this in the source.
const COUNSELOR_DEMO_PASSCODE = 'lumen';

function CounselorGate({ onUnlock }) {
  const [pass, setPass] = useState('');
  const [err, setErr] = useState(false);
  const submit = (e) => {
    e.preventDefault();
    if (pass.trim().toLowerCase() === COUNSELOR_DEMO_PASSCODE) onUnlock();
    else setErr(true);
  };
  return (
    <div className="cnsl-gate">
      <div className="cnsl-gate-card">
        <div className="cnsl-demo-tag">Demo · not real authentication</div>
        <div className="cnsl-gate-logo">
          <span className="logo-transfer">Transfer</span><span className="logo-lens">Lens</span>
          <span className="cnsl-gate-role">for counselors</span>
        </div>
        <p className="cnsl-gate-sub">
          Enter the demo passcode to open the review queue. This is a stand-in gate for the
          video — a real deployment would use your institution's single sign-on.
        </p>
        <form onSubmit={submit} className="cnsl-gate-form">
          <input className="cnsl-gate-input" type="password" placeholder="Demo passcode" value={pass}
            onChange={e => { setPass(e.target.value); setErr(false); }} autoFocus />
          <button className="cnsl-gate-btn" type="submit">Enter console →</button>
        </form>
        {err
          ? <div className="cnsl-gate-err">That's not the demo passcode. (Hint: it's “lumen”.)</div>
          : <div className="cnsl-gate-hint">Demo passcode: <code>lumen</code></div>}
        <button className="cnsl-gate-back" onClick={() => { window.location.hash = ''; }}>← Back to TransferLens</button>
      </div>
    </div>
  );
}

function CounselorView({ profile, onUpdateProfile, onExit }) {
  const [unlocked, setUnlocked] = useState(() => {
    try { return sessionStorage.getItem('tl_cnsl_demo') === '1'; } catch { return false; }
  });
  const [openPlan, setOpenPlan] = useState(false);

  const unlock = () => { try { sessionStorage.setItem('tl_cnsl_demo', '1'); } catch {} setUnlocked(true); };

  if (!unlocked) return <CounselorGate onUnlock={unlock} />;

  const status = profile?.reviewStatus || null;
  const inQueue = status === 'pending';
  const reviewed = status === 'reviewed';
  const suggestionCount = Object.keys(profile?.courseSuggestions || {}).length;

  // Demo "student" label — no real accounts, so derive it from the plan itself.
  const ccName = profile?.cc?.name || 'Demo student';
  const schools = (profile?.selections || []).map(s => s.school?.abbr).filter(Boolean).join(', ') || '—';
  const termLabel = (window.TRANSFER_TERMS || []).find(t => t.id === profile?.transferTerm)?.label || profile?.transferTerm || '—';
  const totalUnits = Object.values(profile?.semesters || {}).flat()
    .reduce((n, k) => n + ((window.MOCK_COURSES[k] || {}).units || 3), 0);

  const approve = () => {
    onUpdateProfile({ reviewStatus: 'reviewed', reviewedAt: Date.now() });
    window.tlToast('Plan approved — student sees “Reviewed” (demo)', { type: 'success' });
  };

  // ── Detail: reuse the REAL PlanView so the counselor sees what the student sees.
  if (openPlan) {
    return (
      <div className="cnsl-root">
        <div className="cnsl-bar">
          <button className="cnsl-bar-back" onClick={() => setOpenPlan(false)}>← Queue</button>
          <div className="cnsl-bar-title">
            <span className="cnsl-bar-name">{ccName}</span>
            <span className="cnsl-bar-meta">{schools} · {termLabel} · {totalUnits} units</span>
          </div>
          <div className="cnsl-bar-actions">
            <span className="cnsl-demo-tag">Demo review</span>
            {reviewed
              ? <span className="plan-review-badge reviewed">✓ Approved</span>
              : <button className="cnsl-approve-btn" onClick={approve}>Approve plan</button>}
          </div>
        </div>
        <div className="cnsl-hint">
          Click the 💬 icon on any course to leave a free-text suggestion — it saves straight onto the
          student's plan. “Approve plan” sets their status to <strong>Reviewed</strong>.
        </div>
        <div className="cnsl-plan-wrap">
          <window.PlanView profile={profile} onUpdateProfile={onUpdateProfile} onReset={() => {}} counselorMode={true} />
        </div>
      </div>
    );
  }

  // ── Queue
  const QueueCard = ({ badge, metaExtra }) => (
    <button className="cnsl-queue-card" onClick={() => setOpenPlan(true)}>
      <div className="cnsl-queue-main">
        <div className="cnsl-queue-name">{ccName}</div>
        <div className="cnsl-queue-meta">
          Target: {schools} · {termLabel} · {totalUnits} units{metaExtra}
          {suggestionCount ? ` · ${suggestionCount} suggestion${suggestionCount === 1 ? '' : 's'}` : ''}
        </div>
      </div>
      {badge}
      <span className="cnsl-queue-arrow">→</span>
    </button>
  );

  return (
    <div className="cnsl-root">
      <div className="cnsl-bar">
        <div className="cnsl-bar-title">
          <span className="cnsl-bar-name">Counselor review queue</span>
          <span className="cnsl-bar-meta">Plans students submitted for review</span>
        </div>
        <div className="cnsl-bar-actions">
          <span className="cnsl-demo-tag">Demo console · no real accounts</span>
          <button className="cnsl-bar-back" onClick={onExit}>Exit →</button>
        </div>
      </div>

      <div className="cnsl-queue">
        {inQueue && <QueueCard badge={<span className="plan-review-badge pending">◷ Awaiting review</span>} />}
        {reviewed && <QueueCard metaExtra=" · reviewed" badge={<span className="plan-review-badge reviewed">✓ Reviewed</span>} />}
        {!inQueue && !reviewed && (
          <div className="cnsl-empty">
            <div className="cnsl-empty-title">No plans awaiting review</div>
            <div className="cnsl-empty-sub">
              When a student clicks “Submit for counselor review” on their plan, it appears here.
              This demo reads the plan stored in this browser.
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CounselorView });
