/* AORYN Portal — shell: auth, layout, navigation, icons */

const { useState, useEffect, useRef, useMemo } = React;

// ==================== ICONS ====================
const Icon = ({ name, ...p }) => {
  const I = ICONS[name];
  if (!I) return null;
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>{I}</svg>
  );
};
const ICONS = {
  home: <><path d="M3 12L12 4l9 8"/><path d="M5 10v10h14V10"/></>,
  folder: <><path d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V7z"/></>,
  timeline: <><path d="M4 6h16M4 12h12M4 18h8"/><circle cx="20" cy="6" r="1.5"/><circle cx="16" cy="12" r="1.5"/><circle cx="12" cy="18" r="1.5"/></>,
  chat: <><path d="M21 12a8 8 0 11-16 0 8 8 0 0116 0z M5 18l-2 3 4-1"/></>,
  bulb: <><path d="M9 18h6M10 21h4M12 2a6 6 0 00-4 10.5c.7.7 1 1.6 1 2.5v1h6v-1c0-.9.3-1.8 1-2.5A6 6 0 0012 2z"/></>,
  doc: <><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><path d="M14 2v6h6"/></>,
  download: <><path d="M12 4v12M6 12l6 6 6-6M4 20h16"/></>,
  gear: <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 11-4 0v-.1A1.7 1.7 0 008 19.4a1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 110-4h.1A1.7 1.7 0 004.6 8a1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3H9a1.7 1.7 0 001-1.5V3a2 2 0 114 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8V9a1.7 1.7 0 001.5 1H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1z"/></>,
  logout: <><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9"/></>,
  bell: <><path d="M6 8a6 6 0 0112 0c0 7 3 9 3 9H3s3-2 3-9M13.7 21a2 2 0 01-3.4 0"/></>,
  search: <><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></>,
  mail: <><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 6l-10 7L2 6"/></>,
  lock: <><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></>,
  eye: <><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></>,
  google: <><path d="M21.35 11.1H12v2.8h5.35c-.23 1.42-1.7 4.18-5.35 4.18-3.22 0-5.85-2.67-5.85-5.96s2.63-5.96 5.85-5.96c1.84 0 3.07.78 3.77 1.45l2.58-2.48C16.7 3.55 14.6 2.7 12 2.7c-5.1 0-9.3 4.18-9.3 9.32S6.9 21.3 12 21.3c5.4 0 8.95-3.78 8.95-9.11 0-.61-.06-1.08-.15-1.5z" stroke="none" fill="currentColor"/></>,
  arrow: <><path d="M5 12h14M13 5l7 7-7 7"/></>,
  check: <><path d="M20 6L9 17l-5-5"/></>,
  x: <><path d="M18 6L6 18M6 6l12 12"/></>,
  plus: <><path d="M12 5v14M5 12h14"/></>,
  chevdown: <><path d="M6 9l6 6 6-6"/></>,
  clip: <><path d="M21.4 11l-9 9a5.5 5.5 0 11-7.8-7.8l9-9a3.5 3.5 0 015 5l-9 9a1.5 1.5 0 11-2.2-2.2l8-8"/></>,
  smile: <><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2M9 9h.01M15 9h.01"/></>,
  send: <><path d="M22 2L11 13M22 2l-7 20-4-9-9-4z"/></>,
  drive: <><path d="M12 2l5 9-5 9-5-9z" stroke="none" fill="currentColor"/></>,
  image: <><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="M21 15l-5-5L5 21"/></>,
  filePdf: <><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z M14 2v6h6 M9 13h6 M9 17h6"/></>,
  fileVideo: <><rect x="3" y="6" width="18" height="12" rx="2"/><path d="M10 9l5 3-5 3z" fill="currentColor" stroke="none"/></>,
  fileFont: <><path d="M4 4h16v16H4z M8 8h8 M12 8v8"/></>,
  video: <><rect x="2" y="6" width="14" height="12" rx="2"/><path d="M22 8l-6 4 6 4V8z"/></>,
  more: <><circle cx="5" cy="12" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="19" cy="12" r="1.5"/></>,
  info: <><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></>,
  moon: <><path d="M21 12.8A9 9 0 1111.2 3 7 7 0 0021 12.8z"/></>,
  sun: <><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></>,
  arrowLeft: <><path d="M19 12H5M12 19l-7-7 7-7"/></>,
};

// ==================== AVATAR ====================
function Avatar({ name, className = '', tone }) {
  const initials = (name || 'AA').split(' ').filter(Boolean).slice(0, 2).map(s => s[0]).join('').toUpperCase();
  const styles = tone ? { background: tone } : {};
  return <div className={`avatar av ${className}`} style={styles}>{initials}</div>;
}

// ==================== LOGIN ====================
function LoginPage({ onLogin }) {
  const [email, setEmail] = useState('cliente@ejemplo.com');
  const [pw, setPw] = useState('demo1234');
  const [showPw, setShowPw] = useState(false);
  const [loading, setLoading] = useState(false);

  const submit = (e) => {
    e.preventDefault();
    setLoading(true);
    setTimeout(() => { setLoading(false); onLogin({ name: 'María González', email }); }, 800);
  };

  return (
    <div className="login-page">
      <div className="bg-grid"></div>
      <div className="bg-glow g1"></div>
      <div className="bg-glow g2"></div>

      <div style={{ position: 'relative', zIndex: 1 }}>
        <a href="../AORYN.html" className="back-site login-back">
          <Icon name="arrowLeft"/>
          <span>Volver a aoryn.studio</span>
        </a>
        <div className="login-mark">
          <div className="symbol"></div>
          <div className="wordmark">AORYN</div>
        </div>
        <form className="login-card glass" onSubmit={submit}>
          <div className="eyebrow">
            <span className="dot"></span>
            <span>Área cliente · Acceso seguro</span>
          </div>
          <h1>Bienvenido de nuevo</h1>
          <div className="sub">Accede al estado de tu proyecto</div>

          <div className="login-field">
            <label>Email</label>
            <div className="input-wrap">
              <Icon name="mail"/>
              <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="tu@email.com" />
            </div>
          </div>

          <div className="login-field">
            <label>Contraseña</label>
            <div className="input-wrap">
              <Icon name="lock"/>
              <input type={showPw ? 'text' : 'password'} required value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••••" />
              <button type="button" className="toggle-pw" onClick={() => setShowPw(!showPw)} tabIndex={-1}>
                <Icon name="eye" width="16" height="16"/>
              </button>
            </div>
          </div>

          <div className="login-row">
            <label><input type="checkbox" defaultChecked /> Recordarme</label>
            <a href="#">¿Olvidaste tu contraseña?</a>
          </div>

          <button type="submit" className="btn-primary" disabled={loading}>
            {loading ? 'Accediendo...' : 'Iniciar sesión'}
            {!loading && <Icon name="arrow"/>}
          </button>

          <div className="login-sep">o</div>

          <button type="button" className="btn-outline">
            <Icon name="google"/>
            Acceder con Google
          </button>

          <div className="login-foot">
            ¿No tienes cuenta? <a href="../AORYN.html">Contacta con AORYN</a>
          </div>
        </form>
      </div>
    </div>
  );
}

// ==================== SIDEBAR ====================
function Sidebar({ view, setView, onLogout }) {
  const items = (group) => group.map(it => (
    <button key={it.k} className={`sidebar-item ${view === it.k ? 'active' : ''}`} onClick={() => setView(it.k)}>
      <Icon name={it.icon}/>
      <span className="label">{it.label}</span>
      {it.badge && <span className={`badge ${it.badgeDim ? 'dim' : ''}`}>{it.badge}</span>}
    </button>
  ));
  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <span className="mark"></span>
        <span>AORYN</span>
      </div>
      <div className="sidebar-divider"></div>
      <div className="sidebar-group">
        <div className="label">Principal</div>
        {items([
          { k: 'dashboard', icon: 'home', label: 'Dashboard' },
          { k: 'project', icon: 'folder', label: 'Mi Proyecto' },
          { k: 'timeline', icon: 'timeline', label: 'Cronología' }
        ])}
      </div>
      <div className="sidebar-group">
        <div className="label">Comunicación</div>
        {items([
          { k: 'messages', icon: 'chat', label: 'Mensajes', badge: '3' },
          { k: 'proposals', icon: 'bulb', label: 'Propuestas', badge: '2', badgeDim: true }
        ])}
      </div>
      <div className="sidebar-group">
        <div className="label">Recursos</div>
        {items([
          { k: 'files', icon: 'doc', label: 'Archivos' },
          { k: 'deliverables', icon: 'download', label: 'Entregas' }
        ])}
      </div>
      <div className="sidebar-help">
        <h5>¿Necesitas ayuda?</h5>
        <p>El equipo está disponible para cualquier duda sobre tu proyecto.</p>
        <button onClick={() => setView('messages')}>Contactar</button>
      </div>
      <div className="sidebar-group" style={{ marginTop: 18, marginBottom: 0 }}>
        {items([
          { k: 'settings', icon: 'gear', label: 'Configuración' }
        ])}
        <button className="sidebar-item" onClick={onLogout}>
          <Icon name="logout"/>
          <span className="label">Cerrar sesión</span>
        </button>
      </div>
    </aside>
  );
}

// ==================== TOPBAR ====================
function Topbar({ view, user, theme, onToggleTheme }) {
  const titles = {
    dashboard: 'Dashboard',
    project: 'Mi Proyecto',
    timeline: 'Cronología',
    messages: 'Mensajes',
    proposals: 'Propuestas',
    files: 'Archivos',
    deliverables: 'Entregas',
    settings: 'Configuración'
  };
  return (
    <header className="topbar">
      <div className="crumb">
        <span>AORYN</span>
        <span style={{ color: 'var(--fg-3)' }}>/</span>
        <span className="here">{titles[view] || view}</span>
      </div>
      <div className="search">
        <Icon name="search"/>
        <input placeholder="Buscar..." />
        <kbd>⌘K</kbd>
      </div>
      <div className="topbar-right">
        <a href="../AORYN.html" className="back-site back-site-top">
          <Icon name="arrowLeft"/>
          <span>Volver al sitio</span>
        </a>
        <button className="theme-toggle" onClick={onToggleTheme} aria-label="Cambiar tema" title="Cambiar tema">
          <Icon name="moon" className="moon"/>
          <Icon name="sun" className="sun"/>
        </button>
        <button className="icon-btn"><Icon name="bell"/><span className="ping"></span></button>
        <button className="avatar-pill">
          <Avatar name={user.name} />
          <span className="name">{user.name.split(' ')[0]}</span>
          <span className="status"></span>
        </button>
      </div>
    </header>
  );
}

Object.assign(window, { LoginPage, Sidebar, Topbar, Avatar, Icon, MobileNav });

// ==================== MOBILE BOTTOM NAV ====================
function MobileNav({ view, setView }) {
  const items = [
    { k: 'dashboard', icon: 'home', label: 'Inicio' },
    { k: 'project', icon: 'folder', label: 'Proyecto' },
    { k: 'messages', icon: 'chat', label: 'Mensajes', badge: 3 },
    { k: 'files', icon: 'doc', label: 'Archivos' },
    { k: 'settings', icon: 'gear', label: 'Ajustes' }
  ];
  return (
    <nav className="mobile-nav">
      {items.map(it => (
        <button key={it.k} className={`mobile-nav-item ${view === it.k ? 'active' : ''}`} onClick={() => setView(it.k)}>
          <span className="mn-ico">
            <Icon name={it.icon}/>
            {it.badge && <span className="mn-badge">{it.badge}</span>}
          </span>
          <span className="mn-label">{it.label}</span>
        </button>
      ))}
    </nav>
  );
}
