/* UI primitives: Sidebar, Topbar, Card, Stat, Badge, Modal */

// Zijbalk-promo: toont de eerstvolgende verzendbatch op basis van echte data.
function SidebarPromo({ navigate, setMobileOpen }) {
  const D = window.SW_DATA || {};
  const concept = (D.INVOICES || []).filter(i => !i.sent);
  const totaal = concept.reduce((s, i) => s + i.total, 0);
  const verzenddag = (D.SETTINGS && D.SETTINGS.verzenddag) || 20;
  const fmtEUR = D.fmtEUR || (n => '€ ' + n);

  if (concept.length === 0) {
    return (
      <div className="sidebar-promo">
        <div className="promo-eyebrow">Facturatie</div>
        <div className="promo-title">Alle facturen van de lopende ronde zijn verstuurd.</div>
        <button className="promo-cta" onClick={() => { navigate('invoices'); setMobileOpen(false); }}>
          Naar facturen <window.Icons.Chevron size={12} />
        </button>
      </div>
    );
  }
  return (
    <div className="sidebar-promo">
      <div className="promo-eyebrow">Volgende batch</div>
      <div className="promo-title">{concept.length} facturen worden automatisch verstuurd op de {verzenddag}<sup>e</sup>.</div>
      <div className="promo-meta">{fmtEUR(totaal)} totaal</div>
      <button className="promo-cta" onClick={() => { navigate('invoices'); setMobileOpen(false); }}>
        Bekijk batch <window.Icons.Chevron size={12} />
      </button>
    </div>
  );
}

function Sidebar({ route, navigate, mobileOpen, setMobileOpen }) {
  const { Icons } = window;
  const main = [
    { id: 'dashboard',  label: 'Dashboard',   icon: Icons.Dashboard },
    { id: 'tenants',    label: 'Huurders',    icon: Icons.Tenants },
    { id: 'contracts',  label: 'Contracten',  icon: Icons.Contracts },
    { id: 'invoices',   label: 'Facturen',    icon: Icons.Invoices },
    { id: 'maintenance',label: 'Onderhoud',   icon: Icons.Maintenance },
  ];
  const archive = [
    { id: 'documents',  label: 'Documenten',  icon: Icons.Documents },
    { id: 'operations', label: 'Exploitatie', icon: Icons.Operations },
    { id: 'settings',   label: 'Instellingen', icon: Icons.Settings },
  ];
  const renderItem = (it) => {
    const Ic = it.icon;
    const active = route.startsWith(it.id);
    return (
      <button key={it.id} className={'nav-item' + (active ? ' active' : '')}
              onClick={() => { navigate(it.id); setMobileOpen(false); }}>
        <Ic />
        <span>{it.label}</span>
      </button>
    );
  };
  return (
    <>
      <div className={'sidebar-scrim' + (mobileOpen ? ' open' : '')} onClick={() => setMobileOpen(false)}></div>
      <aside className={'sidebar' + (mobileOpen ? ' open' : '')}>
        <div className="brand">SCHOENERWEG<span className="dot">.</span></div>
        <nav className="nav">
          <div className="nav-section">Beheer</div>
          {main.map(renderItem)}
          <div className="nav-section">Archief</div>
          {archive.map(renderItem)}
        </nav>
        <SidebarPromo navigate={navigate} setMobileOpen={setMobileOpen} />
        <div className="user-card">
          <div className="avatar">RD</div>
          <div style={{ minWidth: 0 }}>
            <div className="user-name">Ralph</div>
            <div className="user-role">RD Vastgoed B.V.</div>
          </div>
        </div>
      </aside>
    </>
  );
}

function Topbar({ title, sub, actions, zoek, setMobileOpen }) {
  const { Icons } = window;
  return (
    <header className="topbar">
      <div className="row" style={{ gap: 14 }}>
        <button className="btn btn-icon btn-ghost menu-button" onClick={() => setMobileOpen(true)}>
          <Icons.Menu />
        </button>
        <div>
          <div className="topbar-title">{title}</div>
          {sub && <div className="topbar-sub">{sub}</div>}
        </div>
      </div>
      <div className="topbar-actions">{zoek}{actions}</div>
    </header>
  );
}

function Stat({ label, value, foot, color = 'blue', pct, delta, deltaSign }) {
  // color: blue | green | yellow | purple | pink
  // pct: optional integer to show inside ribbon (e.g. 64 for 64%)
  // delta: { value: '+12%' | '−6%', sign: 'pos' | 'neg' | 'neutral', label: 't.o.v. vorige maand' }
  return (
    <div className="stat" data-c={color}>
      <div className="stat-main">
        <div className="stat-label">{label}</div>
        <div className="stat-value">{value}</div>
        <div className="stat-foot">
          {delta && (
            <span className={'delta-pill ' + (delta.sign || 'pos')}>
              {delta.value}
            </span>
          )}
          {foot && <span>{foot}</span>}
        </div>
      </div>
      <div className="stat-ribbon">
        <span className="stat-ribbon-cap"></span>
        <span className="stat-ribbon-pct">{pct != null ? `${pct}%` : ''}</span>
      </div>
    </div>
  );
}

function Badge({ kind = 'neutral', children, dot = true }) {
  return (
    <span className={'badge badge-' + kind}>
      {dot && <span className="dot"></span>}
      {children}
    </span>
  );
}

function Card({ title, action, children, flush }) {
  return (
    <div className="card">
      {(title || action) && (
        <div className="card-header">
          <div className="h2">{title}</div>
          {action}
        </div>
      )}
      <div className={flush ? 'card-flush' : 'card-body'}>{children}</div>
    </div>
  );
}

function Search({ value, onChange, placeholder = 'Zoeken…', width }) {
  const { Icons } = window;
  return (
    <div className="input-with-icon" style={{ width }}>
      <Icons.Search />
      <input className="input search" value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder} style={width ? { width: '100%' } : null} />
    </div>
  );
}

function Tabs({ value, onChange, options }) {
  return (
    <div className="tabs">
      {options.map(o => (
        <button key={o.value}
                className={'tab' + (value === o.value ? ' active' : '')}
                onClick={() => onChange(o.value)}>
          {o.label}
          {o.count != null && <span className="count">{o.count}</span>}
        </button>
      ))}
    </div>
  );
}

function Unit({ children }) {
  return <span className="unit">{children}</span>;
}

function Avatar({ name, size = 28 }) {
  const initials = name.split(/\s+/).filter(Boolean).slice(0,2).map(p => p[0]).join('').toUpperCase();
  return <div className="avatar" style={{ width: size, height: size, fontSize: size * 0.38 }}>{initials}</div>;
}

function Modal({ title, sub, onClose, children, footer, size }) {
  React.useEffect(() => {
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div className="scrim" onClick={onClose}>
      <div className={'modal' + (size === 'lg' ? ' modal-lg' : '')} onClick={e => e.stopPropagation()}>
        <div className="modal-header">
          <div className="modal-title">{title}</div>
          {sub && <div className="modal-sub">{sub}</div>}
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

function Breadcrumb({ items, navigate }) {
  return (
    <div className="crumb">
      {items.map((it, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span className="sep">/</span>}
          {it.to ? <a onClick={() => navigate(it.to)}>{it.label}</a> : <span className="current">{it.label}</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

function StatusBadge({ paid, sent, error, channel }) {
  if (paid) return <Badge kind="success">Betaald</Badge>;
  // Verzending geprobeerd en mislukt: dat is iets anders dan 'nog concept'.
  if (!sent && error) return <Badge kind="danger">Verzending mislukt</Badge>;
  if (sent && channel === 'dry-run') return <Badge kind="warning">Niet gemaild</Badge>;
  if (sent) return <Badge kind="danger">Open</Badge>;
  return <Badge kind="warning">Concept</Badge>;
}

function MaintenanceStatus({ status }) {
  if (status === 'open') return <Badge kind="danger">Open</Badge>;
  if (status === 'in_behandeling') return <Badge kind="warning">In behandeling</Badge>;
  return <Badge kind="success">Afgerond</Badge>;
}

function YesNo({ yes, yesLabel = 'Ja', noLabel = 'Nee' }) {
  const { Icons } = window;
  return yes
    ? <span className="check-yes"><Icons.Check size={14} stroke={2} />{yesLabel}</span>
    : <span className="check-no"><Icons.X size={14} stroke={2} />{noLabel}</span>;
}

window.UI = { Sidebar, Topbar, Stat, Badge, Card, Search, Tabs, Unit, Avatar, Modal, Breadcrumb, StatusBadge, MaintenanceStatus, YesNo };
