/* screens-editor.jsx — Block-based Lesson Builder for staff/editors */
const { useState: eState, useEffect: eEffect, useRef: eRef } = React;

/* ─── Block palette definition ───────────────────────────────────── */
const EDITOR_PALETTE = [
  { group: 'Content', items: [
    { type: 'heading',   label: 'Heading',    icon: 'pen',    hint: 'Section title (H2 or H3)' },
    { type: 'text',      label: 'Paragraph',  icon: 'pen',    hint: 'Body text' },
    { type: 'callout',   label: 'Callout',    icon: 'target', hint: 'Key point, tip, warning, or info box' },
    { type: 'divider',   label: 'Divider',    icon: 'minus',  hint: 'Visual separator between sections' },
  ]},
  { group: 'Media', items: [
    { type: 'video',  label: 'Video',      icon: 'play',   hint: 'YouTube, Vimeo, or direct MP4 link' },
    { type: 'image',  label: 'Image',      icon: 'layers', hint: 'URL or Supabase storage path' },
    { type: 'pdf',    label: 'PDF / File', icon: 'book',   hint: 'Downloadable document with link' },
    { type: 'embed',  label: 'Embed',      icon: 'link',   hint: 'Google Slides, Loom, Figma, iFrame…' },
  ]},
  { group: 'Assessment', items: [
    { type: 'mcq',       label: 'Quiz Question', icon: 'quiz',  hint: 'Multiple choice with correct answer + explanation' },
    { type: 'checklist', label: 'Checklist',     icon: 'check', hint: 'Learner tick-off steps or tasks' },
  ]},
  { group: 'People', items: [
    { type: 'instructor-intros', label: 'Instructor Intros', icon: 'robot', hint: 'Circular video cards for instructor introductions' },
  ]},
  { group: 'Interactive', items: [
    { type: 'journal',               label: 'Reflection Journal',       icon: 'pen',    hint: 'Private per-learner notes, saved to Supabase' },
    { type: 'discussion',            label: 'Discussion Board',          icon: 'chat',   hint: 'Cohort conversation scoped to this lesson' },
    { type: 'aichat',                label: 'AI Sandbox',                icon: 'robot',  hint: 'AI persona chat (coming soon)' },
    { type: 'upload',                label: 'File Submission',           icon: 'upload', hint: 'PDF / DOCX assignment upload' },
    { type: 'video-upload',          label: 'Video Submission',          icon: 'film',   hint: 'Learner video reflection upload' },
    { type: 'ai-opportunity-canvas', label: 'AI Opportunity Canvas',     icon: 'target', hint: 'Backward-design worksheet for AI integration planning' },
  ]},
];

const BLOCK_DEFAULTS = {
  heading:        { content: 'New Heading', level: 2 },
  text:           { content: '' },
  callout:        { content: '', variant: 'key' },
  divider:        {},
  video:          { url: '', caption: '' },
  image:          { url: '', alt: '', caption: '' },
  pdf:            { url: '', label: 'Download document' },
  embed:          { url: '', caption: '' },
  mcq:            { question: '', options: ['', '', ''], correct: 0, explanation: '' },
  checklist:      { title: '', items: [''] },
  journal:        { prompt: '' },
  discussion:     {},
  aichat:         {},
  upload:         { label: 'Submit your assignment', hint: 'PDF, DOCX — up to 50 MB' },
  'video-upload': { label: 'Submit your video reflection', hint: 'MP4, MOV — up to 500 MB' },
  'instructor-intros': { heading: 'Meet Your Instructors', instructors: [{ name: '', title: '', videoUrl: '' }] },
  'ai-opportunity-canvas': {},
};

const CALLOUT_VARIANTS = {
  key:     { bg: 'var(--lime-soft)',                                          border: 'var(--lime)',  icon: 'target', label: 'Key Point' },
  info:    { bg: 'color-mix(in srgb, #3498db 10%, var(--surface))',           border: '#3498db',      icon: 'info',   label: 'Info' },
  tip:     { bg: 'color-mix(in srgb, #27AE60 10%, var(--surface))',           border: '#27AE60',      icon: 'check',  label: 'Tip' },
  warning: { bg: 'color-mix(in srgb, #E67E22 12%, var(--surface))',           border: '#E67E22',      icon: 'flag',   label: 'Warning' },
};

/* ─── Block Preview (read-style, shown on canvas) ────────────────── */
function BlockPreview({ b }) {
  const cv = CALLOUT_VARIANTS[b.variant] || CALLOUT_VARIANTS.key;
  switch (b.type) {
    case 'heading':
      return <div style={{ fontSize: b.level === 3 ? 20 : 26, fontWeight: 800, fontFamily: 'var(--font-head)', color: b.content ? 'var(--text)' : 'var(--text-muted)', lineHeight: 1.2 }}>{b.content || 'Heading text…'}</div>;
    case 'text':
      return <p style={{ fontSize: 16, lineHeight: 1.65, margin: 0, color: b.content ? 'var(--text)' : 'var(--text-muted)', whiteSpace: 'pre-wrap' }}>{b.content || 'Paragraph text…'}</p>;
    case 'callout':
      return (
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', background: cv.bg, borderLeft: `4px solid ${cv.border}`, borderRadius: 10, padding: '12px 16px' }}>
          <Icon name={cv.icon} size={18} style={{ color: cv.border, flex: 'none', marginTop: 2 }} />
          <p style={{ margin: 0, fontSize: 15, fontWeight: 600, lineHeight: 1.5, color: b.content ? 'var(--text)' : 'var(--text-muted)' }}>{b.content || 'Callout text…'}</p>
        </div>
      );
    case 'divider':
      return <hr style={{ border: 'none', borderTop: '1.5px solid var(--border)', margin: '4px 0' }} />;
    case 'video':
      return b.url
        ? <div style={{ aspectRatio: '16/9', background: '#111', borderRadius: 10, display: 'grid', placeItems: 'center', color: '#fff', gap: 8, fontSize: 13 }}><Icon name="play" size={28} /><span style={{ opacity: .6 }}>{b.url.slice(0, 48)}…</span></div>
        : <div style={{ aspectRatio: '16/9', background: 'var(--surface-2)', borderRadius: 10, display: 'grid', placeItems: 'center', border: '2px dashed var(--border)', color: 'var(--text-muted)', flexDirection: 'column', gap: 8 }}><Icon name="play" size={32} /><span style={{ fontSize: 13 }}>Add a video URL</span></div>;
    case 'image':
      return b.url
        ? <img src={b.url} alt={b.alt || ''} style={{ width: '100%', maxHeight: 220, objectFit: 'cover', borderRadius: 10, border: '1px solid var(--border)' }} />
        : <div style={{ height: 130, background: 'var(--surface-2)', borderRadius: 10, display: 'grid', placeItems: 'center', border: '2px dashed var(--border)', color: 'var(--text-muted)', gap: 8 }}><Icon name="layers" size={28} /><span style={{ fontSize: 13 }}>Add an image URL</span></div>;
    case 'pdf':
      return (
        <div style={{ display: 'flex', gap: 14, alignItems: 'center', background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 10, padding: '14px 18px' }}>
          <Icon name="book" size={22} style={{ color: 'var(--lime-strong)', flex: 'none' }} />
          <span style={{ fontWeight: 700, fontSize: 15 }}>{b.label || 'PDF Document'}</span>
          {!b.url && <span className="muted" style={{ fontSize: 12, marginLeft: 8 }}>(no URL set)</span>}
        </div>
      );
    case 'embed':
      return (
        <div style={{ height: 110, background: 'var(--surface-2)', borderRadius: 10, display: 'grid', placeItems: 'center', border: '2px dashed var(--border)', color: 'var(--text-muted)', fontSize: 13, gap: 6 }}>
          <Icon name="link" size={22} />
          {b.url ? <span>{b.url.slice(0, 48)}</span> : <span>Add an embed URL</span>}
        </div>
      );
    case 'mcq':
      return (
        <div style={{ background: 'var(--surface-2)', borderRadius: 10, padding: '14px 18px' }}>
          <p style={{ fontWeight: 800, fontSize: 15.5, marginBottom: 12 }}>{b.question || <span style={{ opacity: .4 }}>Quiz question…</span>}</p>
          {(b.options || []).map((o, i) => (
            <div key={i} style={{ padding: '8px 12px', marginBottom: 6, borderRadius: 8, border: '1.5px solid ' + (i === b.correct ? 'var(--lime)' : 'var(--border)'), background: i === b.correct ? 'var(--lime-soft)' : 'var(--surface)', fontSize: 14, fontWeight: i === b.correct ? 700 : 500, display: 'flex', gap: 10, alignItems: 'center' }}>
              {i === b.correct && <Icon name="check" size={14} style={{ color: 'var(--lime-strong)', flex: 'none' }} />}
              {o || <span style={{ opacity: .4 }}>Option {i + 1}</span>}
            </div>
          ))}
        </div>
      );
    case 'checklist':
      return (
        <div style={{ background: 'var(--surface-2)', borderRadius: 10, padding: '14px 18px' }}>
          {b.title && <p style={{ fontWeight: 800, marginBottom: 10, fontSize: 15.5 }}>{b.title}</p>}
          {(b.items || []).map((item, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, marginBottom: 6, alignItems: 'flex-start' }}>
              <div style={{ width: 18, height: 18, border: '2px solid var(--border)', borderRadius: 4, flex: 'none', marginTop: 2 }} />
              <span style={{ fontSize: 14.5 }}>{item || <span style={{ opacity: .4 }}>Item {i + 1}</span>}</span>
            </div>
          ))}
        </div>
      );
    case 'journal':
      return (
        <div style={{ background: 'var(--lime-soft)', borderRadius: 10, padding: '14px 18px', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <Icon name="pen" size={20} style={{ color: 'var(--lime-strong)', flex: 'none', marginTop: 2 }} />
          <div>
            <strong style={{ display: 'block', color: 'var(--lime-strong)', marginBottom: 4 }}>Reflection Journal</strong>
            <span style={{ fontSize: 14, color: 'var(--text-muted)' }}>{b.prompt || <em>No prompt set yet</em>}</span>
          </div>
        </div>
      );
    case 'discussion':
      return (
        <div style={{ background: 'var(--surface-2)', borderRadius: 10, padding: '14px 18px', display: 'flex', gap: 14, alignItems: 'center' }}>
          <Icon name="chat" size={20} style={{ color: 'var(--lime-strong)', flex: 'none' }} />
          <strong style={{ fontSize: 15 }}>Discussion Board</strong>
          <span className="muted" style={{ fontSize: 13 }}>Cohort conversation</span>
        </div>
      );
    case 'aichat':
      return (
        <div style={{ background: 'var(--surface-2)', borderRadius: 10, padding: '14px 18px', display: 'flex', gap: 14, alignItems: 'center', opacity: .7 }}>
          <Icon name="robot" size={20} style={{ color: 'var(--text-muted)', flex: 'none' }} />
          <div><strong style={{ display: 'block', fontSize: 15 }}>AI Sandbox</strong><span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Coming soon</span></div>
        </div>
      );
    case 'upload':
      return (
        <div style={{ background: 'var(--surface-2)', borderRadius: 10, padding: '14px 18px', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <Icon name="upload" size={20} style={{ color: 'var(--lime-strong)', flex: 'none', marginTop: 2 }} />
          <div><strong style={{ display: 'block', fontSize: 15 }}>{b.label || 'File Submission'}</strong><span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{b.hint}</span></div>
        </div>
      );
    case 'video-upload':
      return (
        <div style={{ background: 'var(--surface-2)', borderRadius: 10, padding: '14px 18px', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <Icon name="film" size={20} style={{ color: 'var(--lime-strong)', flex: 'none', marginTop: 2 }} />
          <div><strong style={{ display: 'block', fontSize: 15 }}>{b.label || 'Video Submission'}</strong><span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{b.hint}</span></div>
        </div>
      );
    case 'ai-opportunity-canvas':
      return (
        <div style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 12, padding: '16px 20px', display: 'flex', gap: 14, alignItems: 'center' }}>
          <Icon name="target" size={22} style={{ color: 'var(--lime-strong)', flex: 'none' }} />
          <div><strong style={{ display: 'block', fontSize: 15 }}>AI Opportunity Mapping Canvas</strong><span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Interactive backward-design worksheet — learners fill this out in the LMS</span></div>
        </div>
      );
    case 'instructor-intros': {
      const instructors = b.instructors || [];
      return (
        <div style={{ display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap' }}>
          {instructors.map((inst, i) => (
            <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 56, height: 56, borderRadius: '50%', background: inst.videoUrl ? 'var(--lime-soft)' : 'var(--surface-2)', border: '2px solid var(--lime)', display: 'grid', placeItems: 'center' }}>
                <Icon name="play" size={18} style={{ color: 'var(--lime-strong)' }} />
              </div>
              <span style={{ fontSize: 11, fontWeight: 700, color: inst.name ? 'var(--text)' : 'var(--text-muted)' }}>{inst.name || 'Instructor'}</span>
            </div>
          ))}
          <span style={{ fontSize: 12, color: 'var(--text-muted)', fontStyle: 'italic' }}>{b.heading || 'Instructor Intros'}</span>
        </div>
      );
    }
    default:
      return <div style={{ color: 'var(--text-muted)', fontSize: 13, fontStyle: 'italic' }}>Unknown block type: {b.type}</div>;
  }
}

/* ─── Block Editor Form (inline, shown when block is selected) ───── */
function BlockEditorForm({ block, onChange }) {
  const field = (label, key, opts = {}) => (
    <div style={{ marginBottom: 14 }}>
      <label style={{ display: 'block', fontSize: 11.5, fontWeight: 800, letterSpacing: '.07em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 6 }}>{label}</label>
      {opts.area
        ? <textarea value={block[key] || ''} onChange={e => onChange({ [key]: e.target.value })} rows={opts.rows || 3} style={fInputStyle} placeholder={opts.ph} />
        : <input value={block[key] || ''} onChange={e => onChange({ [key]: e.target.value })} style={fInputStyle} placeholder={opts.ph} type={opts.type || 'text'} />}
    </div>
  );

  switch (block.type) {
    case 'heading':
      return (
        <div>
          {field('Heading text', 'content', { ph: 'Section heading…' })}
          <div style={{ marginBottom: 14 }}>
            <label style={fLabelStyle}>Size</label>
            <div style={{ display: 'flex', gap: 8 }}>
              {[{ v: 2, l: 'H2 — Large' }, { v: 3, l: 'H3 — Medium' }].map(({ v, l }) => (
                <button key={v} onClick={() => onChange({ level: v })}
                  style={{ flex: 1, padding: '8px', borderRadius: 9, border: '1.5px solid ' + (block.level === v ? 'var(--lime)' : 'var(--border)'), background: block.level === v ? 'var(--lime-soft)' : 'transparent', color: block.level === v ? 'var(--lime-strong)' : 'var(--text-muted)', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>{l}</button>
              ))}
            </div>
          </div>
        </div>
      );

    case 'text':
      return field('Content', 'content', { area: true, rows: 6, ph: 'Write your paragraph here…' });

    case 'callout':
      return (
        <div>
          {field('Message', 'content', { area: true, rows: 3, ph: 'Key point, tip, or warning…' })}
          <div style={{ marginBottom: 14 }}>
            <label style={fLabelStyle}>Style</label>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {Object.entries(CALLOUT_VARIANTS).map(([k, v]) => (
                <button key={k} onClick={() => onChange({ variant: k })}
                  style={{ padding: '6px 14px', borderRadius: 8, border: '1.5px solid ' + (block.variant === k ? v.border : 'var(--border)'), background: block.variant === k ? v.bg : 'transparent', color: v.border, fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>{v.label}</button>
              ))}
            </div>
          </div>
        </div>
      );

    case 'divider':
      return <p style={{ color: 'var(--text-muted)', fontSize: 14, fontStyle: 'italic', margin: 0 }}>Horizontal rule — no settings needed.</p>;

    case 'video':
      return (
        <div>
          {field('Video URL', 'url', { ph: 'https://youtube.com/… or direct MP4 link' })}
          {field('Caption', 'caption', { ph: 'Optional caption shown below' })}
        </div>
      );

    case 'image':
      return (
        <div>
          {field('Image URL', 'url', { ph: 'https://… or Supabase storage URL' })}
          {field('Alt text', 'alt', { ph: 'Describe the image for accessibility' })}
          {field('Caption', 'caption', { ph: 'Optional caption shown below' })}
          {block.url && <img src={block.url} alt={block.alt || ''} style={{ width: '100%', borderRadius: 8, marginTop: 4, maxHeight: 180, objectFit: 'cover' }} />}
        </div>
      );

    case 'pdf':
      return (
        <div>
          {field('File URL', 'url', { ph: 'Supabase storage URL or external link' })}
          {field('Display label', 'label', { ph: 'e.g. Module 1 Reading.pdf' })}
        </div>
      );

    case 'embed':
      return (
        <div>
          {field('Embed URL', 'url', { ph: 'Google Forms, Slides, Loom, Figma, any iframe URL…' })}
          <p style={{ fontSize: 12, color: 'var(--lime-strong)', margin: '-8px 0 12px', fontWeight: 600 }}>
            💡 Google Form links are converted to embedded mode automatically.
          </p>
          {field('Height (px)', 'height', { ph: '900 for forms, 520 for slides/video' })}
          {field('Caption', 'caption', { ph: 'Optional caption shown below the embed' })}
        </div>
      );

    case 'ai-opportunity-canvas':
      return (
        <div style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 10, padding: '16px 18px' }}>
          <p style={{ margin: 0, fontSize: 14, lineHeight: 1.6 }}>This block renders the full <strong>AI Opportunity Mapping Canvas</strong> worksheet for learners to fill out directly in the LMS. Answers are auto-saved per learner on their device.</p>
          <p style={{ margin: '10px 0 0', fontSize: 13, color: 'var(--text-muted)' }}>No configuration required — add this block to the lesson and it's ready to use.</p>
        </div>
      );

    case 'instructor-intros': {
      const instructors = block.instructors || [{ name: '', title: '', videoUrl: '' }];
      const update = (idx, patch) => {
        const next = instructors.map((inst, i) => i === idx ? { ...inst, ...patch } : inst);
        onChange({ instructors: next });
      };
      return (
        <div>
          {field('Section heading', 'heading', { ph: 'Meet Your Instructors' })}
          <label style={fLabelStyle}>Instructors</label>
          {instructors.map((inst, idx) => (
            <div key={idx} style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 10, padding: '12px 14px', marginBottom: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                <span style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '.06em' }}>Instructor {idx + 1}</span>
                {instructors.length > 1 && (
                  <button onClick={() => onChange({ instructors: instructors.filter((_, i) => i !== idx) })}
                    style={{ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', fontSize: 18, lineHeight: 1, padding: 2 }}>×</button>
                )}
              </div>
              <input value={inst.name} onChange={e => update(idx, { name: e.target.value })} style={{ ...fInputStyle, marginBottom: 8 }} placeholder="Full name" />
              <input value={inst.title} onChange={e => update(idx, { title: e.target.value })} style={{ ...fInputStyle, marginBottom: 8 }} placeholder="Title / role (e.g. CEO)" />
              <input value={inst.org || ''} onChange={e => update(idx, { org: e.target.value })} style={{ ...fInputStyle, marginBottom: 8 }} placeholder="Organization (e.g. Edstutia)" />
              <input value={inst.videoUrl} onChange={e => update(idx, { videoUrl: e.target.value })} style={{ ...fInputStyle, marginBottom: 8 }} placeholder="Video URL (Synthesia, Loom, YouTube…)" />
              {inst.videoUrl?.includes('share.synthesia.io') && !inst.videoUrl?.includes('/embeds/') && (
                <p style={{ margin: '-4px 0 8px', fontSize: 11, color: 'var(--lime-strong)', fontWeight: 600 }}>💡 Synthesia link detected — will auto-embed.</p>
              )}
              <input value={inst.imageUrl || ''} onChange={e => update(idx, { imageUrl: e.target.value })} style={fInputStyle} placeholder="Photo URL (Supabase Storage public URL)" />
              {inst.imageUrl && (
                <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <img src={inst.imageUrl} alt="" style={{ width: 40, height: 40, borderRadius: '50%', objectFit: 'cover', objectPosition: 'center top', border: '2px solid var(--border)' }} onError={e => { e.target.style.display = 'none'; }} />
                  <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>Preview</span>
                </div>
              )}
            </div>
          ))}
          <button onClick={() => onChange({ instructors: [...instructors, { name: '', title: '', videoUrl: '' }] })}
            style={{ width: '100%', padding: '8px', borderRadius: 9, border: '1.5px dashed var(--border)', background: 'transparent', color: 'var(--text-muted)', cursor: 'pointer', fontSize: 13, fontWeight: 700, marginTop: 2 }}>
            + Add Instructor
          </button>
        </div>
      );
    }

    case 'mcq': {
      const opts = block.options || [];
      return (
        <div>
          {field('Question', 'question', { ph: 'What is the question?' })}
          <div style={{ marginBottom: 14 }}>
            <label style={fLabelStyle}>Options <span style={{ opacity: .55, fontWeight: 600 }}>— click ✓ to mark correct</span></label>
            {opts.map((opt, i) => (
              <div key={i} style={{ display: 'flex', gap: 8, marginBottom: 8, alignItems: 'center' }}>
                <button onClick={() => onChange({ correct: i })}
                  title="Mark as correct answer"
                  style={{ width: 32, height: 32, borderRadius: 8, border: '1.5px solid ' + (block.correct === i ? 'var(--lime)' : 'var(--border)'), background: block.correct === i ? 'var(--lime-soft)' : 'transparent', color: 'var(--lime-strong)', cursor: 'pointer', display: 'grid', placeItems: 'center', flex: 'none' }}>
                  <Icon name="check" size={14} />
                </button>
                <input value={opt} onChange={e => { const o = [...opts]; o[i] = e.target.value; onChange({ options: o }); }}
                  style={{ ...fInputStyle, flex: 1 }} placeholder={`Option ${i + 1}`} />
                {opts.length > 2 && (
                  <button onClick={() => { const o = opts.filter((_, j) => j !== i); onChange({ options: o, correct: block.correct >= o.length ? 0 : block.correct }); }}
                    style={{ width: 32, height: 32, borderRadius: 8, border: '1px solid var(--border)', background: 'transparent', color: '#E0584F', cursor: 'pointer', display: 'grid', placeItems: 'center', flex: 'none' }}>
                    <Icon name="minus" size={14} />
                  </button>
                )}
              </div>
            ))}
            <button onClick={() => onChange({ options: [...opts, ''] })}
              style={{ padding: '7px 14px', border: '1px dashed var(--border)', borderRadius: 9, background: 'none', color: 'var(--text-muted)', fontWeight: 700, cursor: 'pointer', fontSize: 13 }}>
              + Add option
            </button>
          </div>
          {field('Explanation', 'explanation', { area: true, rows: 2, ph: 'Why is this the correct answer? Shown after the learner submits.' })}
        </div>
      );
    }

    case 'checklist': {
      const items = block.items || [];
      return (
        <div>
          {field('Checklist title', 'title', { ph: 'e.g. Before you move on…' })}
          <div style={{ marginBottom: 14 }}>
            <label style={fLabelStyle}>Items</label>
            {items.map((item, i) => (
              <div key={i} style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
                <input value={item} onChange={e => { const it = [...items]; it[i] = e.target.value; onChange({ items: it }); }}
                  style={{ ...fInputStyle, flex: 1 }} placeholder={`Step ${i + 1}`} />
                {items.length > 1 && (
                  <button onClick={() => onChange({ items: items.filter((_, j) => j !== i) })}
                    style={{ width: 32, height: 32, borderRadius: 8, border: '1px solid var(--border)', background: 'transparent', color: '#E0584F', cursor: 'pointer', display: 'grid', placeItems: 'center', flex: 'none' }}>
                    <Icon name="minus" size={14} />
                  </button>
                )}
              </div>
            ))}
            <button onClick={() => onChange({ items: [...items, ''] })}
              style={{ padding: '7px 14px', border: '1px dashed var(--border)', borderRadius: 9, background: 'none', color: 'var(--text-muted)', fontWeight: 700, cursor: 'pointer', fontSize: 13 }}>
              + Add item
            </button>
          </div>
        </div>
      );
    }

    case 'journal':
      return field('Reflection prompt', 'prompt', { area: true, rows: 3, ph: 'What question should learners reflect on?' });

    case 'upload':
      return (
        <div>
          {field('Label', 'label', { ph: 'e.g. Submit your assignment' })}
          {field('Hint', 'hint', { ph: 'e.g. PDF or DOCX, up to 50 MB' })}
        </div>
      );

    case 'video-upload':
      return (
        <div>
          {field('Label', 'label', { ph: 'e.g. Submit your video reflection' })}
          {field('Hint', 'hint', { ph: 'e.g. MP4 or MOV, up to 500 MB' })}
        </div>
      );

    default:
      return <p style={{ color: 'var(--text-muted)', fontSize: 14, margin: 0 }}>No settings for this block type.</p>;
  }
}

const fInputStyle = { width: '100%', padding: '9px 12px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--bg)', color: 'var(--text)', fontSize: 14.5, fontFamily: 'var(--font-body)', outline: 'none', boxSizing: 'border-box' };
const fLabelStyle = { display: 'block', fontSize: 11.5, fontWeight: 800, letterSpacing: '.07em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 6 };

/* ─── Setting field helper ───────────────────────────────────────── */
function SF({ label, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label style={fLabelStyle}>{label}</label>
      {children}
    </div>
  );
}
const sInput = { ...fInputStyle, background: 'var(--surface-2)' };

/* ─── Main LessonEditor ──────────────────────────────────────────── */
function LessonEditor({ lessonId, go }) {
  const E = window.EDSTUTIA;

  const [lesson, setLesson] = eState(null);
  const [mod, setMod] = eState(null);
  const [blocks, setBlocks] = eState([]);
  const [meta, setMeta] = eState({ title: '', summary: '', minutes: 15, type: 'ASYNCHRONOUS', status: 'draft' });
  const [selectedId, setSelectedId] = eState(null);
  const [saveStatus, setSaveStatus] = eState('saved');
  const [loading, setLoading] = eState(true);
  const [dragIdx, setDragIdx] = eState(null);
  const [dragOver, setDragOver] = eState(null);
  const saveTimer = eRef(null);

  /* Load lesson */
  eEffect(() => {
    async function load() {
      if (window.supabaseClient) {
        const { data: l } = await window.supabaseClient
          .from('lessons')
          .select('*, modules(*)')
          .eq('id', lessonId)
          .maybeSingle();
        if (l) {
          setLesson(l);
          setMod(l.modules);
          setBlocks(l.content_blocks || []);
          setMeta({ title: l.title || '', summary: l.summary || '', minutes: l.minutes || 15, type: l.type || 'ASYNCHRONOUS', status: l.status || 'draft' });
          setLoading(false);
          return;
        }
      }
      // Fall back to static data.js
      for (const m of E.modules || []) {
        const l = (m.lessons || []).find(x => x.id === lessonId);
        if (l) {
          setLesson(l);
          setMod(m);
          setBlocks(l.content_blocks || []);
          setMeta({ title: l.title || '', summary: l.summary || '', minutes: l.minutes || 15, type: l.type || 'ASYNCHRONOUS', status: l.status || 'draft' });
          setLoading(false);
          return;
        }
      }
      setLoading(false);
    }
    load();
  }, [lessonId]);

  /* Debounced save */
  const scheduleSave = (nextBlocks, nextMeta) => {
    setSaveStatus('unsaved');
    if (saveTimer.current) clearTimeout(saveTimer.current);
    saveTimer.current = setTimeout(() => persist(nextBlocks, nextMeta), 1800);
  };

  const persist = async (bs, m) => {
    if (!lesson) return;
    setSaveStatus('saving');
    if (window.supabaseClient && !String(lesson.id).match(/^m\d/)) {
      const { error } = await window.supabaseClient.from('lessons').update({
        content_blocks: bs,
        title: m.title,
        summary: m.summary,
        minutes: Number(m.minutes) || 15,
        type: m.type,
        status: m.status,
      }).eq('id', lesson.id);
      if (error) { setSaveStatus('error'); return; }
    }
    // Keep local EDSTUTIA data in sync
    for (const mod of (E.modules || [])) {
      const l = (mod.lessons || []).find(x => x.id === lessonId);
      if (l) { Object.assign(l, { content_blocks: bs, ...m }); break; }
    }
    setSaveStatus('saved');
  };

  const updateBlocks = (next) => { setBlocks(next); scheduleSave(next, meta); };
  const updateMeta = (patch) => { const next = { ...meta, ...patch }; setMeta(next); scheduleSave(blocks, next); };

  /* Block operations */
  const addBlock = (type) => {
    const id = crypto.randomUUID();
    const b = { id, type, ...BLOCK_DEFAULTS[type] };
    const next = [...blocks, b];
    updateBlocks(next);
    setSelectedId(id);
    setTimeout(() => document.getElementById('block-' + id)?.scrollIntoView({ behavior: 'smooth', block: 'center' }), 80);
  };

  const updateBlock = (id, patch) => updateBlocks(blocks.map(b => b.id === id ? { ...b, ...patch } : b));
  const deleteBlock = (id) => { updateBlocks(blocks.filter(b => b.id !== id)); if (selectedId === id) setSelectedId(null); };
  const moveBlock = (from, to) => {
    const next = [...blocks];
    const [m] = next.splice(from, 1);
    next.splice(to, 0, m);
    updateBlocks(next);
  };

  /* Drag-and-drop reorder */
  const handleDrop = (targetIdx) => {
    if (dragIdx === null || dragIdx === targetIdx) { setDragIdx(null); setDragOver(null); return; }
    moveBlock(dragIdx, targetIdx);
    setDragIdx(null); setDragOver(null);
  };

  /* Publish / unpublish (immediate save) */
  const togglePublish = async () => {
    const newStatus = meta.status === 'published' ? 'draft' : 'published';
    const nextMeta = { ...meta, status: newStatus };
    setMeta(nextMeta);
    if (saveTimer.current) clearTimeout(saveTimer.current);
    await persist(blocks, nextMeta);
  };

  if (loading) return <div style={{ padding: 60, textAlign: 'center', color: 'var(--text-muted)' }}>Loading editor…</div>;
  if (!lesson) return <div style={{ padding: 60, textAlign: 'center', color: '#E0584F' }}>Lesson not found. <button className="btn btn-ghost btn-sm" onClick={() => go({ name: 'curriculum' })}>Back to Curriculum</button></div>;

  const isPub = meta.status === 'published';
  const sel = blocks.find(b => b.id === selectedId);

  const saveLabel = { saved: '✓ Saved', saving: '↻ Saving…', unsaved: '● Unsaved', error: '✕ Save failed' };
  const saveColor = { saved: 'var(--lime-strong)', saving: 'var(--text-muted)', unsaved: '#E67E22', error: '#E0584F' };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', overflow: 'hidden', background: 'var(--bg)' }}>

      {/* ── Top bar ────────────────────────────────────────────────── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '10px 20px', background: 'var(--surface)', borderBottom: '1px solid var(--border)', flexShrink: 0, zIndex: 50 }}>
        <button onClick={() => go({ name: 'curriculum', focus: mod?.id })} className="btn btn-ghost btn-sm" style={{ flex: 'none' }}>
          <Icon name="chevron" size={15} style={{ transform: 'rotate(180deg)' }} /> Curriculum
        </button>

        <div style={{ width: 1, height: 24, background: 'var(--border)' }} />

        {/* Editable title */}
        <input value={meta.title} onChange={e => updateMeta({ title: e.target.value })}
          style={{ flex: 1, border: 'none', background: 'none', fontSize: 17, fontWeight: 800, fontFamily: 'var(--font-head)', color: 'var(--text)', outline: 'none', minWidth: 0 }}
          placeholder="Lesson title…" />

        {/* Save indicator */}
        <span style={{ fontSize: 13, fontWeight: 700, color: saveColor[saveStatus], flex: 'none', whiteSpace: 'nowrap' }}>{saveLabel[saveStatus]}</span>

        <div style={{ width: 1, height: 24, background: 'var(--border)' }} />

        {/* Status toggle */}
        <div style={{ display: 'flex', borderRadius: 9, border: '1.5px solid var(--border)', overflow: 'hidden', flex: 'none' }}>
          {['draft', 'published'].map(s => (
            <button key={s} onClick={() => { if (meta.status !== s) togglePublish(); }}
              style={{ padding: '7px 14px', border: 'none', background: meta.status === s ? (s === 'published' ? 'var(--lime)' : 'var(--surface-2)') : 'transparent', color: meta.status === s ? (s === 'published' ? '#14180D' : 'var(--text)') : 'var(--text-muted)', fontWeight: 700, fontSize: 13, cursor: meta.status === s ? 'default' : 'pointer', transition: 'all .15s', whiteSpace: 'nowrap' }}>
              {s === 'published' ? '✓ Published' : '◌ Draft'}
            </button>
          ))}
        </div>

        <button onClick={() => go({ name: 'lesson', id: lessonId })} className="btn btn-ghost btn-sm" style={{ flex: 'none' }}>
          <Icon name="eye" size={16} /> Preview
        </button>
      </div>

      {/* ── Body ─────────────────────────────────────────────────────── */}
      <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>

        {/* ── Left: Block palette ────────────────────────────────── */}
        <aside style={{ width: 214, background: 'var(--surface)', borderRight: '1px solid var(--border)', overflowY: 'auto', padding: '18px 10px', flexShrink: 0 }}>
          <p style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--text-muted)', padding: '0 6px 12px', margin: 0 }}>Add block</p>
          {EDITOR_PALETTE.map(({ group, items }) => (
            <div key={group} style={{ marginBottom: 18 }}>
              <p style={{ fontSize: 10, fontWeight: 800, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--text-muted)', padding: '0 6px 6px', opacity: .7, margin: 0 }}>{group}</p>
              {items.map(item => (
                <button key={item.type} onClick={() => addBlock(item.type)} title={item.hint}
                  style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 9, border: 'none', background: 'none', cursor: 'pointer', color: 'var(--text)', fontSize: 13.5, fontWeight: 600, textAlign: 'left', width: '100%', transition: 'background .1s', marginBottom: 2 }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'none'}>
                  <span style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--surface-2)', display: 'grid', placeItems: 'center', flex: 'none', color: 'var(--lime-strong)' }}>
                    <Icon name={item.icon} size={15} />
                  </span>
                  {item.label}
                </button>
              ))}
            </div>
          ))}
        </aside>

        {/* ── Center: Canvas ─────────────────────────────────────── */}
        <main style={{ flex: 1, overflowY: 'auto', background: 'var(--bg)' }}
          onClick={() => setSelectedId(null)}>
          <div style={{ maxWidth: 740, margin: '0 auto', padding: '32px 32px 120px' }}>

            {/* Draft warning */}
            {!isPub && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 18px', background: 'color-mix(in srgb, #E67E22 10%, var(--surface))', borderRadius: 10, marginBottom: 28, border: '1px solid #E67E22' }}>
                <Icon name="slash" size={18} style={{ color: '#E67E22', flex: 'none' }} />
                <p style={{ margin: 0, fontWeight: 700, fontSize: 14, color: '#E67E22', flex: 1 }}>Draft — hidden from learners until published.</p>
                <button onClick={togglePublish} style={{ padding: '5px 14px', background: '#E67E22', color: '#fff', border: 'none', borderRadius: 8, fontWeight: 700, fontSize: 13, cursor: 'pointer', flex: 'none' }}>Publish now</button>
              </div>
            )}

            {/* Module + lesson heading */}
            <div style={{ marginBottom: 4 }}>
              <span className="eyebrow">{mod?.title || 'Module'}</span>
            </div>
            <h1 style={{ fontSize: 34, marginBottom: meta.summary ? 10 : 28, lineHeight: 1.15 }}>{meta.title || <span style={{ opacity: .3 }}>Untitled lesson</span>}</h1>
            {meta.summary && <p style={{ fontSize: 18, color: 'var(--text-muted)', marginBottom: 28, lineHeight: 1.5 }}>{meta.summary}</p>}

            {/* Empty state */}
            {blocks.length === 0 && (
              <div style={{ padding: '60px 32px', border: '2px dashed var(--border)', borderRadius: 16, textAlign: 'center', color: 'var(--text-muted)' }}>
                <Icon name="plus" size={40} style={{ marginBottom: 14, opacity: .35 }} />
                <p style={{ fontWeight: 700, fontSize: 17, marginBottom: 8 }}>This lesson is empty</p>
                <p style={{ fontSize: 15 }}>Click a block type in the left panel to start building.</p>
              </div>
            )}

            {/* Block list */}
            {blocks.map((b, i) => {
              const isSel = selectedId === b.id;
              const isDragging = dragIdx === i;
              const dropAbove = dragOver === i && dragIdx !== null && dragIdx > i;
              const dropBelow = dragOver === i && dragIdx !== null && dragIdx < i;

              return (
                <div key={b.id} id={'block-' + b.id}
                  draggable
                  onDragStart={e => { setDragIdx(i); e.dataTransfer.effectAllowed = 'move'; }}
                  onDragOver={e => { e.preventDefault(); setDragOver(i); }}
                  onDragLeave={() => setDragOver(null)}
                  onDrop={() => handleDrop(i)}
                  onDragEnd={() => { setDragIdx(null); setDragOver(null); }}
                  style={{ opacity: isDragging ? 0.3 : 1, borderTop: dropAbove ? '3px solid var(--lime)' : '3px solid transparent', borderBottom: dropBelow ? '3px solid var(--lime)' : '3px solid transparent', marginBottom: 2, transition: 'opacity .12s' }}>

                  <div onClick={e => { e.stopPropagation(); setSelectedId(isSel ? null : b.id); }}
                    className="block-canvas-item"
                    style={{ position: 'relative', padding: '14px 16px', borderRadius: 12, border: '1.5px solid ' + (isSel ? 'var(--lime)' : 'transparent'), background: isSel ? 'var(--surface)' : 'transparent', cursor: 'default', transition: 'border-color .12s, background .12s', boxShadow: isSel ? 'var(--shadow)' : 'none' }}>

                    {/* Type chip (selected only) */}
                    {isSel && (
                      <div style={{ position: 'absolute', top: -1, left: 16, transform: 'translateY(-50%)', background: 'var(--lime)', color: '#14180D', fontSize: 10, fontWeight: 800, letterSpacing: '.1em', textTransform: 'uppercase', padding: '2px 10px', borderRadius: 99 }}>
                        {b.type.replace(/-/g, ' ')}
                      </div>
                    )}

                    {/* Hover controls */}
                    <div className="block-hover-controls" style={{ position: 'absolute', right: 10, top: 10, display: 'flex', gap: 3, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 3, opacity: 0, transition: 'opacity .12s', pointerEvents: 'none' }}>
                      <button onClick={e => { e.stopPropagation(); if (i > 0) moveBlock(i, i - 1); }} disabled={i === 0} style={ctrlBtn} title="Move up"><Icon name="chevdown" size={13} style={{ transform: 'rotate(180deg)' }} /></button>
                      <button onClick={e => { e.stopPropagation(); if (i < blocks.length - 1) moveBlock(i, i + 1); }} disabled={i === blocks.length - 1} style={ctrlBtn} title="Move down"><Icon name="chevdown" size={13} /></button>
                      <div style={{ width: 1, background: 'var(--border)', margin: '3px 2px' }} />
                      <button onClick={e => { e.stopPropagation(); deleteBlock(b.id); }} style={{ ...ctrlBtn, color: '#E0584F' }} title="Delete block"><Icon name="trash" size={13} /></button>
                    </div>

                    {/* Drag grip */}
                    <div style={{ position: 'absolute', left: -22, top: '50%', transform: 'translateY(-50%)', color: 'var(--border-strong)', opacity: 0, cursor: 'grab', transition: 'opacity .12s' }} className="drag-grip">
                      <Icon name="drag" size={16} />
                    </div>

                    {/* Block content */}
                    <BlockPreview b={b} />

                    {/* Inline edit form */}
                    {isSel && (
                      <div onClick={e => e.stopPropagation()} style={{ marginTop: 16, padding: '18px 20px', background: 'var(--bg)', borderRadius: 12, border: '1.5px solid var(--border)' }}>
                        <BlockEditorForm block={b} onChange={patch => updateBlock(b.id, patch)} />
                      </div>
                    )}
                  </div>
                </div>
              );
            })}

            {/* Drop zone at end */}
            {blocks.length > 0 && (
              <div
                onDragOver={e => { e.preventDefault(); setDragOver('end'); }}
                onDragLeave={() => setDragOver(null)}
                onDrop={() => { if (dragIdx !== null) { moveBlock(dragIdx, blocks.length - 1); setDragIdx(null); setDragOver(null); } }}
                style={{ height: 44, marginTop: 6, borderRadius: 12, border: '2px dashed ' + (dragOver === 'end' ? 'var(--lime)' : 'transparent'), display: 'grid', placeItems: 'center', color: 'var(--lime-strong)', fontSize: 13, fontWeight: 700, background: dragOver === 'end' ? 'var(--lime-soft)' : 'transparent', transition: 'all .15s' }}>
                {dragOver === 'end' && 'Drop here to move to end'}
              </div>
            )}

            {/* Quick-add text */}
            <div style={{ marginTop: 24, textAlign: 'center' }}>
              <button onClick={() => addBlock('text')}
                style={{ padding: '8px 22px', border: '1.5px dashed var(--border)', borderRadius: 10, background: 'none', color: 'var(--text-muted)', cursor: 'pointer', fontWeight: 700, fontSize: 14, transition: 'all .12s' }}
                onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--lime)'; e.currentTarget.style.color = 'var(--lime-strong)'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.color = 'var(--text-muted)'; }}>
                <Icon name="plus" size={15} /> Add text block
              </button>
            </div>
          </div>
        </main>

        {/* ── Right: Settings panel ──────────────────────────────── */}
        <aside style={{ width: 270, background: 'var(--surface)', borderLeft: '1px solid var(--border)', overflowY: 'auto', padding: '22px 18px', flexShrink: 0 }}>
          <p style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 20 }}>Lesson settings</p>

          <SF label="Summary / description">
            <textarea value={meta.summary} onChange={e => updateMeta({ summary: e.target.value })} rows={3} style={{ ...sInput, resize: 'vertical' }} placeholder="Shown to learners in the curriculum view…" />
          </SF>

          <SF label="Duration">
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <input type="number" value={meta.minutes} onChange={e => updateMeta({ minutes: e.target.value })} min={1} max={480} style={{ ...sInput, width: 80 }} />
              <span className="muted" style={{ fontSize: 13 }}>minutes</span>
            </div>
          </SF>

          <SF label="Lesson type">
            <select value={meta.type} onChange={e => updateMeta({ type: e.target.value })} style={{ ...sInput, appearance: 'auto', cursor: 'pointer' }}>
              <option value="ASYNCHRONOUS">Async — self-paced</option>
              <option value="SYNCHRONOUS">Sync — live session</option>
              <option value="QUIZ">Quiz / Assessment</option>
            </select>
          </SF>

          {/* Block summary */}
          <div style={{ padding: '14px 16px', background: 'var(--surface-2)', borderRadius: 10, border: '1px solid var(--border)', marginBottom: 20 }}>
            <p style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 12 }}>Content summary</p>
            {[
              { label: 'Total blocks', val: blocks.length },
              { label: 'Videos', val: blocks.filter(b => b.type === 'video').length },
              { label: 'Quiz questions', val: blocks.filter(b => b.type === 'mcq').length },
              { label: 'Interactive', val: blocks.filter(b => ['journal', 'discussion', 'aichat', 'upload', 'video-upload', 'checklist'].includes(b.type)).length },
            ].map(row => (
              <div key={row.label} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, marginBottom: 7 }}>
                <span className="muted">{row.label}</span>
                <strong>{row.val}</strong>
              </div>
            ))}
          </div>

          {/* Block outline / jump-to */}
          {blocks.length > 0 && (
            <div style={{ marginBottom: 20 }}>
              <p style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 10 }}>Outline</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
                {blocks.map((b, i) => (
                  <button key={b.id} onClick={() => { setSelectedId(b.id); document.getElementById('block-' + b.id)?.scrollIntoView({ behavior: 'smooth', block: 'center' }); }}
                    style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 10px', borderRadius: 8, border: 'none', background: selectedId === b.id ? 'var(--lime-soft)' : 'transparent', cursor: 'pointer', textAlign: 'left', fontSize: 12.5, fontWeight: selectedId === b.id ? 700 : 500, color: selectedId === b.id ? 'var(--lime-strong)' : 'var(--text-muted)', transition: 'background .1s' }}
                    onMouseEnter={e => { if (selectedId !== b.id) e.currentTarget.style.background = 'var(--bg-2)'; }}
                    onMouseLeave={e => { if (selectedId !== b.id) e.currentTarget.style.background = 'transparent'; }}>
                    <Icon name={EDITOR_PALETTE.flatMap(g => g.items).find(x => x.type === b.type)?.icon || 'pen'} size={13} style={{ flex: 'none' }} />
                    <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>
                      {b.type === 'heading' ? (b.content || 'Heading') : b.type === 'text' ? (b.content?.slice(0, 28) + (b.content?.length > 28 ? '…' : '') || 'Paragraph') : b.type.replace(/-/g, ' ')}
                    </span>
                    <span style={{ opacity: .4, fontWeight: 600 }}>#{i + 1}</span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Danger zone */}
          <div style={{ paddingTop: 18, borderTop: '1px solid var(--border)' }}>
            <p style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.08em', textTransform: 'uppercase', color: '#E0584F', marginBottom: 10 }}>Danger zone</p>
            <button onClick={() => { if (confirm('Clear all blocks? This cannot be undone.')) { updateBlocks([]); setSelectedId(null); } }}
              className="btn btn-ghost btn-sm"
              style={{ width: '100%', justifyContent: 'center', color: '#E0584F', borderColor: 'rgba(224,88,79,.3)', fontSize: 13 }}>
              <Icon name="trash" size={14} /> Clear all blocks
            </button>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* Block canvas hover styles injected once */
(function injectEditorStyles() {
  if (document.getElementById('editor-styles')) return;
  const s = document.createElement('style');
  s.id = 'editor-styles';
  s.textContent = `
    .block-canvas-item:hover { background: var(--surface-2) !important; }
    .block-canvas-item:hover .block-hover-controls { opacity: 1 !important; pointer-events: auto !important; }
    .block-canvas-item:hover .drag-grip { opacity: 1 !important; }
    .block-hover-controls button:hover { background: var(--bg-2) !important; }
    .block-hover-controls button:disabled { opacity: .3; cursor: not-allowed; }
  `;
  document.head.appendChild(s);
})();

const ctrlBtn = { width: 26, height: 26, border: 'none', background: 'none', cursor: 'pointer', borderRadius: 6, color: 'var(--text-muted)', display: 'grid', placeItems: 'center' };

window.LessonEditor = LessonEditor;
window.CALLOUT_VARIANTS = CALLOUT_VARIANTS;
