const { createContext, useContext } = React;

const ThemeCtx  = createContext({ theme: 'dark', toggleTheme: () => {} });
const TweaksCtx = createContext({ cardShape: 'poster', accent: '#C9A800', typeVoice: 'modern' });
const UserCtx   = createContext({ user: null, logout: () => {} });

/* Helper para iniciais (usado no avatar) */
const getInitials = (name = '') =>
  name.trim().split(/\s+/).map(w => w[0]).slice(0, 2).join('').toUpperCase();

/* ── ICONS ─────────────────────────────────────────────────────── */
const IconPlay = ({ size = 16, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={color} style={{ display:'block' }}>
    <path d="M8 5.14v14l11-7-11-7z"/>
  </svg>
);

const IconCheck = ({ size = 14, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ display:'block' }}>
    <path d="M20 6L9 17l-5-5"/>
  </svg>
);

const IconSun = ({ size = 17 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" style={{ display:'block' }}>
    <circle cx="12" cy="12" r="5"/>
    <line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/>
    <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
    <line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/>
    <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
  </svg>
);

const IconMoon = ({ size = 17 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" style={{ display:'block' }}>
    <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/>
  </svg>
);

const IconArrowLeft = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display:'block' }}>
    <path d="M19 12H5M12 19l-7-7 7-7"/>
  </svg>
);

const IconAward = ({ size = 24, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ display:'block' }}>
    <circle cx="12" cy="8" r="6"/><path d="M15.477 12.89L17 22l-5-3-5 3 1.523-9.11"/>
  </svg>
);

const IconChevron = ({ size = 14, dir = 'right' }) => {
  const deg = { right: 0, down: 90, left: 180, up: 270 }[dir] || 0;
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
      style={{ display:'block', transform:`rotate(${deg}deg)`, transition:'transform 0.25s' }}>
      <path d="M9 18l6-6-6-6"/>
    </svg>
  );
};

const IconDownload = ({ size = 15 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display:'block' }}>
    <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>
  </svg>
);

const IconLogout = ({ size = 15 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display:'block' }}>
    <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
    <polyline points="16 17 21 12 16 7"/>
    <line x1="21" y1="12" x2="9" y2="12"/>
  </svg>
);

/* ── PROGRESS BAR ───────────────────────────────────────────────── */
const ProgressBar = ({ value = 0, height = 3, style: s = {} }) => (
  <div style={{ height, background: 'var(--border)', borderRadius: height, overflow: 'hidden', ...s }}>
    <div style={{
      height: '100%', width: `${Math.min(100, Math.max(0, value))}%`,
      background: 'var(--gold)', borderRadius: height,
      transition: 'width 0.5s ease'
    }} />
  </div>
);

/* ── PROGRESS RING ──────────────────────────────────────────────── */
const ProgressRing = ({ value = 0, size = 72, stroke = 5 }) => {
  const r = (size - stroke) / 2;
  const circ = 2 * Math.PI * r;
  const offset = circ - (value / 100) * circ;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: 'rotate(-90deg)', display:'block' }}>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--border)" strokeWidth={stroke}/>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--gold)" strokeWidth={stroke}
        strokeDasharray={circ} strokeDashoffset={offset} strokeLinecap="round"
        style={{ transition: 'stroke-dashoffset 0.6s ease' }}/>
    </svg>
  );
};

/* ── USER MENU ──────────────────────────────────────────────────── */
const UserMenu = ({ size = 33 }) => {
  const { user, logout } = useContext(UserCtx);
  const [open, setOpen] = React.useState(false);
  const wrapRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);

  if (!user) return null;
  const initials = getInitials(user.name);

  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      <button
        onClick={() => setOpen(o => !o)}
        title={user.name}
        style={{
          width: size, height: size, borderRadius: '50%', flexShrink: 0,
          background: 'var(--gold)', display: 'flex', alignItems: 'center',
          justifyContent: 'center', fontSize: size * 0.36, fontWeight: 700, color: '#0A0A0A',
          padding: 0,
        }}
      >
        {initials}
      </button>

      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 8px)', right: 0,
          minWidth: 210,
          background: 'var(--card)', border: '1px solid var(--border)',
          borderRadius: 10, boxShadow: '0 8px 28px rgba(0,0,0,0.35)',
          overflow: 'hidden', zIndex: 200,
        }}>
          <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)' }}>
            <p style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text)', marginBottom: 2 }}>
              {user.name}
            </p>
            <p style={{ fontSize: 11, color: 'var(--text2)', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {user.email}
            </p>
          </div>
          <button
            onClick={() => { setOpen(false); logout(); }}
            style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 9,
              padding: '11px 14px', background: 'none',
              fontSize: 13, color: 'var(--text2)', textAlign: 'left',
              transition: 'background 0.15s',
            }}
            onMouseEnter={e => { e.currentTarget.style.background = 'var(--card-h)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'none'; }}
          >
            <IconLogout size={14}/> Sair da conta
          </button>
        </div>
      )}
    </div>
  );
};

/* ── NAV ────────────────────────────────────────────────────────── */
const Nav = ({ screen, onBack, completedCount, totalLessons }) => {
  const { theme, toggleTheme } = useContext(ThemeCtx);
  const pct = totalLessons > 0 ? Math.round((completedCount / totalLessons) * 100) : 0;

  return (
    <nav style={{
      position: 'sticky', top: 0, zIndex: 100,
      background: 'var(--nav-bg)', backdropFilter: 'blur(18px)',
      borderBottom: '1px solid var(--border)',
      height: 58, display: 'flex', alignItems: 'center',
      padding: '0 24px', gap: 14,
    }}>
      {screen !== 'dashboard' && (
        <button onClick={onBack} style={{
          display: 'flex', alignItems: 'center', gap: 6,
          background: 'none', color: 'var(--text2)',
          padding: '6px 8px', borderRadius: 7, fontSize: 13,
        }}>
          <IconArrowLeft size={14}/> Voltar
        </button>
      )}

      <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{
          fontSize: 12, fontWeight: 600, letterSpacing: '0.09em',
          textTransform: 'uppercase', color: 'var(--gold)',
        }}>
          Descomplicando a Clínica
        </span>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontSize: 12, color: 'var(--text2)', fontWeight: 500 }}>{pct}%</span>
        <ProgressBar value={pct} style={{ width: 72 }} />
      </div>

      <button onClick={toggleTheme} style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        width: 34, height: 34, borderRadius: '50%',
        background: 'var(--gold-bg)', border: '1px solid var(--border)',
        color: 'var(--gold)',
      }}>
        {theme === 'dark' ? <IconSun size={16}/> : <IconMoon size={16}/>}
      </button>

      <UserMenu size={33}/>
    </nav>
  );
};

Object.assign(window, {
  ThemeCtx, TweaksCtx, UserCtx, getInitials,
  ProgressBar, ProgressRing, Nav, UserMenu,
  IconPlay, IconCheck, IconSun, IconMoon, IconArrowLeft,
  IconAward, IconChevron, IconDownload, IconLogout,
});
