// Surface — Courses home (org dashboard with course grid)

function SurfaceHome({ orgId, onOpenCourse, onNewCourse, onSwitchOrg }) {
  const org = window.SAMPLE_ORGS.find(o => o.id === orgId) || window.SAMPLE_ORGS[0];
  const courses = window.SAMPLE_COURSES_LIST.filter(c => c.org === orgId);
  const [filter, setFilter] = React.useState('all');
  const [view, setView] = React.useState('grid');

  const counts = {
    all: courses.length,
    'in-progress': courses.filter(c => c.status === 'in-progress').length,
    shipped: courses.filter(c => c.status === 'shipped').length,
    archived: courses.filter(c => c.status === 'archived').length,
  };
  const filtered = filter === 'all' ? courses : courses.filter(c => c.status === filter);

  return (
    <div style={{ height: '100%', background: 'var(--bg)', overflowY: 'auto' }}
         data-screen-label="Home · Courses overview">
      {/* Org banner */}
      <OrgBanner org={org} onSwitch={onSwitchOrg} />

      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '24px 28px 40px' }}>
        {/* Filter + actions */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
          <h2 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Courses</h2>
          <div style={{
            display: 'flex', gap: 2, padding: 3,
            background: 'var(--surface)', borderRadius: 'var(--radius)',
            border: '1px solid var(--border)', marginLeft: 8,
          }}>
            {[
              ['all', 'All'],
              ['in-progress', 'In progress'],
              ['shipped', 'Shipped'],
              ['archived', 'Archived'],
            ].map(([k, l]) => (
              <button key={k} onClick={() => setFilter(k)}
                style={{
                  padding: '5px 10px', border: 0, borderRadius: 4,
                  background: filter === k ? 'var(--surface-inset)' : 'transparent',
                  color: filter === k ? 'var(--text)' : 'var(--text-muted)',
                  fontSize: 12, fontWeight: filter === k ? 600 : 500,
                  fontFamily: 'inherit', cursor: 'default',
                  display: 'inline-flex', alignItems: 'center', gap: 5,
                }}>
                {l}
                <span style={{ fontSize: 10, color: 'var(--text-faint)',
                  fontFamily: 'var(--font-mono)' }}>{counts[k]}</span>
              </button>
            ))}
          </div>
          <div style={{ flex: 1 }} />
          <div style={{
            display: 'flex', gap: 1, padding: 1,
            background: 'var(--surface)', borderRadius: 'var(--radius)',
            border: '1px solid var(--border)',
          }}>
            <button onClick={() => setView('grid')} className="btn sm ghost"
              style={{ height: 26, padding: '0 8px',
                background: view === 'grid' ? 'var(--surface-inset)' : 'transparent' }}>
              <I.Grid size={12} />
            </button>
            <button onClick={() => setView('list')} className="btn sm ghost"
              style={{ height: 26, padding: '0 8px',
                background: view === 'list' ? 'var(--surface-inset)' : 'transparent' }}>
              <I.ListChecks size={12} />
            </button>
          </div>
          <button className="btn sm primary" onClick={onNewCourse}><I.Plus size={12} />New course</button>
        </div>

        {/* Course grid / list */}
        {view === 'grid' ? (
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14,
          }}>
            {filtered.map(c => <CourseCard key={c.id} course={c} org={org} onOpen={() => onOpenCourse(c)} />)}
          </div>
        ) : (
          <div className="card" style={{ padding: 0 }}>
            <div style={{
              display: 'grid', gridTemplateColumns: '32px 1fr 100px 140px 110px 140px 80px 40px',
              gap: 14, padding: '10px 14px', fontSize: 11, color: 'var(--text-muted)',
              fontWeight: 600, letterSpacing: '.04em', textTransform: 'uppercase',
              borderBottom: '1px solid var(--border)',
            }}>
              <span></span>
              <span>Course</span>
              <span>Topic</span>
              <span>Status</span>
              <span>Languages</span>
              <span>Last saved · editor</span>
              <span>Issues</span>
              <span></span>
            </div>
            {filtered.map(c => <CourseListRow key={c.id} course={c} onOpen={() => onOpenCourse(c)} />)}
          </div>
        )}
      </div>
    </div>
  );
}

// ── OrgBanner ──────────────────────────────────────────────────────────────
function OrgBanner({ org, onSwitch }) {
  return (
    <div style={{
      background: `linear-gradient(135deg, ${org.color[0]} 0%, ${org.color[1]} 100%)`,
      color: '#fff', padding: '28px 0',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* subtle pattern */}
      <svg style={{ position: 'absolute', right: -40, top: -40, opacity: 0.07 }}
           width="320" height="320" viewBox="0 0 100 100">
        <defs>
          <pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse">
            <path d="M 10 0 L 0 0 0 10" fill="none" stroke="white" strokeWidth="0.5"/>
          </pattern>
        </defs>
        <rect width="100" height="100" fill="url(#grid)"/>
      </svg>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 28px',
        display: 'flex', alignItems: 'center', gap: 20 }}>
        <OrgGlyph org={org} size={56} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.08em',
            textTransform: 'uppercase', opacity: 0.7, marginBottom: 4 }}>
            Organization
          </div>
          <h1 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: '-.01em' }}>
            {org.full}
          </h1>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'flex-end' }}>
          <span style={{
            padding: '3px 8px', fontSize: 11, fontWeight: 600,
            background: 'rgba(255,255,255,0.18)', borderRadius: 4,
            letterSpacing: '.04em', textTransform: 'uppercase',
          }}>You · Senior Editor</span>
          <span style={{ fontSize: 12, opacity: 0.8 }}>Lisa Park · lisa@{org.id}.com</span>
        </div>
      </div>
    </div>
  );
}

function OrgGlyph({ org, size = 36 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: size > 40 ? 12 : 8,
      background: `linear-gradient(135deg, ${org.color[0]}, ${org.color[1]})`,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      color: '#fff', fontWeight: 700, fontSize: size > 40 ? 22 : 13,
      letterSpacing: org.glyph.length > 1 ? '-.02em' : 0,
      boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.2), 0 1px 3px rgba(0,0,0,0.2)',
    }}>{org.glyph}</div>
  );
}

function Stat({ label, value }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <span style={{ fontSize: 17, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{value}</span>
      <span style={{ fontSize: 10.5, opacity: 0.65, letterSpacing: '.04em',
        textTransform: 'uppercase', fontWeight: 600 }}>{label}</span>
    </div>
  );
}

function StatCard({ icon, label, value, sub, tone }) {
  const Icon = window.I[icon] || window.I.Hash;
  const toneColor = tone === 'warning' ? 'var(--warning)'
    : tone === 'accent' ? 'var(--accent)' : 'var(--text-muted)';
  const toneBg = tone === 'warning' ? 'var(--warning-bg)'
    : tone === 'accent' ? 'var(--accent-bg)' : 'var(--surface-inset)';
  return (
    <div className="card" style={{ padding: 14, background: 'var(--surface)' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
        <span style={{
          width: 32, height: 32, borderRadius: 8, background: toneBg,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          color: toneColor,
        }}><Icon size={16} /></span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>{label}</div>
          <div style={{ fontSize: 22, fontWeight: 600, lineHeight: 1.1,
            fontVariantNumeric: 'tabular-nums', color: 'var(--text)' }}>{value}</div>
          <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>{sub}</div>
        </div>
      </div>
    </div>
  );
}

// ── CourseCard ─────────────────────────────────────────────────────────────
function CourseCard({ course: c, org, onOpen }) {
  return (
    <button onClick={onOpen} className="focusable"
      style={{
        display: 'block', width: '100%', textAlign: 'left',
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 'var(--radius-md)', overflow: 'hidden',
        cursor: 'default', fontFamily: 'inherit', color: 'var(--text)',
        padding: 0, transition: 'border-color 150ms, box-shadow 150ms, transform 150ms',
      }}
      onMouseOver={e => { e.currentTarget.style.borderColor = 'var(--border-strong)';
        e.currentTarget.style.boxShadow = 'var(--shadow-md)'; }}
      onMouseOut={e => { e.currentTarget.style.borderColor = 'var(--border)';
        e.currentTarget.style.boxShadow = 'none'; }}>
      <CourseCover course={c} org={org} />
      <div style={{ padding: '12px 14px' }}>
        <h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 600,
          color: 'var(--text)', lineHeight: 1.3 }}>{c.title}</h3>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8,
          marginTop: 10, fontSize: 11.5, color: 'var(--text-muted)' }}>
          <span>{c.modules} modules</span>
          <span>·</span>
          <span>{c.layouts} layouts</span>
          <div style={{ flex: 1 }} />
          <span style={{ display: 'inline-flex', gap: 1, fontSize: 13 }}>
            {c.langs.slice(0, 4).map(l => (
              <span key={l} style={{ lineHeight: 1 }}>{LANG_FLAGS[l]}</span>
            ))}
            {c.langs.length > 4 && <span style={{ fontSize: 10, color: 'var(--text-faint)',
              alignSelf: 'center', marginLeft: 2 }}>+{c.langs.length - 4}</span>}
          </span>
        </div>
      </div>
    </button>
  );
}

function CourseCover({ course: c, org }) {
  // Uniform org-colored thumbnail. Minimal — just the org glyph + brand strip.
  return (
    <div style={{
      height: 80, position: 'relative', overflow: 'hidden',
      background: `linear-gradient(135deg, ${org.color[0]} 0%, ${org.color[1]} 100%)`,
      color: 'rgba(255,255,255,.9)',
    }}>
      <div style={{ position: 'absolute', top: 12, left: 14,
        display: 'flex', alignItems: 'center', gap: 8 }}>
        <OrgGlyph org={org} size={24} />
        <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.06em',
          textTransform: 'uppercase', opacity: 0.9 }}>{org.name}</span>
      </div>
    </div>
  );
}

// ── CourseListRow (alt view) ───────────────────────────────────────────────
function CourseListRow({ course: c, onOpen }) {
  const ValidIcon = c.validation.level === 'error' ? I.AlertCircle
    : c.validation.level === 'warning' ? I.AlertTriangle : I.Check;
  return (
    <div onClick={onOpen}
      style={{
        display: 'grid', gridTemplateColumns: '32px 1fr 100px 140px 110px 140px 80px 40px',
        gap: 14, alignItems: 'center',
        padding: '10px 14px', cursor: 'default',
        borderBottom: '1px solid var(--border-faint)',
      }}
      onMouseOver={e => e.currentTarget.style.background = 'var(--surface-inset)'}
      onMouseOut={e => e.currentTarget.style.background = 'transparent'}>
      <div style={{ width: 28, height: 28, borderRadius: 6,
        background: `linear-gradient(135deg, ${window.SAMPLE_ORGS.find(o => o.id === c.org).color[0]}, ${window.SAMPLE_ORGS.find(o => o.id === c.org).color[1]})`,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        color: '#fff', fontSize: 11, fontWeight: 700 }}>
        {c.title[0]}
      </div>
      <div>
        <div style={{ fontSize: 13.5, fontWeight: 600 }}>{c.title}</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>
          {c.modules} modules · {c.layouts} layouts
        </div>
      </div>
      <span style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>{c.topic}</span>
      <span className={`pill ${c.status === 'shipped' ? 'accepted'
        : c.status === 'in-progress' ? 'proposed' : ''}`} style={{ fontSize: 10.5 }}>
        {c.status}
      </span>
      <span style={{ display: 'inline-flex', gap: 2, fontSize: 13 }}>
        {c.langs.slice(0, 3).map(l => <span key={l}>{LANG_FLAGS[l]}</span>)}
        {c.langs.length > 3 && <span style={{ fontSize: 10, color: 'var(--text-faint)',
          alignSelf: 'center', marginLeft: 2 }}>+{c.langs.length - 3}</span>}
      </span>
      <span style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>
        {c.editor.split(' ')[0]} · {c.lastSaved}
      </span>
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 11.5,
        color: c.validation.level === 'error' ? 'var(--error-text)'
          : c.validation.level === 'warning' ? 'var(--warning-text)' : 'var(--success-text)',
      }}>
        <ValidIcon size={11} />{c.validation.count === 0 ? 'OK' : c.validation.count}
      </span>
      <I.ChevronRight size={13} style={{ color: 'var(--text-faint)' }} />
    </div>
  );
}

// ── NewCourseCard ──────────────────────────────────────────────────────────
function NewCourseCard({ onClick }) {
  return (
    <button onClick={onClick}
      style={{
        background: 'transparent',
        border: '1px dashed var(--border-strong)',
        borderRadius: 'var(--radius-md)',
        padding: 0,
        cursor: 'default', fontFamily: 'inherit', color: 'var(--text-muted)',
        minHeight: 224, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 8,
      }}
      onMouseOver={e => { e.currentTarget.style.borderColor = 'var(--accent)';
        e.currentTarget.style.color = 'var(--accent-text)';
        e.currentTarget.style.background = 'var(--accent-bg)'; }}
      onMouseOut={e => { e.currentTarget.style.borderColor = 'var(--border-strong)';
        e.currentTarget.style.color = 'var(--text-muted)';
        e.currentTarget.style.background = 'transparent'; }}>
      <I.Plus size={22} />
      <span style={{ fontSize: 13, fontWeight: 500 }}>New course</span>
      <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>
        Start from a template or upload sources
      </span>
    </button>
  );
}

// ── Activity feed ──────────────────────────────────────────────────────────
function ActivityFeed({ org }) {
  const events = [
    { who: 'Lisa Park', what: 'edited M2-L3 in', target: 'Difficult Interactions', when: '2 min ago', icon: 'PenLine', tint: 'var(--accent)' },
    { who: 'Marco Rossi', what: 'shipped', target: 'Code of Conduct v3.4', when: '2 days ago', icon: 'Package', tint: 'var(--success)' },
    { who: 'AI · Gemini', what: 'generated cover image for', target: 'Cybersecurity Foundations', when: '32 min ago', icon: 'Sparkle', tint: 'var(--ai-text)' },
    { who: 'Akira Sato', what: 'archived', target: 'Service Excellence (legacy)', when: '6 weeks ago', icon: 'History', tint: 'var(--text-muted)' },
    { who: 'Lisa Park', what: 'added Italian translations to', target: 'Guest Privacy & GDPR', when: '1 hr ago', icon: 'Globe', tint: 'var(--accent)' },
  ];
  return (
    <div className="card" style={{ padding: 4 }}>
      {events.map((e, i) => {
        const Icon = window.I[e.icon] || window.I.Activity;
        return (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '28px 1fr auto', gap: 12, alignItems: 'center',
            padding: '10px 14px',
            borderBottom: i < events.length - 1 ? '1px solid var(--border-faint)' : 'none',
          }}>
            <span style={{
              width: 24, height: 24, borderRadius: 6, background: 'var(--surface-inset)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              color: e.tint,
            }}><Icon size={13} /></span>
            <div style={{ fontSize: 13, color: 'var(--text)' }}>
              <span style={{ fontWeight: 600 }}>{e.who}</span>
              <span style={{ color: 'var(--text-muted)' }}> {e.what} </span>
              <span style={{ fontWeight: 500 }}>{e.target}</span>
            </div>
            <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>{e.when}</span>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { SurfaceHome, OrgGlyph });
