/* screens-survey.jsx — Learner data collection: survey popups + queue manager */
const { useState: svState, useEffect: svEffect } = React;

/* ── inject animation styles ─────────────────────────────────── */
(function () {
  if (document.getElementById('survey-styles')) return;
  const s = document.createElement('style');
  s.id = 'survey-styles';
  s.textContent = `
    @keyframes surveySlideUp {
      from { opacity: 0; transform: translateY(28px) scale(.97); }
      to   { opacity: 1; transform: translateY(0)    scale(1);   }
    }
    @keyframes surveyFadeIn { from { opacity:0; } to { opacity:1; } }

    .survey-overlay {
      position: fixed; inset: 0; z-index: 10000;
      background: rgba(0,0,0,.6);
      backdrop-filter: blur(12px);
      display: grid; place-items: center;
      padding: 20px;
      animation: surveyFadeIn .22s ease;
    }
    .survey-card {
      background: var(--bg);
      border-radius: 24px;
      padding: 40px 44px;
      max-width: 480px; width: 100%;
      box-shadow: 0 40px 100px rgba(0,0,0,.45);
      animation: surveySlideUp .32s cubic-bezier(.4,0,.2,1);
    }
    .sv-icon {
      width: 82px; height: 82px; border-radius: 50%;
      display: grid; place-items: center;
      margin: 0 auto 20px; font-size: 38px; line-height: 1;
    }
    .sv-kicker {
      font-size: 11px; font-weight: 800; letter-spacing: .12em;
      text-transform: uppercase; color: var(--text-muted);
      text-align: center; margin: 0 0 8px;
    }
    .sv-title {
      font-size: 21px; font-weight: 800; line-height: 1.35;
      text-align: center; margin: 0 0 6px;
    }
    .sv-subtitle {
      font-size: 14px; color: var(--text-muted); text-align: center; margin: 0 0 28px;
    }
    .sv-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 26px; }

    /* confidence emoji buttons */
    .conf-row { display: flex; justify-content: center; gap: 10px; }
    .conf-btn {
      display: flex; flex-direction: column; align-items: center; gap: 7px;
      padding: 12px 10px; border-radius: 14px; cursor: pointer;
      min-width: 62px; border: 2px solid var(--border);
      background: var(--surface-1); transition: all .15s;
    }
    .conf-btn.active  { border-color: var(--lime); background: var(--lime-soft); }
    .conf-btn .cv-em  { font-size: 28px; line-height: 1; transition: transform .15s; }
    .conf-btn.active .cv-em { transform: scale(1.2); }
    .conf-btn .cv-num { font-size: 11px; font-weight: 700; color: var(--text-muted); }
    .conf-btn.active .cv-num { color: var(--lime-strong); }

    /* star rating */
    .star-row { display: flex; justify-content: center; gap: 6px; }
    .star-btn {
      background: none; border: none; padding: 3px; cursor: pointer;
      font-size: 36px; line-height: 1; transition: transform .12s, filter .12s;
    }

    /* NPS grid */
    .nps-grid { display: grid; grid-template-columns: repeat(11,1fr); gap: 5px; }
    .nps-btn {
      border: 2px solid var(--border); background: var(--surface-1);
      border-radius: 9px; padding: 9px 2px;
      font-weight: 700; font-size: 14px; cursor: pointer;
      color: var(--text); transition: all .12s;
    }
  `;
  document.head.appendChild(s);
}());

/* ── Supabase save ───────────────────────────────────────────── */
async function saveSurveyResponse(item, score) {
  const db = window.supabaseClient;
  const uid = window.ME_UUID;
  if (!db || !uid) return;

  if (item.type === 'confidence') {
    await db.from('confidence_checks').upsert({
      user_id: uid,
      module_id: String(item.moduleId || 'course'),
      type: item.checkType,
      score,
    }, { onConflict: 'user_id,module_id,type' });
  } else {
    const TYPE_MAP = { course_satisfaction: 'satisfaction', module_pulse: 'module_satisfaction' };
    const responseType = TYPE_MAP[item.type] || item.type;
    await db.from('experience_responses').insert({
      user_id: uid,
      lesson_id: item.lessonId ? String(item.lessonId) : null,
      module_id: item.moduleId ? String(item.moduleId) : null,
      response_type: responseType,
      score,
    });
  }
}

/* ── Base shell ──────────────────────────────────────────────── */
function SurveyShell({ iconBg, icon, kicker, title, subtitle, children, actions }) {
  return (
    <div className="survey-overlay">
      <div className="survey-card">
        <div className="sv-icon" style={{ background: iconBg }}>{icon}</div>
        {kicker && <p className="sv-kicker">{kicker}</p>}
        <h2 className="sv-title">{title}</h2>
        {subtitle && <p className="sv-subtitle">{subtitle}</p>}
        {children}
        <div className="sv-actions">{actions}</div>
      </div>
    </div>
  );
}

/* ── Confidence check (1 – 5 emoji scale) ────────────────────── */
const CONF_OPTS = [
  { emoji: '😟', label: 'Not confident' },
  { emoji: '😐', label: 'Slightly unsure' },
  { emoji: '🙂', label: 'Getting there' },
  { emoji: '😊', label: 'Fairly confident' },
  { emoji: '🤩', label: 'Very confident' },
];

function ConfidenceCheck({ moduleTitle, checkType, scope, onSubmit, onSkip }) {
  const [score, setScore] = svState(null);
  const [hover, setHover] = svState(null);
  const isPre = checkType === 'pre';
  const isCourse = !scope || scope === 'course';

  return (
    <SurveyShell
      iconBg={isPre
        ? 'linear-gradient(135deg,#E0F2FE,#BAE6FD)'
        : 'linear-gradient(135deg,var(--lime-soft),var(--lime))'}
      icon={isPre ? '🧠' : '🎯'}
      kicker={isPre ? 'Before you begin' : isCourse ? 'Course complete! 🎉' : 'Module complete! 🎯'}
      title={isPre
        ? 'How confident are you about the topics in this course right now?'
        : isCourse
          ? 'How confident do you feel now that you\'ve completed the full course?'
          : `How confident do you feel after completing ${moduleTitle || 'this module'}?`}
      subtitle={isCourse ? moduleTitle : null}
      actions={<>
        <button className="btn btn-ghost" onClick={onSkip}>Skip</button>
        <button className="btn btn-primary" disabled={!score} onClick={() => onSubmit(score)}>
          {isPre ? "Let's go →" : 'Save →'}
        </button>
      </>}
    >
      <div className="conf-row" style={{ marginBottom: 8 }}>
        {CONF_OPTS.map((o, i) => {
          const val = i + 1;
          const active = score === val || hover === val;
          return (
            <button key={i} className={`conf-btn${active ? ' active' : ''}`}
              onClick={() => setScore(val)}
              onMouseEnter={() => setHover(val)}
              onMouseLeave={() => setHover(null)}>
              <span className="cv-em">{o.emoji}</span>
              <span className="cv-num">{val}</span>
            </button>
          );
        })}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--text-muted)', padding: '0 4px' }}>
        <span>Not confident</span><span>Very confident</span>
      </div>
      {score && (
        <p style={{ textAlign: 'center', fontSize: 14, fontWeight: 700, color: 'var(--lime-strong)', marginTop: 14 }}>
          {CONF_OPTS[score - 1].label}
        </p>
      )}
    </SurveyShell>
  );
}

/* ── Lesson pulse (1 – 5 stars) ──────────────────────────────── */
const PULSE_LABELS = ['Tap to rate', 'Not for me', 'Could be better', 'It was okay', 'Pretty good!', 'Loved it! ✨'];

function LessonPulse({ lessonTitle, moduleMode, onSubmit, onSkip }) {
  const [rating, setRating] = svState(0);
  const [hover, setHover] = svState(0);
  const active = hover || rating;

  return (
    <SurveyShell
      iconBg={moduleMode ? 'linear-gradient(135deg,#DCFCE7,#86EFAC)' : 'linear-gradient(135deg,#FEF9C3,#FDE68A)'}
      icon={moduleMode ? '🏁' : '⭐'}
      kicker={moduleMode ? 'Module complete' : 'Lesson complete'}
      title={moduleMode ? 'How was this module?' : 'How was this lesson?'}
      subtitle={lessonTitle}
      actions={<>
        <button className="btn btn-ghost" onClick={onSkip}>Skip</button>
        <button className="btn btn-primary" disabled={!rating} onClick={() => onSubmit(rating)}>Submit →</button>
      </>}
    >
      <div className="star-row" style={{ marginBottom: 8 }}>
        {[1, 2, 3, 4, 5].map(n => (
          <button key={n} className="star-btn"
            onClick={() => setRating(n)}
            onMouseEnter={() => setHover(n)}
            onMouseLeave={() => setHover(0)}
            style={{
              filter: n <= active ? 'none' : 'grayscale(1) opacity(.28)',
              transform: n <= active ? 'scale(1.12)' : 'scale(1)',
            }}>⭐</button>
        ))}
      </div>
      <p style={{ textAlign: 'center', fontSize: 15, fontWeight: 600, color: 'var(--text-muted)', minHeight: 22 }}>
        {PULSE_LABELS[active]}
      </p>
    </SurveyShell>
  );
}

/* ── NPS survey (0 – 10) ─────────────────────────────────────── */
function NPSSurvey({ onSubmit, onSkip }) {
  const [score, setScore] = svState(null);
  const npsColor = n => n >= 9 ? '#16A34A' : n >= 7 ? '#D97706' : '#DC2626';

  return (
    <SurveyShell
      iconBg="linear-gradient(135deg,#EDE9FE,#C4B5FD)"
      icon="💬"
      kicker="Quick check-in"
      title="How likely are you to recommend this course to a colleague?"
      actions={<>
        <button className="btn btn-ghost" onClick={onSkip}>Skip</button>
        <button className="btn btn-primary" disabled={score === null} onClick={() => onSubmit(score)}>Submit →</button>
      </>}
    >
      <div className="nps-grid" style={{ marginBottom: 8 }}>
        {Array.from({ length: 11 }, (_, n) => (
          <button key={n} className="nps-btn"
            onClick={() => setScore(n)}
            style={{
              borderColor: score === n ? npsColor(n) : 'var(--border)',
              background: score === n ? npsColor(n) : 'var(--surface-1)',
              color: score === n ? '#fff' : 'var(--text)',
            }}>
            {n}
          </button>
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--text-muted)' }}>
        <span>0 — Not likely</span><span>10 — Very likely</span>
      </div>
    </SurveyShell>
  );
}

/* ── Course satisfaction (end-of-course 1 – 5 stars) ────────── */
const COURSE_SAT_LABELS = ['Tap to rate', 'Not for me', 'Could be better', 'It was okay', 'Really good!', 'Outstanding! 🌟'];

function CourseSatisfaction({ onSubmit, onSkip }) {
  const [rating, setRating] = svState(0);
  const [hover, setHover] = svState(0);
  const active = hover || rating;

  return (
    <SurveyShell
      iconBg="linear-gradient(135deg,#EDE9FE,#C4B5FD)"
      icon="🎓"
      kicker="Course complete — well done!"
      title="How satisfied are you with this course overall?"
      actions={<>
        <button className="btn btn-ghost" onClick={onSkip}>Skip</button>
        <button className="btn btn-primary" disabled={!rating} onClick={() => onSubmit(rating)}>Submit →</button>
      </>}
    >
      <div className="star-row" style={{ marginBottom: 8 }}>
        {[1, 2, 3, 4, 5].map(n => (
          <button key={n} className="star-btn"
            onClick={() => setRating(n)}
            onMouseEnter={() => setHover(n)}
            onMouseLeave={() => setHover(0)}
            style={{
              filter: n <= active ? 'none' : 'grayscale(1) opacity(.28)',
              transform: n <= active ? 'scale(1.12)' : 'scale(1)',
            }}>⭐</button>
        ))}
      </div>
      <p style={{ textAlign: 'center', fontSize: 15, fontWeight: 600, color: 'var(--text-muted)', minHeight: 22 }}>
        {COURSE_SAT_LABELS[active]}
      </p>
    </SurveyShell>
  );
}

/* ── Queue manager: shows surveys one at a time ──────────────── */
function SurveyQueue({ surveys, onComplete }) {
  const [idx, setIdx] = svState(0);

  if (!surveys || !surveys.length || idx >= surveys.length) return null;

  const item = surveys[idx];
  const next = () => { if (idx + 1 >= surveys.length) onComplete(); else setIdx(idx + 1); };
  const submit = async (score) => { await saveSurveyResponse(item, score); next(); };

  if (item.type === 'confidence')
    return <ConfidenceCheck moduleTitle={item.moduleTitle} checkType={item.checkType} scope={item.moduleId === 'course' ? 'course' : 'module'} onSubmit={submit} onSkip={next} />;
  if (item.type === 'lesson_pulse')
    return <LessonPulse lessonTitle={item.lessonTitle} onSubmit={submit} onSkip={next} />;
  if (item.type === 'module_pulse')
    return <LessonPulse lessonTitle={item.moduleTitle} moduleMode={true} onSubmit={submit} onSkip={next} />;
  if (item.type === 'nps')
    return <NPSSurvey onSubmit={submit} onSkip={next} />;
  if (item.type === 'course_satisfaction')
    return <CourseSatisfaction onSubmit={submit} onSkip={next} />;

  return null;
}

window.SurveyQueue = SurveyQueue;
