import { For, Show, createEffect, createMemo, createSignal, onMount } from 'solid-js';
import DashboardDesignPreview from '~/components/admin/DashboardDesignPreview';

const API = '';

type RoleOption = { id: string; key: string; name: string };

type InternalDashboard = {
  id: string;
  roleId: string;
  roleKey: string;
  name: string;
  code: string;
  widgets: string[];
  tabs: string[];
  sidebarItems: string[];
  fields: string[];
  status: 'ACTIVE' | 'INACTIVE' | 'DRAFT';
  updatedAt: string;
};

const AVAILABLE_WIDGETS = ['kpi_summary', 'pending_approvals', 'user_growth', 'active_sessions', 'system_health', 'recent_activity', 'quick_actions', 'team_performance'];
const AVAILABLE_TABS = ['overview', 'approvals', 'users', 'reports', 'audit_logs', 'settings'];
const AVAILABLE_SIDEBAR_ITEMS = ['dashboard', 'user_management', 'role_management', 'approvals', 'reports', 'settings'];
const AVAILABLE_FIELDS = ['employee_name', 'employee_email', 'department', 'designation', 'status', 'joined_date'];

function asStringArray(value: unknown): string[] {
  if (!Array.isArray(value)) return [];
  return value.map((item) => String(item || '').trim()).filter(Boolean);
}

function normalizeDashboard(item: any): InternalDashboard {
  const cfg = item?.config_json ?? {};
  const widgets = asStringArray(Array.isArray(cfg?.widgets) ? cfg.widgets.map((w: any) => (typeof w === 'string' ? w : (w?.key || w?.id))) : []);
  const tabs = asStringArray(cfg?.tabs);
  const sidebarItems = asStringArray(cfg?.sidebar_items ?? cfg?.sidebarItems);
  const fields = asStringArray(cfg?.fields);

  const isInactive = item?.is_active === false || String(item?.status || '').toUpperCase() === 'INACTIVE';
  const isDraft = String(item?.status || '').toUpperCase() === 'DRAFT';

  return {
    id: String(item?.id || ''),
    roleId: String(item?.role_id || ''),
    roleKey: String(cfg?.role_key || cfg?.roleKey || item?.role_key || ''),
    name: String(cfg?.name || item?.name || 'Internal Dashboard'),
    code: String(cfg?.code || item?.code || ''),
    widgets,
    tabs,
    sidebarItems,
    fields,
    status: isInactive ? 'INACTIVE' : (isDraft ? 'DRAFT' : 'ACTIVE'),
    updatedAt: String(item?.updated_at || ''),
  };
}

function StatusBadge(props: { status: string }) {
  const active = () => props.status === 'ACTIVE';
  return (
    <span style={`display:inline-flex;align-items:center;border-radius:9999px;border:1px solid ${active() ? '#FFD8C2' : '#D1D5DB'};background:${active() ? '#FFF1EB' : '#F3F4F6'};color:${active() ? '#FF5E13' : '#4B5563'};padding:2px 10px;font-size:12px;font-weight:500`}>
      {active() ? 'Active' : 'Inactive'}
    </span>
  );
}

export default function InternalDashboardManagementPage() {
  const [rows, setRows] = createSignal<InternalDashboard[]>([]);
  const [roles, setRoles] = createSignal<RoleOption[]>([]);
  const [loading, setLoading] = createSignal(false);
  const [saving, setSaving] = createSignal(false);
  const [error, setError] = createSignal('');

  const [view, setView] = createSignal<'list' | 'form'>('list');
  const [editingId, setEditingId] = createSignal<string | null>(null);
  const [formTab, setFormTab] = createSignal<'general' | 'tabs' | 'sidebar' | 'fields' | 'preview'>('general');
  const [listTab, setListTab] = createSignal<'all' | 'create'>('all');

  const [search, setSearch] = createSignal('');
  const [statusFilter, setStatusFilter] = createSignal<'all' | 'active' | 'inactive'>('all');
  const [sortBy, setSortBy] = createSignal<'name_asc' | 'name_desc' | 'updated_desc' | 'updated_asc'>('updated_desc');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);

  const [name, setName] = createSignal('');
  const [code, setCode] = createSignal('');
  const [roleId, setRoleId] = createSignal('');
  const [widgets, setWidgets] = createSignal<string[]>([]);
  const [tabs, setTabs] = createSignal<string[]>([]);
  const [sidebarItems, setSidebarItems] = createSignal<string[]>([]);
  const [fields, setFields] = createSignal<string[]>([]);
  const [isActive, setIsActive] = createSignal(true);
  const [activePreviewSidebar, setActivePreviewSidebar] = createSignal('');
  const [activePreviewTab, setActivePreviewTab] = createSignal('');

  const previewSidebarItems = createMemo(() => (sidebarItems().length ? sidebarItems() : ['dashboard', 'user_management', 'settings']));
  const previewTabs = createMemo(() => (tabs().length ? tabs() : ['overview']));

  createEffect(() => {
    const items = previewSidebarItems();
    if (!items.includes(activePreviewSidebar())) setActivePreviewSidebar(items[0] || '');
  });

  createEffect(() => {
    const list = previewTabs();
    if (!list.includes(activePreviewTab())) setActivePreviewTab(list[0] || '');
  });

  const authHeaders = () => {
    const token = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('nxtgauge_admin_access_token') || '' : '';
    return { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) };
  };

  const toggle = (list: () => string[], setter: (v: string[] | ((p: string[]) => string[])) => void, value: string) => {
    setter((prev: string[]) => (prev.includes(value) ? prev.filter((v) => v !== value) : [...prev, value]));
  };

  const loadAll = async () => {
    setLoading(true);
    setError('');
    try {
      const [dashRes, rolesRes] = await Promise.all([
        fetch(`${API}/api/admin/dashboard-config`, { headers: authHeaders(), credentials: 'include' }),
        fetch(`${API}/api/admin/roles?audience=INTERNAL&per_page=200`, { headers: authHeaders(), credentials: 'include' }),
      ]);

      const dashData = dashRes.ok ? await dashRes.json().catch(() => []) : [];
      const roleData = rolesRes.ok ? await rolesRes.json().catch(() => []) : [];

      const dashRows = Array.isArray(dashData) ? dashData : (dashData?.items || dashData?.configs || []);
      const roleRows = Array.isArray(roleData) ? roleData : (roleData?.roles || roleData?.items || []);

      setRoles(roleRows
        .filter((r: any) => String(r?.audience || '').toUpperCase() === 'INTERNAL')
        .map((r: any) => ({ id: String(r?.id || ''), key: String(r?.key || '').toUpperCase(), name: String(r?.name || r?.key || 'Internal Role') }))
        .filter((r: RoleOption) => r.id));

      setRows(dashRows
        .filter((item: any) => String(item?.audience || '').toUpperCase() === 'INTERNAL')
        .map(normalizeDashboard)
        .sort((a: InternalDashboard, b: InternalDashboard) => b.updatedAt.localeCompare(a.updatedAt)));
    } catch (e: any) {
      setRows([]);
      setRoles([]);
      setError(e?.message || 'Failed to load internal dashboards.');
    } finally {
      setLoading(false);
    }
  };

  onMount(() => void loadAll());

  const filtered = createMemo(() => {
    const q = search().trim().toLowerCase();
    const next = rows().filter((row) => {
      if (statusFilter() === 'active' && row.status !== 'ACTIVE') return false;
      if (statusFilter() === 'inactive' && row.status === 'ACTIVE') return false;
      if (!q) return true;
      return row.name.toLowerCase().includes(q) || row.code.toLowerCase().includes(q) || row.roleKey.toLowerCase().includes(q);
    });
    next.sort((a, b) => {
      if (sortBy() === 'name_asc') return a.name.localeCompare(b.name);
      if (sortBy() === 'name_desc') return b.name.localeCompare(a.name);
      if (sortBy() === 'updated_asc') return a.updatedAt.localeCompare(b.updatedAt);
      return b.updatedAt.localeCompare(a.updatedAt);
    });
    return next;
  });

  const resetForm = () => {
    setEditingId(null);
    setFormTab('general');
    setName('');
    setCode('');
    setRoleId(roles()[0]?.id || '');
    setWidgets([]);
    setTabs([]);
    setSidebarItems([]);
    setFields([]);
    setIsActive(true);
  };

  const openCreate = () => { resetForm(); setListTab('create'); setView('form'); };

  const openEdit = (row: InternalDashboard) => {
    setEditingId(row.id);
    setFormTab('general');
    setName(row.name);
    setCode(row.code);
    setRoleId(row.roleId);
    setWidgets(row.widgets);
    setTabs(row.tabs);
    setSidebarItems(row.sidebarItems);
    setFields(row.fields);
    setIsActive(row.status === 'ACTIVE');
    setListTab('create');
    setView('form');
  };

  const saveDashboard = async () => {
    if (!name().trim()) return setError('Dashboard name is required.');
    if (!roleId()) return setError('Internal role is required.');

    const selectedRole = roles().find((r) => r.id === roleId());
    if (!selectedRole) return setError('Selected role is invalid.');

    setSaving(true);
    setError('');
    try {
      const res = await fetch(`${API}/api/admin/dashboard-config`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...authHeaders() },
        credentials: 'include',
        body: JSON.stringify({
          role_id: roleId(),
          audience: 'INTERNAL',
          is_active: isActive(),
          config_json: {
            name: name().trim(),
            code: code().trim() || `INTERNAL-${selectedRole.key}`,
            role_key: selectedRole.key,
            widgets: widgets().map((key) => ({ key })),
            tabs: tabs(),
            sidebar_items: sidebarItems(),
            fields: fields(),
          },
        }),
      });
      const payload = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(payload?.message || `Request failed (${res.status})`);
      await loadAll();
      setView('list');
      setListTab('all');
      resetForm();
    } catch (e: any) {
      setError(e?.message || 'Failed to save internal dashboard.');
    } finally {
      setSaving(false);
    }
  };

  return (
      <div class="w-full space-y-6 pb-8">
        <div>
          <h1 class="text-[28px] font-bold leading-tight text-[#111827]">Internal Dashboard Management</h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">Create dashboards with tabs, sidebar and fields, then preview before saving.</p>
        </div>

        <Show when={error()}>
          <div style="border-radius:10px;border:1px solid #FECACA;background:#FEF2F2;padding:12px 16px;font-size:13px;color:#B91C1C">{error()}</div>
        </Show>

        <Show when={view() === 'list'} fallback={
          <div style="border-radius:16px;border:1px solid #E5E7EB;background:white;box-shadow:0 1px 4px rgba(0,0,0,0.06);overflow:hidden">
            <div style="padding:18px 24px;border-bottom:1px solid #E5E7EB;display:flex;justify-content:space-between;align-items:center">
              <p style="margin:0;font-size:16px;font-weight:700;color:#111827">{editingId() ? 'Edit Internal Dashboard' : 'Create Internal Dashboard'}</p>
              <button type="button" onClick={() => { setView('list'); resetForm(); }} style="height:34px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:12px;font-weight:700;color:#374151;cursor:pointer">Back</button>
            </div>

            <div style="display:flex;gap:4px;border-bottom:1px solid #E5E7EB;padding:0 16px;background:#FAFAFA">
              <For each={['general', 'tabs', 'sidebar', 'fields', 'preview'] as const}>{(tab) => (
                <button type="button" onClick={() => setFormTab(tab)} style={`position:relative;padding:12px 10px;font-size:12px;font-weight:700;border:none;background:none;cursor:pointer;color:${formTab() === tab ? '#FF5E13' : '#6B7280'}`}>
                  {tab.toUpperCase()}
                  <Show when={formTab() === tab}><span style="position:absolute;left:0;right:0;bottom:0;height:2px;background:#FF5E13" /></Show>
                </button>
              )}</For>
            </div>

            <div style="padding:24px">
              <Show when={formTab() === 'general'}>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
                  <label style="display:block"><span style="font-size:13px;font-weight:600;color:#374151">Dashboard Name *</span><input value={name()} onInput={(e) => setName(e.currentTarget.value)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px" /></label>
                  <label style="display:block"><span style="font-size:13px;font-weight:600;color:#374151">Code</span><input value={code()} onInput={(e) => setCode(e.currentTarget.value)} placeholder="Optional" style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px" /></label>
                  <label style="display:block;grid-column:1 / -1"><span style="font-size:13px;font-weight:600;color:#374151">Internal Role *</span><select value={roleId()} onChange={(e) => setRoleId(e.currentTarget.value)} style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;padding:0 14px;font-size:13px;background:white"><For each={roles()}>{(r) => <option value={r.id}>{r.name} ({r.key})</option>}</For></select></label>
                  <div style="grid-column:1 / -1"><span style="font-size:13px;font-weight:600;color:#374151">Widgets</span><div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:8px"><For each={AVAILABLE_WIDGETS}>{(key) => <button type="button" onClick={() => toggle(widgets, setWidgets, key)} style={`height:30px;border-radius:8px;padding:0 10px;font-size:11px;font-weight:700;cursor:pointer;border:1px solid ${widgets().includes(key) ? '#0D0D2A' : '#E5E7EB'};background:${widgets().includes(key) ? '#0D0D2A' : 'white'};color:${widgets().includes(key) ? 'white' : '#374151'}`}>{key}</button>}</For></div></div>
                  <label style="display:flex;align-items:center;gap:8px;grid-column:1 / -1;font-size:13px;color:#374151"><input type="checkbox" checked={isActive()} onChange={(e) => setIsActive(e.currentTarget.checked)} style="width:16px;height:16px;accent-color:#0D0D2A" />Active dashboard</label>
                </div>
              </Show>

              <Show when={formTab() === 'tabs'}>
                <div><p style="font-size:13px;font-weight:600;color:#374151">Dashboard Tabs</p><div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:8px"><For each={AVAILABLE_TABS}>{(key) => <button type="button" onClick={() => toggle(tabs, setTabs, key)} style={`height:30px;border-radius:8px;padding:0 10px;font-size:11px;font-weight:700;cursor:pointer;border:1px solid ${tabs().includes(key) ? '#0D0D2A' : '#E5E7EB'};background:${tabs().includes(key) ? '#0D0D2A' : 'white'};color:${tabs().includes(key) ? 'white' : '#374151'}`}>{key}</button>}</For></div></div>
              </Show>

              <Show when={formTab() === 'sidebar'}>
                <div><p style="font-size:13px;font-weight:600;color:#374151">Sidebar Items</p><div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:8px"><For each={AVAILABLE_SIDEBAR_ITEMS}>{(key) => <button type="button" onClick={() => toggle(sidebarItems, setSidebarItems, key)} style={`height:30px;border-radius:8px;padding:0 10px;font-size:11px;font-weight:700;cursor:pointer;border:1px solid ${sidebarItems().includes(key) ? '#0D0D2A' : '#E5E7EB'};background:${sidebarItems().includes(key) ? '#0D0D2A' : 'white'};color:${sidebarItems().includes(key) ? 'white' : '#374151'}`}>{key}</button>}</For></div></div>
              </Show>

              <Show when={formTab() === 'fields'}>
                <div><p style="font-size:13px;font-weight:600;color:#374151">Visible Fields</p><div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:8px"><For each={AVAILABLE_FIELDS}>{(key) => <button type="button" onClick={() => toggle(fields, setFields, key)} style={`height:30px;border-radius:8px;padding:0 10px;font-size:11px;font-weight:700;cursor:pointer;border:1px solid ${fields().includes(key) ? '#0D0D2A' : '#E5E7EB'};background:${fields().includes(key) ? '#0D0D2A' : 'white'};color:${fields().includes(key) ? 'white' : '#374151'}`}>{key}</button>}</For></div></div>
              </Show>

              <Show when={formTab() === 'preview'}>
                <div style="display:flex;flex-direction:column;gap:10px">
                  <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px 12px;border:1px solid #E5E7EB;border-radius:10px;background:#FAFAFA">
                    <div>
                      <p style="margin:0;font-size:13px;font-weight:700;color:#111827">Compact Preview</p>
                      <p style="margin:2px 0 0;font-size:12px;color:#6B7280">Validate sidebar, tabs, and fields for internal role dashboard preview.</p>
                    </div>
                  </div>
                  <div style="border:1px solid #E5E7EB;border-radius:12px;background:#F9FAFB;padding:10px 12px">
                    <p style="margin:0;font-size:12px;font-weight:800;color:#374151">Config Snapshot (Instant)</p>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:8px">
                      <div>
                        <p style="margin:0;font-size:11px;font-weight:800;color:#6B7280;text-transform:uppercase">Widgets</p>
                        <div style="display:flex;flex-wrap:wrap;gap:6px;margin-top:6px">
                          <For each={widgets().length ? widgets() : ['(none)']}>
                            {(w) => <span style="padding:2px 8px;border-radius:999px;border:1px solid #E5E7EB;background:white;font-size:11px;color:#374151">{w}</span>}
                          </For>
                        </div>
                      </div>
                      <div>
                        <p style="margin:0;font-size:11px;font-weight:800;color:#6B7280;text-transform:uppercase">Tabs</p>
                        <div style="display:flex;flex-wrap:wrap;gap:6px;margin-top:6px">
                          <For each={tabs().length ? tabs() : ['(none)']}>
                            {(t) => <span style="padding:2px 8px;border-radius:999px;border:1px solid #E5E7EB;background:white;font-size:11px;color:#374151">{t}</span>}
                          </For>
                        </div>
                      </div>
                    </div>
                  </div>
                  <DashboardDesignPreview
                    status={isActive() ? 'ACTIVE' : 'INACTIVE'}
                    sidebarItems={previewSidebarItems()}
                    activeSidebar={activePreviewSidebar()}
                    onSidebarSelect={setActivePreviewSidebar}
                    tabs={previewTabs()}
                    activeTab={activePreviewTab()}
                    onTabSelect={setActivePreviewTab}
                    widgets={widgets()}
                    fields={fields()}
                  />
                </div>
              </Show>
            </div>

            <div style="padding:14px 24px;border-top:1px solid #E5E7EB;display:flex;justify-content:flex-end;gap:10px">
              <button type="button" onClick={() => { setView('list'); resetForm(); }} style="height:38px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 20px;font-size:13px;font-weight:600;color:#374151;cursor:pointer">Cancel</button>
              <button type="button" onClick={() => void saveDashboard()} disabled={saving()} style="height:38px;border-radius:10px;background:#0D0D2A;padding:0 24px;font-size:13px;font-weight:600;color:white;border:none;cursor:pointer;opacity:0.95">{saving() ? 'Saving...' : (editingId() ? 'Update Dashboard' : 'Create Dashboard')}</button>
            </div>
          </div>
        }>
          <div style="margin-top:24px;display:flex;align-items:center;gap:24px;border-bottom:1px solid #E5E7EB">
            <button type="button" onClick={() => { setListTab('all'); setView('list'); }} style={`padding-bottom:12px;font-size:14px;font-weight:500;background:none;border:none;cursor:pointer;${listTab() === 'all' ? 'color:#FF5E13;border-bottom:2px solid #FF5E13;margin-bottom:-1px' : 'color:#6B7280'}`}>All Dashboards</button>
            <button type="button" onClick={openCreate} style={`padding-bottom:12px;font-size:14px;font-weight:500;background:none;border:none;cursor:pointer;${listTab() === 'create' ? 'color:#FF5E13;border-bottom:2px solid #FF5E13;margin-bottom:-1px' : 'color:#6B7280'}`}>Create Dashboard</button>
          </div>

          <div style="position:relative;margin-top:1.5rem;margin-left:-24px;margin-right:-24px;border-radius:0;border-left:none;border-right:none;overflow:visible;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
            <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6">
              <input value={search()} onInput={(e) => setSearch(e.currentTarget.value)} placeholder="Search dashboards..." style="height:34px;flex:1;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none" />
              <div style="position:relative">
                <button type="button" onClick={() => { setSortMenuOpen((v) => !v); setFilterMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 4v13"/><path d="m3 13 4 4 4-4"/><path d="M17 20V7"/><path d="m21 11-4-4-4 4"/></svg>
                  Sort
                </button>
                <Show when={sortMenuOpen()}>
                  <div style="position:absolute;left:0;top:38px;z-index:30;min-width:200px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                    <For each={[
                      ['name_asc', 'Name (A-Z)'],
                      ['name_desc', 'Name (Z-A)'],
                      ['updated_desc', 'Updated (Newest)'],
                      ['updated_asc', 'Updated (Oldest)'],
                    ] as const}>{([key, label]) => (
                      <button type="button" onClick={() => { setSortBy(key); setSortMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${sortBy() === key ? '#FF5E13' : '#374151'};background:${sortBy() === key ? '#FFF1EB' : 'transparent'}`}>{label}</button>
                    )}</For>
                  </div>
                </Show>
              </div>
              <div style="position:relative">
                <button type="button" onClick={() => { setFilterMenuOpen((v) => !v); setSortMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18M6 12h12M10 19h4"/></svg>
                  Filters
                </button>
                <Show when={filterMenuOpen()}>
                  <div style="position:absolute;left:0;top:38px;z-index:30;min-width:160px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                    <For each={[
                      ['all', 'All Status'],
                      ['active', 'Active'],
                      ['inactive', 'Inactive'],
                    ] as const}>{([key, label]) => (
                      <button type="button" onClick={() => { setStatusFilter(key); setFilterMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${statusFilter() === key ? '#FF5E13' : '#374151'};background:${statusFilter() === key ? '#FFF1EB' : 'transparent'}`}>{label}</button>
                    )}</For>
                  </div>
                </Show>
              </div>
              <button type="button" style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                Export
              </button>
            </div>

            <div class="overflow-x-auto overflow-y-visible">
              <table class="min-w-full">
                <thead>
                  <tr style="background:#0D0D2A;text-align:left">
                    <For each={['Name', 'Code', 'Role', 'Widgets', 'Status', 'Updated', 'Actions']}>{(h) => (
                      <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">{h}</th>
                    )}</For>
                  </tr>
                </thead>
                <tbody>
                  <Show when={!loading()} fallback={<tr><td colspan="7" style="padding:18px 20px;color:#6B7280;font-size:13px">Loading dashboards...</td></tr>}>
                    <Show when={filtered().length > 0} fallback={<tr><td colspan="7" style="padding:18px 20px;color:#6B7280;font-size:13px">No internal dashboards found.</td></tr>}>
                      <For each={filtered()}>
                        {(row) => (
                          <tr style="border-bottom:1px solid #F3F4F6" class="hover:bg-[#FAFAFA] transition-colors">
                            <td style="padding:12px 20px;font-size:14px;font-weight:600;color:#111827">{row.name}</td>
                            <td style="padding:12px 20px;font-size:12px;color:#6B7280;font-family:monospace">{row.code || '—'}</td>
                            <td style="padding:12px 20px;font-size:13px;color:#374151">{row.roleKey || '—'}</td>
                            <td style="padding:12px 20px;font-size:13px;color:#374151">{row.widgets.length}</td>
                            <td style="padding:12px 20px"><StatusBadge status={row.status} /></td>
                            <td style="padding:12px 20px;font-size:13px;color:#6B7280">{row.updatedAt ? new Date(row.updatedAt).toLocaleString() : '—'}</td>
                            <td style="padding:12px 20px">
                              <button type="button" onClick={() => openEdit(row)} style="height:30px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:700;color:#374151;cursor:pointer">Edit</button>
                            </td>
                          </tr>
                        )}
                      </For>
                    </Show>
                  </Show>
                </tbody>
              </table>
            </div>

            <Show when={filtered().length > 0}>
              <div style="display:flex;align-items:center;justify-content:space-between;border-top:1px solid #F3F4F6;padding:12px 20px">
                <p style="font-size:13px;color:#6B7280">
                  Showing <strong style="font-weight:600;color:#111827">1–{filtered().length}</strong> of <strong style="font-weight:600;color:#111827">{filtered().length}</strong> dashboards
                </p>
                <div style="display:flex;align-items:center;gap:4px">
                  <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#6B7280;cursor:pointer;font-size:15px">‹</button>
                  <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;background:#FF5E13;color:white;font-size:13px;font-weight:600;border:none;cursor:pointer">1</button>
                  <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#6B7280;cursor:pointer;font-size:15px">›</button>
                </div>
              </div>
            </Show>
          </div>
        </Show>
      </div>
  );
}
