// aerOS — data display: DataTable + StatCard. Exports to window.
const { useState: _dS, useMemo: _dM } = React;

/* ----------------------------- StatCard ----------------------------- */
function StatCard({ label, value, unit, delta, icon, spark, tone = 'brand', sub }) {
  const up = delta != null && delta >= 0;
  return (
    <div style={{ background: 'var(--bg-0)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: 18, boxShadow: 'var(--shadow-sm)', display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
        <span style={{ fontSize: 12, color: 'var(--fg-3)', fontWeight: 600, letterSpacing: '0.03em', textTransform: 'uppercase', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</span>
        {icon && <span style={{ width: 32, height: 32, borderRadius: 'var(--r-sm)', background: `var(--${tone === 'brand' ? 'brand' : tone}-soft, var(--brand-soft))`, color: `var(--${tone === 'brand' ? 'brand' : tone})`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{typeof icon === 'function' ? icon({ size: 17 }) : icon}</span>}
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 10 }}>
        <div style={{ minWidth: 0 }}>
          <div className="tnum" style={{ fontSize: 26, fontWeight: 700, color: 'var(--fg-1)', lineHeight: 1.1, letterSpacing: '-0.02em', display: 'flex', alignItems: 'baseline', gap: 4 }}>
            {value}{unit && <span style={{ fontSize: 13, color: 'var(--fg-3)', fontWeight: 500 }}>{unit}</span>}
          </div>
          {(delta != null || sub) && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 7 }}>
              {delta != null && (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 2, fontSize: 12, fontWeight: 600, color: up ? 'var(--ok)' : 'var(--danger)' }}>
                  {(up ? Icon.trending : Icon.trending)({ size: 13, style: { transform: up ? 'none' : 'scaleY(-1)' } })}
                  {up ? '+' : ''}{delta}%
                </span>
              )}
              {sub && <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>{sub}</span>}
            </div>
          )}
        </div>
        {spark && <div style={{ flexShrink: 0 }}><Sparkline data={spark} color={`var(--${tone === 'brand' ? 'brand' : tone})`} /></div>}
      </div>
    </div>
  );
}

/* ----------------------------- DataTable ----------------------------- */
// columns: [{ key, label, align, sortable, render, width, sortValue }]
function DataTable({ columns, rows, searchKeys, filters, pageSize = 8, onRowClick, empty, dense, rightTools, searchPlaceholder = 'Ara…', initialSort }) {
  const [q, setQ] = _dS('');
  const [page, setPage] = _dS(1);
  const [sort, setSort] = _dS(initialSort || null); // {key, dir}
  const [filterVals, setFilterVals] = _dS({});

  const filtered = _dM(() => {
    let r = rows;
    if (q && searchKeys) {
      const ql = q.toLowerCase();
      r = r.filter(row => searchKeys.some(k => String(row[k] ?? '').toLowerCase().includes(ql)));
    }
    if (filters) {
      for (const f of filters) {
        const v = filterVals[f.key];
        if (v != null && v !== '') r = r.filter(row => String(row[f.key]) === String(v));
      }
    }
    if (sort) {
      const col = columns.find(c => c.key === sort.key);
      r = [...r].sort((a, b) => {
        const av = col?.sortValue ? col.sortValue(a) : a[sort.key];
        const bv = col?.sortValue ? col.sortValue(b) : b[sort.key];
        if (av == null) return 1; if (bv == null) return -1;
        if (typeof av === 'number' && typeof bv === 'number') return sort.dir === 'asc' ? av - bv : bv - av;
        return sort.dir === 'asc' ? String(av).localeCompare(String(bv), 'tr') : String(bv).localeCompare(String(av), 'tr');
      });
    }
    return r;
  }, [rows, q, sort, filterVals, columns, searchKeys, filters]);

  const pages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const curPage = Math.min(page, pages);
  const pageRows = filtered.slice((curPage - 1) * pageSize, curPage * pageSize);

  const toggleSort = (key) => {
    setSort(s => s?.key === key ? (s.dir === 'asc' ? { key, dir: 'desc' } : null) : { key, dir: 'asc' });
  };
  React.useEffect(() => { setPage(1); }, [q, filterVals]);

  const cellPad = dense ? '9px 14px' : '13px 16px';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
      {(searchKeys || filters || rightTools) && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: '1px solid var(--border)', flexWrap: 'wrap' }}>
          {searchKeys && (
            <div style={{ flex: 1, minWidth: 200, maxWidth: 320 }}>
              <Input value={q} onChange={setQ} placeholder={searchPlaceholder} icon={Icon.search} />
            </div>
          )}
          {filters && filters.map(f => (
            <div key={f.key} style={{ minWidth: 150 }}>
              <Select value={filterVals[f.key] ?? ''} onChange={v => setFilterVals(s => ({ ...s, [f.key]: v }))} options={f.options} placeholder={f.placeholder || f.label} />
            </div>
          ))}
          <div style={{ flex: 1 }} />
          {rightTools}
        </div>
      )}
      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 560 }}>
          <thead>
            <tr>
              {columns.map(c => (
                <th key={c.key} onClick={c.sortable ? () => toggleSort(c.key) : undefined}
                  style={{ textAlign: c.align || 'left', padding: cellPad, fontSize: 11, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '0.04em', textTransform: 'uppercase', borderBottom: '1px solid var(--border)', cursor: c.sortable ? 'pointer' : 'default', whiteSpace: 'nowrap', width: c.width, background: 'var(--bg-0)', userSelect: 'none' }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, justifyContent: c.align === 'right' ? 'flex-end' : 'flex-start' }}>
                    {c.label}
                    {c.sortable && <span style={{ display: 'flex', color: sort?.key === c.key ? 'var(--brand)' : 'var(--fg-3)', opacity: sort?.key === c.key ? 1 : 0.4 }}>{sort?.key === c.key && sort.dir === 'desc' ? Icon.chevDown({ size: 13 }) : Icon.chevUp({ size: 13 })}</span>}
                  </span>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {pageRows.length === 0 ? (
              <tr><td colSpan={columns.length} style={{ padding: 0 }}>{empty || <EmptyState compact title="Kayıt bulunamadı" desc="Arama veya filtreleri değiştirin." />}</td></tr>
            ) : pageRows.map((row, ri) => (
              <tr key={row.id ?? ri} onClick={onRowClick ? () => onRowClick(row) : undefined}
                style={{ cursor: onRowClick ? 'pointer' : 'default', transition: 'background 100ms' }}
                onMouseEnter={e => { if (onRowClick) e.currentTarget.style.background = 'var(--bg-2)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}>
                {columns.map(c => (
                  <td key={c.key} style={{ textAlign: c.align || 'left', padding: cellPad, fontSize: 13.5, color: 'var(--fg-1)', borderBottom: '1px solid var(--border)', whiteSpace: c.wrap ? 'normal' : 'nowrap', fontVariantNumeric: c.align === 'right' ? 'tabular-nums' : 'normal' }}>
                    {c.render ? c.render(row) : row[c.key]}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {pages > 1 && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', gap: 12, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 12.5, color: 'var(--fg-3)' }} className="tnum">{filtered.length} kayıt · sayfa {curPage}/{pages}</span>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <IconButton icon={Icon.chevLeft} title="Önceki" onClick={() => setPage(p => Math.max(1, p - 1))} />
            {Array.from({ length: pages }, (_, i) => i + 1).filter(p => p === 1 || p === pages || Math.abs(p - curPage) <= 1).map((p, idx, arr) => (
              <React.Fragment key={p}>
                {idx > 0 && arr[idx - 1] !== p - 1 && <span style={{ color: 'var(--fg-3)', padding: '0 2px' }}>…</span>}
                <button onClick={() => setPage(p)} style={{ minWidth: 32, height: 32, borderRadius: 'var(--r-sm)', border: '1px solid ' + (p === curPage ? 'var(--brand)' : 'transparent'), background: p === curPage ? 'var(--brand-soft)' : 'transparent', color: p === curPage ? 'var(--brand)' : 'var(--fg-2)', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }} className="tnum">{p}</button>
              </React.Fragment>
            ))}
            <IconButton icon={Icon.chevRight} title="Sonraki" onClick={() => setPage(p => Math.min(pages, p + 1))} />
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { StatCard, DataTable });
