/* global React */
const { useState, useEffect, useMemo, useRef } = React;

// ============ Shared components ============
window.Icon = function Icon({ name, size = 16, stroke = 2 }) {
  const paths = {
    arrow_left: <><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></>,
    arrow_right: <><line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></>,
    chevron_right: <polyline points="9 18 15 12 9 6" />,
    chevron_down: <polyline points="6 9 12 15 18 9" />,
    refresh: <><polyline points="23 4 23 10 17 10" /><polyline points="1 20 1 14 7 14" /><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" /></>,
    log_out: <><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" /></>,
    home: <><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" /></>,
    grid: <><rect x="3" y="3" width="7" height="7" /><rect x="14" y="3" width="7" height="7" /><rect x="14" y="14" width="7" height="7" /><rect x="3" y="14" width="7" height="7" /></>,
    users: <><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M23 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" /></>,
    user: <><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" /></>,
    list: <><line x1="8" y1="6" x2="21" y2="6" /><line x1="8" y1="12" x2="21" y2="12" /><line x1="8" y1="18" x2="21" y2="18" /><line x1="3" y1="6" x2="3.01" y2="6" /><line x1="3" y1="12" x2="3.01" y2="12" /><line x1="3" y1="18" x2="3.01" y2="18" /></>,
    package: <><line x1="16.5" y1="9.4" x2="7.5" y2="4.21" /><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /><polyline points="3.27 6.96 12 12.01 20.73 6.96" /><line x1="12" y1="22.08" x2="12" y2="12" /></>,
    clock: <><circle cx="12" cy="12" r="10" /><polyline points="12 6 12 12 16 14" /></>,
    alert: <><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" /><line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" /></>,
    trending_up: <><polyline points="23 6 13.5 15.5 8.5 10.5 1 18" /><polyline points="17 6 23 6 23 12" /></>,
    trending_down: <><polyline points="23 18 13.5 8.5 8.5 13.5 1 6" /><polyline points="17 18 23 18 23 12" /></>,
    camera: <><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" /><circle cx="12" cy="13" r="4" /></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round">
      {paths[name]}
    </svg>
  );
};

// ============ Update banner ============
// Page is refreshed every 10 minutes — show last update + countdown to next.
window.LiveBanner = function LiveBanner({ scenario, role, storeName }) {
  // Anchor 'now' to mount so the countdown ticks down deterministically
  // toward the next 10-min cycle. Real backend would push the actual timestamp.
  const [now, setNow] = useState(new Date());
  useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);

  // Last update = most recent 10-minute boundary in wall time.
  const lastUpdate = new Date(now);
  lastUpdate.setMinutes(Math.floor(lastUpdate.getMinutes() / 10) * 10, 0, 0);
  const nextUpdate = new Date(lastUpdate.getTime() + 10 * 60 * 1000);
  const secsToNext = Math.max(0, Math.floor((nextUpdate - now) / 1000));
  const mm = Math.floor(secsToNext / 60).toString().padStart(2, '0');
  const ss = (secsToNext % 60).toString().padStart(2, '0');

  const fmtTime = (d) => d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
  const fmtDate = (d) => d.toLocaleDateString('pt-BR', { weekday: 'long', day: '2-digit', month: 'long' });
  const dateLabel = fmtDate(now).charAt(0).toUpperCase() + fmtDate(now).slice(1);

  return (
    <div className="live-banner">
      <div className="live-banner-left">
        <div>
          <div className="live-label">Última atualização</div>
          <div className="live-time-wrap">
            <span className="live-time">{fmtTime(lastUpdate)}</span>
            <span className="live-meta">{dateLabel}</span>
          </div>
        </div>
      </div>
      <div className="live-banner-right">
        <span className="live-chip">Próxima atualização em <strong>{mm}:{ss}</strong></span>
      </div>
    </div>
  );
};

// ============ KPI Big Number Card ============
window.KPICard = function KPICard({ label, value, unit, raw, status, delta, deltaLabel, hint, max = 100, invert = false, onClick }) {
  const statusClass = status || 'neutral';
  const fillWidth = invert
    ? Math.min(100, (value / Math.max(max, 1)) * 100)
    : Math.min(100, (value / Math.max(max, 1)) * 100);
  return (
    <div className={`kpi-card ${onClick ? 'clickable' : ''}`} onClick={onClick}>
      <div className="kpi-card-head">
        <span className="kpi-label">{label}</span>
        <span className={`kpi-status-dot ${statusClass}`} />
      </div>
      <div className="kpi-value-row">
        <span className={`kpi-value ${statusClass}`}>{value}</span>
        {unit && <span className="kpi-unit">{unit}</span>}
      </div>
      <div className="kpi-foot">
        <span className="kpi-raw">{raw}</span>
        {delta !== undefined && (
          <span className={`kpi-delta ${delta > 0 ? 'up' : delta < 0 ? 'down' : 'neutral'}`}>
            <Icon name={delta > 0 ? 'trending_up' : 'trending_down'} size={11} />
            {delta > 0 ? '+' : ''}{delta}{deltaLabel || ''}
          </span>
        )}
      </div>
      <div className="kpi-track">
        <div className={`kpi-track-fill ${statusClass}`} style={{ width: `${fillWidth}%` }} />
      </div>
      {hint && <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>{hint}</div>}
    </div>
  );
};

// ============ Status pill ============
window.StatusPill = function StatusPill({ status, children }) {
  return <span className={`store-pill ${status}`}>{children}</span>;
};

// ============ Pct cell ============
window.PctCell = function PctCell({ value, status }) {
  return (
    <div className="pct-cell">
      <div className="pct-bar"><div className={`pct-bar-fill ${status}`} style={{ width: `${Math.min(100, value)}%` }} /></div>
      <span className={`num pct-value ${status}`}>{value.toFixed(1)}%</span>
    </div>
  );
};

// ============ Initials helper ============
window.initials = function initials(name) {
  return name.split(' ').filter(Boolean).slice(0, 2).map(w => w[0]).join('').toUpperCase();
};

// ============ Tab bar (top tabs) ============
window.Tabs = function Tabs({ tabs, value, onChange }) {
  return (
    <div className="tabs">
      {tabs.map((t) => (
        <button key={t.id} className={`tab ${value === t.id ? 'active' : ''}`} onClick={() => onChange(t.id)}>
          {t.label}
          {t.count !== undefined && <span className="tab-count">{t.count}</span>}
        </button>
      ))}
    </div>
  );
};
