/* global React */

function WelcomeChip({ icon, num, label, tone }) {
  const I = window.Icons;
  return (
    <div className={`welcome-chip${tone ? ' is-' + tone : ''}`}>
      <div className="welcome-chip__icon">{React.createElement(I[icon], { size: 16 })}</div>
      <div>
        <div className="welcome-chip__num">{num}</div>
        <div className="welcome-chip__label">{label}</div>
      </div>
    </div>
  );
}

function Welcome({ user, roleId }) {
  const greeting = window.getGreeting();
  const first = user.name.split(' ')[0];

  let intro = null, chips = null;
  if (roleId === 'institucion') {
    intro = 'Tienes pendientes que requieren tu atención esta semana.';
    chips = (
      <>
        <WelcomeChip icon="AlertCircle" num="1" label="Reporte devuelto para ajuste" tone="warn" />
        <WelcomeChip icon="Clock" num="3" label="Plazos en los próximos 7 días" tone="danger" />
        <WelcomeChip icon="MessageSquare" num="2" label="Mensajes sin leer" />
      </>
    );
  } else if (roleId === 'cancilleria') {
    intro = 'Tres reportes nuevos están listos para envío internacional.';
    chips = (
      <>
        <WelcomeChip icon="FileText" num="3" label="Reportes aprobados nuevos" />
        <WelcomeChip icon="Calendar" num="MES V" label="Ronda activa MESICIC" />
        <WelcomeChip icon="MessageSquare" num="1" label="Mensaje sin leer" />
      </>
    );
  } else {
    intro = 'Hay reportes esperando revisión y vencimientos próximos esta semana.';
    chips = (
      <>
        <WelcomeChip icon="Inbox" num="7" label="Reportes en bandeja de revisión" tone="warn" />
        <WelcomeChip icon="Clock" num="5" label="Plazos vencen en los próximos 7 días" tone="danger" />
        <WelcomeChip icon="MessageSquare" num="3" label="Mensajes sin leer" />
      </>
    );
  }

  return (
    <section className="welcome">
      <div>
        <div className="welcome__eyebrow">
          <span>{user.org}</span>
          <span className="role-pill">{user.role}</span>
        </div>
        <h1>{greeting}, {first}.</h1>
        <p className="welcome__sub">{intro}</p>
      </div>
      <div className="welcome__chips">{chips}</div>
    </section>
  );
}

// ---------------- Feature card: Tablero ----------------
function TableroFeatureCard({ kpis, onClick }) {
  const I = window.Icons;
  return (
    <button type="button" className="module module--feature" onClick={onClick}>
      <div className="module__top">
        <div className="module__icon"><I.LayoutDashboard size={20} /></div>
        <span className="module__badge is-info">
          <I.Sparkles size={11} /> Vista en tiempo real
        </span>
      </div>
      <div>
        <div className="module__title">Tablero de Control</div>
        <div className="module__desc">Visualiza el estado de cumplimiento país consolidado entre los tres mecanismos.</div>
      </div>
      <div className="module-stats">
        <div className="module-stats__cell">
          <div className="label">Total</div>
          <div className="num">{kpis.total}</div>
        </div>
        <div className="module-stats__cell is-ok">
          <div className="label"><span className="dot-status is-ok"></span>Cumplidos</div>
          <div className="num">{kpis.cumplidos}</div>
        </div>
        <div className="module-stats__cell is-warn">
          <div className="label"><span className="dot-status is-warn"></span>Parciales</div>
          <div className="num">{kpis.parciales}</div>
        </div>
        <div className="module-stats__cell is-danger">
          <div className="label"><span className="dot-status is-danger"></span>No cumpl.</div>
          <div className="num">{kpis.noCumplidos}</div>
        </div>
      </div>
      <div className="module__cta">Abrir tablero analítico <I.ArrowRight size={13} /></div>
    </button>
  );
}

// ---------------- Feature card: Reportes Aprobados (Cancillería) ----------------
function ReportesAprobadosFeatureCard({ onClick }) {
  const I = window.Icons;
  return (
    <button type="button" className="module module--feature" onClick={onClick}>
      <div className="module__top">
        <div className="module__icon"><I.FileText size={20} /></div>
        <span className="module__badge is-info">
          <I.Sparkles size={11} /> 3 nuevos esta semana
        </span>
      </div>
      <div>
        <div className="module__title">Reportes Aprobados</div>
        <div className="module__desc">Documentos consolidados aprobados por la CGR, listos para envío a OEA, ONU y OCDE.</div>
      </div>
      <div className="module-stats">
        <div className="module-stats__cell">
          <div className="label">Total</div>
          <div className="num">12</div>
        </div>
        <div className="module-stats__cell">
          <div className="label">MESICIC</div>
          <div className="num">5</div>
        </div>
        <div className="module-stats__cell">
          <div className="label">UNCAC</div>
          <div className="num">4</div>
        </div>
        <div className="module-stats__cell">
          <div className="label">OCDE</div>
          <div className="num">3</div>
        </div>
      </div>
      <div className="module__cta">Abrir reportes aprobados <I.ArrowRight size={13} /></div>
    </button>
  );
}

// ---------------- Compact module card ----------------
function ModuleCard({ m, onClick }) {
  const I = window.Icons;
  return (
    <button
      type="button"
      className={`module${m.variant === 'accent' ? ' module--accent' : ''}${m.variant === 'wide' ? ' module--wide' : ''}`}
      onClick={onClick}
    >
      <div className="module__top">
        <div className="module__icon">{React.createElement(I[m.icon], { size: 18 })}</div>
        {m.badge && (
          <span className={`module__badge${m.badge.tone === 'info' ? ' is-info' : ''}${m.badge.tone === 'warn' ? ' is-warn' : ''}`}>
            {m.badge.count}{m.badge.tone === 'danger' ? ' pendientes' : ''}
          </span>
        )}
      </div>
      <div>
        <div className="module__title">{m.title}</div>
        <div className="module__desc">{m.desc}</div>
      </div>
      <div className="module__cta">
        {m.variant === 'accent' ? 'Abrir portal ciudadano' : 'Abrir módulo'} <I.ArrowRight size={13} />
      </div>
    </button>
  );
}

// ---------------- Activity Timeline ----------------
function ActivityTimeline({ items }) {
  const I = window.Icons;
  const iconFor = t => {
    if (t === 'submitted') return <I.Upload size={14} />;
    if (t === 'returned')  return <I.AlertCircle size={14} />;
    if (t === 'approved')  return <I.CheckCircle2 size={14} />;
    if (t === 'alert')     return <I.Bell size={14} />;
    if (t === 'message')   return <I.MessageSquare size={14} />;
    return <I.FileText size={14} />;
  };
  return (
    <div className="timeline">
      {items.map((it, i) => (
        <div className="timeline__item" key={i}>
          <div className={`timeline__avatar is-${it.avatarTone === 'default' ? '' : it.avatarTone}`}>
            {iconFor(it.type)}
          </div>
          <div className="timeline__body">
            <strong>{it.actor}</strong> {it.body} {it.ref && <span className="ref">{it.ref}</span>}
            {it.title && <small>{it.title}</small>}
          </div>
          <div className="timeline__time">{it.time}</div>
        </div>
      ))}
    </div>
  );
}

// ---------------- Deadlines List ----------------
function DeadlinesList({ items, onOpen }) {
  const I = window.Icons;
  return (
    <div className="deadlines">
      {items.map((d, i) => (
        <div key={i} className={`deadline${d.tone !== 'normal' ? ' is-' + d.tone : ''}`}>
          <div className="deadline__count">{d.code}</div>
          <div className="deadline__body">
            <div className="title">
              <span>{d.title}</span>
              <span className="id mono">{d.id}</span>
            </div>
            <div className="meta">{d.inst} · vence {d.date}</div>
          </div>
          <button type="button" className="deadline__cta" onClick={onOpen}>Ver <I.ChevronRight size={12} /></button>
        </div>
      ))}
    </div>
  );
}

// ---------------- Home Screen ----------------
function HomeScreen({ user, roleId, onNavigate }) {
  const I = window.Icons;
  const kpis = window.getKPIs(roleId);
  const activity = window.getActivity(roleId);
  const deadlines = window.getDeadlines(roleId);
  const modules = window.homeModulesForRole(roleId);

  // Find the feature module (Tablero or Reportes Aprobados) to render special
  const featureMod = modules.find(m => m.variant === 'feature');
  const rest = modules.filter(m => m !== featureMod);

  // Compose bento layout:
  // - Tablero feature: span 8
  // - Next module: span 4 (top right)
  // - Remaining: span 4 each
  // - Portal (accent): span 4
  // We tag the second module with module--wide false; just default span 4
  // To balance, mark Mensajería or first non-feature module as the right top-side card
  // Simple approach: just render feature first then rest in default grid

  return (
    <div data-screen-label="01 Home Dashboard">
      <Welcome user={user} roleId={roleId} />

      <div className="section-head">
        <h2>Módulos del sistema</h2>
        <span className="section-head__hint">Selecciona un módulo para empezar</span>
      </div>

      <div className="modules">
        {featureMod && featureMod.id === 'tablero' && (
          <TableroFeatureCard
            kpis={kpis}
            onClick={() => onNavigate(featureMod.id)}
          />
        )}
        {featureMod && featureMod.id === 'reportes_aprobados' && (
          <ReportesAprobadosFeatureCard
            onClick={() => onNavigate(featureMod.id)}
          />
        )}
        {/* Right column next to feature: first 1 short card */}
        {featureMod && rest[0] && (
          <ModuleCard m={rest[0]} onClick={() => onNavigate(rest[0].id)} />
        )}

        {/* Remaining 3-up */}
        {rest.slice(featureMod ? 1 : 0).map(m => (
          <ModuleCard key={m.id} m={m} onClick={() => onNavigate(m.id)} />
        ))}
      </div>

      <div className="split">
        <div className="card">
          <div className="card__head">
            <h3>Actividad reciente</h3>
            <button type="button" className="section-head__link">
              Ver todo <I.ArrowRight size={12} />
            </button>
          </div>
          <ActivityTimeline items={activity} />
        </div>

        <div className="card">
          <div className="card__head">
            <h3>Próximos vencimientos</h3>
            <span className="meta">D-7 · D-3 · D-1 · D · D+1</span>
          </div>
          <DeadlinesList items={deadlines} onOpen={() => onNavigate('alertas')} />
        </div>
      </div>
    </div>
  );
}

// ---------------- Stub Screen ----------------
function StubScreen({ moduleDef, onBack }) {
  const I = window.Icons;
  return (
    <div data-screen-label={`Stub · ${moduleDef.title}`}>
      <div className="stub">
        <div className="stub__icon">{React.createElement(I[moduleDef.icon], { size: 28 })}</div>
        <h2>{moduleDef.title}</h2>
        <p>
          Este módulo está fuera del alcance de esta primera entrega.
          El foco de este prototipo es la <strong>pantalla Home</strong> (hub principal).
          La navegación queda preparada para conectarse con las pantallas detalladas en próximas iteraciones.
        </p>
        <button type="button" className="btn btn--primary" onClick={onBack}>
          <I.Home size={14} /> Volver al inicio
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen, StubScreen });
