// Dynamo Authoring root — pick which organization to enter.

function SurfaceDynamoHome({ onPickOrg }) {
  const orgs = window.SAMPLE_ORGS;
  const allCourses = window.SAMPLE_COURSES_LIST;

  // Aggregate counts across all orgs the user has access to
  const totals = orgs.reduce((acc, o) => {
    const orgCourses = allCourses.filter(c => c.org === o.id);
    acc.courses += orgCourses.length;
    acc.inProgress += orgCourses.filter(c => c.status === 'in-progress').length;
    acc.issues += orgCourses.reduce((s, c) => s + c.validation.count, 0);
    return acc;
  }, { courses: 0, inProgress: 0, issues: 0 });

  return (
    <div style={{ height: '100%', background: 'var(--bg)', overflowY: 'auto' }}
         data-screen-label="Dynamo Authoring Home · Org picker">

      {/* Soft hero strip — neutral, not org-colored */}
      <div style={{
        background: 'linear-gradient(180deg, var(--surface) 0%, var(--bg) 100%)',
        borderBottom: '1px solid var(--border)',
      }}>
        <div style={{ maxWidth: 1200, margin: '0 auto', padding: '40px 28px 28px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 6 }}>
            <DynamoMark size={36} />
            <div>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-muted)',
                letterSpacing: '.08em', textTransform: 'uppercase' }}>
                Dynamo Authoring
              </div>
              <h1 style={{ margin: '2px 0 0', fontSize: 24, fontWeight: 600,
                letterSpacing: '-.01em' }}>Welcome back, Lisa</h1>
            </div>
          </div>
          <p style={{ margin: '8px 0 20px 50px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 640 }}>
            You have access to {orgs.length} organizations. Pick one to continue authoring,
            or jump straight to recent work below.
          </p>

          {/* Quick stats */}
          <div style={{ display: 'flex', gap: 32, paddingLeft: 50,
            fontSize: 12, color: 'var(--text-muted)' }}>
            <BigStat label="Organizations" value={orgs.length} />
            <BigStat label="Total courses" value={totals.courses} />
            <BigStat label="In progress" value={totals.inProgress} />
            <BigStat label="Open issues" value={totals.issues} tone="warning" />
          </div>
        </div>
      </div>

      {/* Org cards */}
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '28px 28px 40px' }}>
        <SectionHeader
          title="Your organizations"
          subtitle="Click to enter that org's authoring workspace" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 14 }}>
          {orgs.map(org => <OrgPickerCard key={org.id} org={org}
            courses={allCourses.filter(c => c.org === org.id)}
            onClick={() => onPickOrg(org.id)} />)}
          <JoinOrgCard />
        </div>

        {/* Recent activity across orgs */}
        <div style={{ marginTop: 32 }}>
          <SectionHeader
            title="Pick up where you left off"
            subtitle="Courses you've touched recently" />
          <div style={{ display: 'grid', gap: 8 }}>
            {allCourses.filter(c => c.status === 'in-progress')
              .sort((a, b) => a.lastSaved.localeCompare(b.lastSaved))
              .slice(0, 5)
              .map(c => <RecentCourseRow key={c.id} course={c}
                org={orgs.find(o => o.id === c.org)}
                onOpen={() => onPickOrg(c.org)} />)}
          </div>
        </div>

        {/* Footer note */}
        <div style={{
          marginTop: 28, padding: '12px 16px',
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 'var(--radius-md)',
          display: 'flex', alignItems: 'center', gap: 10,
          fontSize: 12, color: 'var(--text-muted)',
        }}>
          <I.Info size={13} />
          <span>
            Don't see your organization?{' '}
            <a href="#" style={{ color: 'var(--accent-text)' }}>Ask an admin to invite you</a>
            {' '}or{' '}
            <a href="#" style={{ color: 'var(--accent-text)' }}>create a new organization</a>.
          </span>
        </div>
      </div>
    </div>
  );
}

function DynamoMark({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <rect x="2" y="2" width="28" height="28" rx="7" fill="var(--text)" />
      <path d="M10 9 L10 23 L17 23 C20.3 23 22.5 20 22.5 16 C22.5 12 20.3 9 17 9 Z"
        fill="var(--bg)" />
      <circle cx="22" cy="9" r="2.5" fill="var(--accent)" />
    </svg>
  );
}

function BigStat({ label, value, tone }) {
  const color = tone === 'warning' ? 'var(--warning-text)' : 'var(--text)';
  return (
    <div>
      <div style={{ fontSize: 22, fontWeight: 600, color, lineHeight: 1.1,
        fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--text-faint)',
        letterSpacing: '.06em', textTransform: 'uppercase', marginTop: 2 }}>{label}</div>
    </div>
  );
}

function SectionHeader({ title, subtitle }) {
  return (
    <header style={{ marginBottom: 14 }}>
      <h2 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>{title}</h2>
      {subtitle && <p style={{ margin: '2px 0 0', fontSize: 13, color: 'var(--text-muted)' }}>
        {subtitle}</p>}
    </header>
  );
}

// ── OrgPickerCard ──────────────────────────────────────────────────────────
function OrgPickerCard({ org, courses, onClick }) {
  const inProgress = courses.filter(c => c.status === 'in-progress').length;
  const issues = courses.reduce((s, c) => s + c.validation.count, 0);
  return (
    <button onClick={onClick} className="focusable"
      style={{
        position: 'relative',
        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: 'all 150ms',
      }}
      onMouseOver={e => { e.currentTarget.style.borderColor = org.color[0];
        e.currentTarget.style.boxShadow = 'var(--shadow-lg)';
        e.currentTarget.style.transform = 'translateY(-1px)'; }}
      onMouseOut={e => { e.currentTarget.style.borderColor = 'var(--border)';
        e.currentTarget.style.boxShadow = 'none';
        e.currentTarget.style.transform = 'translateY(0)'; }}>
      {/* Brand strip */}
      <div style={{
        height: 80, position: 'relative', overflow: 'hidden',
        background: `linear-gradient(135deg, ${org.color[0]}, ${org.color[1]})`,
      }}>
        {/* Subtle pattern */}
        <svg style={{ position: 'absolute', right: -10, top: -10, opacity: 0.08 }}
             width="120" height="120" viewBox="0 0 100 100">
          <defs>
            <pattern id={`pat-${org.id}`} width="8" height="8" patternUnits="userSpaceOnUse">
              <circle cx="4" cy="4" r="1" fill="white"/>
            </pattern>
          </defs>
          <rect width="100" height="100" fill={`url(#pat-${org.id})`}/>
        </svg>
        <div style={{ position: 'absolute', bottom: 12, left: 16,
          display: 'flex', alignItems: 'center', gap: 10, color: '#fff' }}>
          <div style={{
            width: 44, height: 44, borderRadius: 10,
            background: 'rgba(255,255,255,0.18)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontWeight: 700, fontSize: 17,
            backdropFilter: 'blur(8px)',
            boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.25)',
          }}>{org.glyph}</div>
          <div>
            <div style={{ fontSize: 15, fontWeight: 600, lineHeight: 1.2 }}>{org.name}</div>
            <div style={{ fontSize: 11, opacity: 0.85 }}>{org.plan}</div>
          </div>
        </div>
      </div>

      {/* Body */}
      <div style={{ padding: '14px 16px' }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 2 }}>{org.full}</div>
        <p style={{ margin: 0, fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
          {org.desc}
        </p>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 6, marginTop: 12, paddingTop: 12,
          borderTop: '1px solid var(--border-faint)',
        }}>
          <OrgMiniStat label="Courses" value={courses.length} />
          <OrgMiniStat label="Active" value={inProgress} tone={inProgress > 0 ? 'accent' : null} />
          <OrgMiniStat label="Issues" value={issues} tone={issues > 0 ? 'warning' : null} />
        </div>
        <div style={{
          marginTop: 12, padding: '6px 0 0',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          fontSize: 12, color: 'var(--text-muted)',
        }}>
          <span>{org.stats.editors} editors</span>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            color: 'var(--accent-text)', fontWeight: 500,
          }}>
            Enter <I.ArrowRight size={12} />
          </span>
        </div>
      </div>
    </button>
  );
}

function OrgMiniStat({ label, value, tone }) {
  const color = tone === 'warning' ? 'var(--warning-text)'
    : tone === 'accent' ? 'var(--accent-text)'
    : 'var(--text)';
  return (
    <div>
      <div style={{ fontSize: 15, fontWeight: 600, color, lineHeight: 1.1,
        fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      <div style={{ fontSize: 10, color: 'var(--text-faint)',
        letterSpacing: '.04em', textTransform: 'uppercase', fontWeight: 600,
        marginTop: 2 }}>{label}</div>
    </div>
  );
}

// ── JoinOrgCard ────────────────────────────────────────────────────────────
function JoinOrgCard() {
  return (
    <button
      style={{
        background: 'transparent',
        border: '1px dashed var(--border-strong)',
        borderRadius: 'var(--radius-md)',
        padding: 0,
        cursor: 'default', fontFamily: 'inherit', color: 'var(--text-muted)',
        minHeight: 240, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 10,
      }}
      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={24} />
      <span style={{ fontSize: 13.5, fontWeight: 500 }}>Join another organization</span>
      <span style={{ fontSize: 11.5, color: 'var(--text-faint)', maxWidth: 220, textAlign: 'center' }}>
        Have an invitation code, or want to start a new one from scratch?
      </span>
    </button>
  );
}

// ── RecentCourseRow ────────────────────────────────────────────────────────
function RecentCourseRow({ course: c, org, onOpen }) {
  const ValidIcon = c.validation.level === 'error' ? I.AlertCircle
    : c.validation.level === 'warning' ? I.AlertTriangle : I.Check;
  return (
    <button onClick={onOpen} className="focusable"
      style={{
        display: 'grid', gridTemplateColumns: '36px 1fr auto auto auto',
        gap: 14, alignItems: 'center',
        padding: '10px 14px', textAlign: 'left',
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 'var(--radius-md)', cursor: 'default',
        fontFamily: 'inherit', color: 'var(--text)',
        transition: 'border-color 150ms',
      }}
      onMouseOver={e => e.currentTarget.style.borderColor = 'var(--border-strong)'}
      onMouseOut={e => e.currentTarget.style.borderColor = 'var(--border)'}>
      <div style={{
        width: 32, height: 32, borderRadius: 'var(--radius)',
        background: `linear-gradient(135deg, ${org.color[0]}, ${org.color[1]})`,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        color: '#fff', fontSize: 12, fontWeight: 700,
      }}>{org.glyph}</div>
      <div>
        <div style={{ fontSize: 13.5, fontWeight: 600 }}>{c.title}</div>
        <div style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>
          {org.name} · {c.topic} · {c.modules} modules
        </div>
      </div>
      <span style={{ fontSize: 11, color: 'var(--text-faint)',
        fontFamily: 'var(--font-mono)' }}>{c.lastSaved}</span>
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11.5,
        padding: '2px 6px', borderRadius: 4,
        background: c.validation.level === 'error' ? 'var(--error-bg)'
          : c.validation.level === 'warning' ? 'var(--warning-bg)' : 'var(--success-bg)',
        color: c.validation.level === 'error' ? 'var(--error-text)'
          : c.validation.level === 'warning' ? 'var(--warning-text)' : 'var(--success-text)',
        fontWeight: 500,
      }}>
        <ValidIcon size={11} />{c.validation.count === 0 ? 'OK' : c.validation.count}
      </span>
      <I.ChevronRight size={14} style={{ color: 'var(--text-faint)' }} />
    </button>
  );
}

Object.assign(window, { SurfaceDynamoHome });
