// AcademiaDental — Reusable UI components
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ---------- Icons (inline SVGs) ----------
const Icon = {
  Home: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>),
  Book: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>),
  Chat: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>),
  User: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>),
  Gift: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M20 12V22H4V12"/><path d="M22 7H2v5h20V7z"/><path d="M12 22V7"/><path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/><path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/></svg>),
  Shield: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>),
  Lock: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>),
  Check: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" {...p}><polyline points="20 6 9 17 4 12"/></svg>),
  X: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>),
  Back: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><polyline points="15 18 9 12 15 6"/></svg>),
  Play: (p) => (<svg viewBox="0 0 24 24" fill="currentColor" stroke="none" {...p}><polygon points="6 4 20 12 6 20 6 4"/></svg>),
  Phone: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="5" y="2" width="14" height="20" rx="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg>),
  Laptop: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="2" y1="21" x2="22" y2="21"/></svg>),
  Bell: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>),
  Clock: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>),
  Send: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" {...p}><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>),
  Settings: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>),
  Map: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/><line x1="8" y1="2" x2="8" y2="18"/><line x1="16" y1="6" x2="16" y2="22"/></svg>),
  Flag: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/></svg>),
  Trash: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>),
  Download: (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>),
  Flame: (p) => (<svg viewBox="0 0 24 24" fill="currentColor" stroke="none" {...p}><path d="M12 2s4 4 4 8a4 4 0 0 1-8 0c0-1 .5-2 1-3-1 0-3 2-3 6a6 6 0 0 0 12 0c0-5-6-11-6-11z"/></svg>)
};

// ---------- Toast ----------
window.AD_TOAST = (() => {
  const sub = new Set();
  let list = [];
  function emit() { sub.forEach((f) => f(list.slice())); }
  function show(msg, ms = 2200) {
    const id = Math.random().toString(36).slice(2);
    list.push({ id, msg });
    emit();
    setTimeout(() => { list = list.filter((t) => t.id !== id); emit(); }, ms);
  }
  function subscribe(fn) { sub.add(fn); fn(list.slice()); return () => sub.delete(fn); }
  return { show, subscribe };
})();

function ToastHost() {
  const [items, setItems] = useState([]);
  useEffect(() => window.AD_TOAST.subscribe(setItems), []);
  if (!items.length) return null;
  return (
    <div className="toast-root">
      {items.map((t) => (<div key={t.id} className="toast">{t.msg}</div>))}
    </div>
  );
}

// ---------- Modal ----------
function Modal({ title, body, onClose, actions }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div className="modal-root" onClick={onClose}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()}>
        {title ? <h3>{title}</h3> : null}
        {body}
        {actions ? <div style={{display:'flex', gap:8, marginTop:14}}>{actions}</div> : null}
      </div>
    </div>
  );
}

// ---------- Layout: AppShell (sidebar on desktop, top+bottom on mobile) ----------
function AppShell({ session, route, setRoute, children }) {
  const S = window.AD_STATE;
  const streak = S.getStreak(session.email).count || 0;

  const tabs = [
    { id: 'home',     label: 'Inicio',    icon: Icon.Home },
    { id: 'modules',  label: 'Módulos',   icon: Icon.Book },
    { id: 'tutor',    label: 'Tutor IA',  icon: Icon.Chat },
    { id: 'account',  label: 'Cuenta',    icon: Icon.User }
  ];

  const sideExtra = [
    { id: 'minsal',    label: 'Guías MINSAL', icon: Icon.Flag },
    { id: 'referrals', label: 'Referidos',    icon: Icon.Gift },
    { id: 'security',  label: 'Seguridad',    icon: Icon.Shield }
  ];

  return (
    <div className="app-root">
      <div className="app-window">
        {/* Desktop sidebar */}
        <aside className="sidebar">
          <div className="brand">Academia<span>Dental</span></div>
          {tabs.map((t) => (
            <button key={t.id}
              className={'nav-item ' + (route.startsWith(t.id) ? 'active' : '')}
              onClick={() => setRoute(t.id)}>
              <t.icon /> {t.label}
            </button>
          ))}
          <div className="nav-divider"></div>
          {sideExtra.map((t) => (
            <button key={t.id}
              className={'nav-item ' + (route === t.id ? 'active' : '')}
              onClick={() => setRoute(t.id)}>
              <t.icon /> {t.label}
            </button>
          ))}
          <div className="streak-pill">
            <Icon.Flame style={{width:14,height:14,color:'#F0997B'}}/>
            <span><strong>{streak}</strong> días de racha</span>
          </div>
          <div className="footer">
            <strong>{session.name}</strong><br/>
            {session.email}
          </div>
        </aside>

        {/* Main area */}
        <div className="main-area" style={{display:'flex',flexDirection:'column',overflow:'hidden',flex:1}}>
          {children}
          {/* Mobile bottom nav */}
          <nav className="bottom-nav">
            {tabs.map((t) => (
              <button key={t.id}
                className={'bn-item ' + (route.startsWith(t.id) ? 'active' : '')}
                onClick={() => setRoute(t.id)}>
                <t.icon /><span className="bn-lbl">{t.label}</span>
              </button>
            ))}
          </nav>
        </div>
      </div>
      <ToastHost />
    </div>
  );
}

// ---------- Mobile top bar ----------
function TopBar({ title, back, right, logo }) {
  return (
    <div className="top-bar">
      {back
        ? <button className="back" onClick={back.onClick}><Icon.Back style={{width:14,height:14}}/>{back.label || 'Volver'}</button>
        : (logo
            ? <div className="logo-mark">Academia<span>Dental</span></div>
            : (title ? <div className="title">{title}</div> : <div />))}
      {title && (back || logo) ? <div className="title">{title}</div> : null}
      <div className="actions">{right}</div>
    </div>
  );
}

// Progress bar
function ProgressBar({ value, color }) {
  return (
    <div className="pbar-bg">
      <div className={'pbar ' + (color || '')} style={{ width: Math.min(100, Math.max(0, value)) + '%' }} />
    </div>
  );
}

// Streak weekly strip (sun-mon-tue ...)
function StreakWeek({ email }) {
  const S = window.AD_STATE;
  const streak = S.getStreak(email);
  const days = ['L','M','M','J','V','S','D'];
  const today = new Date();
  // Build last 7 days back-to-front
  const cells = [];
  for (let i = 6; i >= 0; i--) {
    const d = new Date(today); d.setDate(today.getDate() - i);
    const key = S.todayKey(d);
    const done = !!(streak.daysOfWeek && streak.daysOfWeek[key]);
    const isToday = i === 0;
    // Map day index Monday=0
    const dayName = days[(d.getDay() + 6) % 7];
    cells.push({ key, done, isToday, dayName });
  }
  return (
    <div className="streak-week">
      {cells.map((c, i) => (
        <div key={i} className={'streak-day ' + (c.isToday ? 'today' : (c.done ? 'done' : ''))}>
          <div className="ball">{c.done ? <Icon.Check style={{width:14,height:14}}/> : (c.isToday ? '·' : '')}</div>
          <div>{c.dayName}</div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Icon, Modal, AppShell, TopBar, ProgressBar, StreakWeek, ToastHost });
