import { useState, useEffect, useCallback } from 'react'

import { Badge } from "./components/ui/badge"
import { Tabs, TabsContent } from "./components/ui/tabs"
import { toast } from "sonner"
import {
  CheckCircle2,
  RefreshCw,
  UserPlus,
  Database,
  Server,
  Clock,
  Wrench,
  ShieldCheck,
  AlertCircle,
  Info,
  XCircle,
  ShieldAlert,
  Copy,
  Eraser,
  Trash2,
  Zap,
  Layout,
  ChevronDown,
  ChevronUp,
  Activity
} from 'lucide-react'
import {
  SettingCard,
  BannerCard,
  FlatTabs,
  SettingsLayout,
  SettingsHeader,
  PrimaryButton,
  OutlineButton,
  ModernCardHeader
} from "./components/ui/settings-ui"

import type { DashboardData, SystemData } from './types';

interface DashboardWindow {
  wawpDashboardData?: { 
    domainStatus?: string; 
    currentSection?: string;
  };
}

export default function SystemInfo({ data: dashboardData }: { data: DashboardData }) {
  const [data, setData] = useState<SystemData | undefined>(dashboardData?.systemInfo)
  const [loading, setLoading] = useState(!dashboardData?.systemInfo)
  const [activeTab, setActiveTab] = useState('wordpress')
  const [activeAction, setActiveAction] = useState<string | null>(null)
  const [showAllIssues, setShowAllIssues] = useState(true)

  useEffect(() => {
    if (dashboardData?.systemInfo) {
      setData(dashboardData.systemInfo);
      setLoading(false);
    }
  }, [dashboardData]);

  const refreshStatus = useCallback(async () => {
    setLoading(true)
    setActiveAction('refresh')
    try {
      const res = await fetch(`${dashboardData.global.apiRestUrl}/system/status`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        }
      })
      const json = await res.json()
      if (json.success) {
        setData(json.data.data)
        toast.success(dashboardData.i18n?.refreshSuccess || 'Status refreshed')
      }
    } catch {
      toast.error('Failed to refresh status')
    } finally {
      setLoading(false)
      setActiveAction(null)
    }
  }, [dashboardData])

  useEffect(() => {
    if (!data && dashboardData?.ajaxUrl) {
      refreshStatus()
    }
  }, [data, dashboardData?.ajaxUrl, refreshStatus])

  const dStat = dashboardData?.domainStatus || (window as unknown as DashboardWindow).wawpDashboardData?.domainStatus;
  const cSec = dashboardData?.global?.section || (window as unknown as DashboardWindow).wawpDashboardData?.currentSection;

  if (dStat && dStat !== 'active' && cSec !== 'connector') return null;
  if (!data) return null;

  const isRtl = dashboardData?.rtl || document.documentElement.dir === 'rtl'
  const t = dashboardData?.i18n

  const syncUsers = async () => {
    setLoading(true)
    setActiveAction('sync')
    try {
      const res = await fetch(`${dashboardData.global.apiRestUrl}/system/sync-users`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        }
      })
      await res.json()
      toast.success(t.syncSuccess || 'User sync complete')
      refreshStatus()
    } catch {
      toast.error('User sync failed')
    } finally {
      setLoading(false)
      setActiveAction(null)
    }
  }

  const repairAll = async () => {
    setLoading(true)
    setActiveAction('repairAll')
    try {
      const res = await fetch(`${dashboardData.global.apiRestUrl}/system/repair`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        }
      })
      const json = await res.json()
      if (json.success) {
        setData(json.data.data)
        toast.success(t.repairSuccess || 'All issues repaired')
      }
    } catch {
      toast.error('Failed to repair issues')
    } finally {
      setLoading(false)
      setActiveAction(null)
    }
  }

  const handleDbAction = async (action: 'truncate' | 'delete' | 'create' | 'repair', table: string) => {
    const confirmMsg = action === 'delete' ? t.confirmDeleteTable : t.confirmEmptyTable;
    if (['truncate', 'delete'].includes(action) && !confirm(`${confirmMsg || 'Are you sure?'} (${table})`)) return

    setLoading(true)
    try {
      const res = await fetch(`${dashboardData.global.apiRestUrl}/system/db/${action}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({ table })
      })
      const json = await res.json()
      if (json.success) {
        toast.success(json.data?.message || 'Action executed')
        refreshStatus()
      } else {
        toast.error(json.data?.message || 'Action failed')
      }
    } catch {
      toast.error('Network error executing database action')
    } finally {
      setLoading(false)
    }
  }

  const handleScheduleCron = async (hook: string) => {
    setLoading(true)
    try {
      const res = await fetch(`${dashboardData.global.apiRestUrl}/system/schedule-cron`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({ hook })
      })
      const json = await res.json()
      if (json.success) {
        toast.success(json.data?.message || 'Task scheduled')
        refreshStatus()
      } else {
        toast.error(json.data?.message || 'Failed to schedule task')
      }
    } catch {
      toast.error('Failed to schedule task')
    } finally {
      setLoading(false)
    }
  }

  const copyForSupport = () => {
    if (!data) return
    let text = `=== WAWP SYSTEM INFO REPORT ===\n`
    text += `Generated at: ${new Date().toLocaleString()}\n`
    text += `Status: ${data.status.toUpperCase()}\n\n`

    text += `### WordPress Environment ###\n`
    data.wp_env.forEach(i => text += `${i.label}: ${i.value} [${i.status}]\n`)

    text += `\n### Server Environment ###\n`
    data.server_env.forEach(i => text += `${i.label}: ${i.value} [${i.status}]\n`)

    text += `\n### WordPress Configuration ###\n`
    text += `Active Theme: ${data.wp_config.theme}\n`
    text += `Active Plugins:\n`
    data.wp_config.plugins.forEach(p => text += `- ${p}\n`)

    text += `\n### Wawp System Health Checks ###\n`
    data.health_checks.forEach(c => text += `${c.label}: ${c.status} - ${c.details} [${c.level}]\n`)

    text += `\n### WP-Cron Status ###\n`
    text += `Cron Engine: ${data.cron.enabled ? 'Enabled' : 'Disabled'}\n`
    data.cron.events.forEach(e => text += `- ${e.hook}: ${e.status} (Next: ${e.next_run})\n`)

    text += `\n### Database Tables Status ###\n`
    data.database.forEach(t => text += `${t.name}: ${t.status} ${t.missing ? '(' + t.missing + ')' : ''}\n`)

    text += `\n### Security & Core Configuration ###\n`
    data.security.forEach(s => text += `${s.label}: ${s.status} - ${s.message}\n`)

    text += `\n### Feature Status (Local) ###\n`
    const features = dashboardData.features || {}
    Object.keys(features).forEach(k => {
      text += `${k}: ${features[k].enabled ? 'Enabled' : 'Disabled'} (Allowed: ${features[k].allowed ? 'Yes' : 'No'})\n`
    })

    navigator.clipboard.writeText(text)
    toast.success(t?.copied || 'Copied to clipboard', {
      description: t?.copySuccessMsg || 'Diagnostic report copied successfully.'
    })
  }


  const isIssue = (s: string) => {
    if (!s || typeof s !== 'string') return false;
    const l = s.toLowerCase();
    return l.includes('error') || l.includes('warning') || l.includes('misconfigured') || l.includes('failure') || l.includes('missing') || l.includes('disconnected') || l.includes('incomplete') || l.includes('issue');
  }

  const getStatusChip = (s: string) => {
    if (!s || typeof s !== 'string') return null;
    const s_lower = s.toLowerCase();
    const isOk = s_lower === 'ok' || s_lower === 'healthy' || s_lower === 'enabled' || s_lower === 'writable' || s_lower === 'accessible' || s_lower === 'scheduled' || s_lower === 'active';
    const isWarning = s_lower.includes('warning') || s_lower.includes('misconfigured') || s_lower.includes('pending');
    const isError = s_lower.includes('error') || s_lower.includes('critical') || s_lower.includes('disconnected') || s_lower.includes('disabled') || s_lower.includes('missing') || s_lower.includes('failure') || s_lower.includes('incomplete');

    let bg = 'bg-gray-100/50 text-gray-600';
    let icon = <Info className="w-3 h-3" />;

    if (isOk) {
      bg = 'bg-emerald-50 text-emerald-700';
      icon = <CheckCircle2 className="w-3 h-3" />;
    } else if (isWarning) {
      bg = 'bg-amber-50 text-amber-700';
      icon = <AlertCircle className="w-3 h-3" />;
    } else if (isError) {
      bg = 'bg-rose-50 text-rose-700';
      icon = <XCircle className="w-3 h-3" />;
    }

    return (
      <Badge variant="secondary" className={`inline-flex items-center flex-row font-bold px-2.5 py-1 text-[10px] uppercase tracking-wider gap-2 border-none shadow-none whitespace-nowrap min-w-max h-auto ${bg}`}>
        {icon}
        <span className="leading-none">{s}</span>
      </Badge>
    )
  }

  const getAllIssues = () => {
    interface Issue {
      label: string;
      status: string;
      group: string;
    }
    const issues: Issue[] = [];
    if (!data) return issues;

    (data.wp_env || []).filter(i => isIssue(i.status)).forEach(i => issues.push({ label: i.label, status: (i.label === 'WP_DEBUG') ? 'Warning' : i.status, group: (t?.tabWordpress as string) || 'WordPress' }));
    (data.server_env || []).filter(i => isIssue(i.status)).forEach(i => issues.push({ label: i.label, status: i.status || 'Issue', group: (t?.tabServer as string) || 'Server' }));
    (data.health_checks || []).filter(i => isIssue(i.status) || isIssue(i.level)).forEach(i => issues.push({ label: i.label, status: i.status || 'Issue', group: 'Wawp' }));
    (data.database || []).filter(i => isIssue(i.status) || i.state !== 'ok').forEach(i => issues.push({ label: i.name, status: i.status || 'Issue', group: (t?.tabDatabase as string) || 'Database' }));

    (data.security || []).forEach(i => {
      if (i.label === "WordPress Debug Mode" || i.label === "WP_DEBUG") return;
      if (isIssue(i.status)) {
        let status = i.status;
        if (i.label === "Debug Log") {
          status = "Warning";
        }
        issues.push({ label: i.label, status: status, group: (t?.tabSecurity as string) || 'Security' });
      }
    });

    if (!data.cron.enabled) {
      issues.push({ label: (t?.cronStatusTitle as string) || 'Cron Engine', status: (t?.disabled as string) || 'Disabled', group: 'Cron' });
    }
    if (data.cron && data.cron.events) {
      data.cron.events.filter(e => isIssue(e.status) || e.state === 'disabled').forEach(e => {
        issues.push({ label: e.hook, status: e.status, group: 'Cron' });
      });
    }

    return issues;
  }

  const getStatusBanner = () => {
    const issuesList = getAllIssues();
    let status: 'healthy' | 'warning' | 'issues' = 'healthy';
    if (issuesList.length > 0) {
      const hasErrors = issuesList.some(i => i.status.toLowerCase().includes('error') || i.status.toLowerCase().includes('critical') || i.status.toLowerCase().includes('failure'));
      status = hasErrors ? 'issues' : 'warning';
    }

    const config = {
      healthy: {
        lightBg: 'bg-emerald-50/30',
        borderColor: 'border-emerald-200/50',
        icon: <ShieldCheck className="w-5 h-5 text-emerald-500" />,
        title: t.allSystemsOperational || 'System Infrastructure is Healthy',
        desc: data.header.desc || (t.healthyBannerDesc || 'Everything is running smoothly.')
      },
      warning: {
        lightBg: 'bg-amber-50/30',
        borderColor: 'border-amber-200/50',
        icon: <AlertCircle className="w-5 h-5 text-amber-500" />,
        title: t.attentionNeeded || 'Optimizations Recommended',
        desc: issuesList.length > 0
          ? `We found ${issuesList.length} system ${issuesList.length === 1 ? 'issue' : 'issues'} that could be optimized.`
          : (data.header.desc || t.warningBannerDesc || 'Some non-critical issues were found.')
      },
      issues: {
        lightBg: 'bg-rose-50/30',
        borderColor: 'border-rose-200/50',
        icon: <ShieldAlert className="w-5 h-5 text-rose-500" />,
        title: t.criticalIssuesFound || 'Critical Infrastructure Alert',
        desc: issuesList.length > 0
          ? `We found ${issuesList.length} critical system ${issuesList.length === 1 ? 'issue' : 'issues'} that need fixing.`
          : (data.header.desc || t.issuesBannerDesc || 'Major components need your attention.')
      }
    };

    const { icon, title, desc, lightBg, borderColor } = config[status] || config.healthy;

    const hasRepairableContent = () => {
      const hasDbIssues = (data.database || []).some(t => t.can_create || t.can_repair || t.missing);
      const hasCronIssues = !data.cron.enabled || (data.cron.events || []).some(e => e.status?.toLowerCase().includes('error') || e.status?.toLowerCase().includes('missing'));
      return (data.header.repairable > 0) && (hasDbIssues || hasCronIssues);
    };

    return (
      <SettingCard className="p-0 overflow-hidden mb-8 shadow-none">
        <ModernCardHeader
          title={title}
          description={desc}
          icon={() => <div className={`p-1.5 rounded-[4px] border ${lightBg} ${borderColor} flex items-center justify-center`}>{icon}</div>}
          rightAction={
            <div className="flex flex-wrap items-center gap-2.5">
              {hasRepairableContent() && (
                <PrimaryButton onClick={repairAll} loading={loading && activeAction === 'repairAll'} className="bg-rose-600 hover:bg-rose-700 h-9 px-4 text-xs">
                  <Wrench className="w-3.5 h-3.5 mr-1.5" />
                  {t.repairAll || 'Repair All'}
                </PrimaryButton>
              )}
              <OutlineButton onClick={refreshStatus} disabled={loading} className="h-9 px-4 text-xs">
                <RefreshCw className={`w-3.5 h-3.5 mr-1.5 ${loading && activeAction === 'refresh' ? 'animate-spin' : ''}`} />
                {t.refreshStatus || 'Refresh'}
              </OutlineButton>
            </div>
          }
        />

        <div className="p-6">
          {data.header.banner_text && (
            <div className="mb-6">
              <p className="text-[11px] text-[#004449] font-bold px-3 py-1.5 bg-[#004449]/5 rounded border border-[#004449]/10 w-fit">
                {data.header.banner_text}
              </p>
            </div>
          )}

          {issuesList.length > 0 && (
            <div className="space-y-4">
              <div className="flex items-center justify-between px-1">
                <div className="flex items-center gap-3">
                  <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{t.itemsNeededAttention || 'Infrastructure Alerts'}</span>
                  <Badge variant="secondary" className="bg-rose-50 text-rose-600 border-none px-2 py-0.5 rounded-[3px] text-[10px] font-black">{issuesList.length}</Badge>
                </div>
                <button onClick={() => setShowAllIssues(!showAllIssues)} className="text-[10px] font-black text-slate-400 hover:text-slate-600 transition-colors uppercase tracking-widest flex items-center gap-1.5">
                  {showAllIssues ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
                  {showAllIssues ? (t.hideList || 'Collapse Metrics') : (t.showList || 'View Breakdown')}
                </button>
              </div>

              {showAllIssues && (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 animate-in fade-in slide-in-from-top-2 duration-400">
                  {issuesList.map((issue, i) => (
                    <div key={i} className="flex items-center justify-between p-4 bg-gray-50/50 rounded-[5px] border border-gray-100 group transition-all hover:bg-white hover:border-[#dcdcde]">
                      <div className="flex flex-col min-w-0 text-start">
                        <span className="text-[9px] font-black text-slate-400 uppercase leading-none mb-1.5 truncate tracking-widest">{issue.group}</span>
                        <span className="text-[13px] font-bold text-gray-700 truncate">{issue.label}</span>
                      </div>
                      <div className="ms-3 flex-shrink-0">
                        {getStatusChip(issue.status)}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      </SettingCard>
    )
  }

  return (
    <SettingsLayout
      id="wawp-system-info"
      dir={isRtl ? "rtl" : "ltr"}
      style={{ fontFamily: isRtl ? "'IBM Plex Sans Arabic', sans-serif" : "'Inter', sans-serif" }}
    >
      <SettingsHeader
        title={t.system_info_title || 'System Infrastructure'}
        description={t.system_info_desc || 'Comprehensive diagnostic reports and health monitoring for your environment.'}
      >
        <OutlineButton onClick={syncUsers} disabled={loading} className="h-10 px-6 uppercase tracking-widest text-[11px] font-black">
          <UserPlus className="w-4 h-4 mr-1.5 text-emerald-500" />
          {t.syncUsers || 'Sync Users'}
        </OutlineButton>
        <OutlineButton onClick={copyForSupport} className="h-10 px-6 uppercase tracking-widest text-[11px] font-black">
          <Copy className="w-4 h-4 mr-1.5 text-indigo-500" />
          {t.copySupport || 'Copy for Support'}
        </OutlineButton>
      </SettingsHeader>

      {getStatusBanner()}

      {data?.update && (
        <BannerCard
          title={t.updateAvailable || 'New Update Available'}
          badge={`v${data.update.new_version}`}
          color="emerald"
          icon={Info}
        >
          <div className="flex flex-col sm:flex-row items-center justify-between gap-6 p-2">
            <p className="text-[12px] text-emerald-700 font-bold uppercase tracking-widest leading-relaxed">
              {t.updateNotice || 'A newer version of the platform is available with improvements and fixes.'}
            </p>
            <PrimaryButton size="sm" className="bg-[#004449] hover:bg-[#003337] text-white font-black text-[12px] uppercase tracking-widest px-8 h-10 rounded-[5px] flex items-center gap-2 shrink-0" onClick={() => { if (data.update?.url) window.location.href = data.update.url; }}>
              {t.updateNow || 'Update Now'} <Zap size={14} className="fill-white" />
            </PrimaryButton>
          </div>
        </BannerCard>
      )}

      {data.banned_msg && (
        <BannerCard
          title={t.accountIssue || 'Account Issue Reported'}
          badge="Restriction"
          color="orange"
          icon={ShieldAlert}
        >
          <div className="p-2">
            <p className="text-[14px] text-orange-900 font-bold leading-relaxed tracking-wide italic px-1">
              "{data.banned_msg}"
            </p>
          </div>
        </BannerCard>
      )}

      {data.not_logged_msg && (
        <BannerCard
          title={t.notLoggedIn || 'Platform Authentication Required'}
          badge="Action Required"
          color="blue"
          icon={ShieldCheck}
        >
          <div className="flex flex-col sm:flex-row items-center justify-between gap-6 p-2">
            <p className="text-[12px] text-indigo-700 font-bold uppercase tracking-widest leading-relaxed">
              {data.not_logged_msg}
            </p>
            {data.login_url && (
              <PrimaryButton size="sm" className="bg-indigo-600 hover:bg-indigo-700 text-white font-black text-[12px] uppercase tracking-widest px-8 h-10 rounded-[5px] flex items-center gap-2 shrink-0" onClick={() => window.location.href = data.login_url}>
                {t.signInNow || 'Sign In Now'} <Zap size={14} className="fill-white" />
              </PrimaryButton>
            )}
          </div>
        </BannerCard>
      )}

      <div className="flex justify-center w-full" dir={isRtl ? "rtl" : "ltr"}>
        <FlatTabs
          tabs={[
            { id: 'wordpress', label: t.tabWordpress || 'WordPress', icon: Layout },
            { id: 'server', label: t.tabServer || 'Server', icon: Server },
            { id: 'cron', label: 'Cron', icon: Clock },
            { id: 'health', label: t.tabHealth || 'Health', icon: Activity },
            { id: 'database', label: t.tabDatabase || 'Database', icon: Database },
            { id: 'security', label: t.tabSecurity || 'Security', icon: ShieldCheck }
          ]}
          activeTab={activeTab}
          onTabChange={setActiveTab}
        />
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <div className="animate-in fade-in duration-500">
          <TabsContent value="wordpress" className="focus:outline-none space-y-8 animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.wpConfigTitle || 'WordPress Configuration'}
                description="Detailed view of your WordPress environment and installation."
                icon={Layout}
                rightAction={
                  <div className="flex items-center gap-2">
                    <Badge variant="secondary" className="bg-indigo-50 text-indigo-700 border-none px-2.5 py-1 font-bold text-[10px]">{data.wp_config.theme}</Badge>
                    <span className="text-[9px] font-bold text-slate-400 uppercase tracking-widest">{t.themeLabel || 'Theme'}</span>
                  </div>
                }
              />
              <div className="grid grid-cols-1 md:grid-cols-2 divide-y md:divide-y divide-x-0 md:divide-x divide-slate-50">
                {data.wp_env.map((item, i: number) => (
                  <div key={i} className="flex flex-col p-5 px-6 hover:bg-slate-50/50 transition-colors w-full gap-2 border-slate-50">
                    <div className="flex flex-row items-center justify-between">
                      <span className="text-[13px] font-bold text-gray-600 text-start whitespace-nowrap">{item.label}</span>
                      <div className="flex items-center gap-4">
                        <span className="text-[12px] font-semibold text-gray-400">{item.value}</span>
                        {getStatusChip(item.status)}
                      </div>
                    </div>
                    {item.message && <p className="text-[11px] text-slate-400 font-medium text-start">{item.message}</p>}
                  </div>
                ))}
              </div>
            </SettingCard>
          </TabsContent>

          <TabsContent value="server" className="focus:outline-none animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.tabServer || 'Server'}
                description="Server environment settings and values"
                icon={Server}
              />
              <div className="divide-y divide-slate-50">
                {data.server_env.map((item, i: number) => (
                  <div key={i} className="flex flex-col p-6 hover:bg-slate-50/50 transition-colors gap-2">
                    <div className="flex flex-row items-center justify-between">
                      <div className="flex items-center gap-5">
                        <span className="text-[13px] font-bold text-gray-700 text-start">{item.label}</span>
                      </div>
                      <div className="flex items-center gap-5">
                        <span className="text-[12px] font-mono font-bold text-gray-400 bg-gray-50 px-2.5 py-1 rounded border border-gray-100">{item.value}</span>
                        {getStatusChip(item.status)}
                      </div>
                    </div>
                    {item.message && <p className="text-[11px] text-slate-400 font-medium text-start italic">{item.message}</p>}
                  </div>
                ))}
              </div>
            </SettingCard>
          </TabsContent>

          <TabsContent value="cron" className="focus:outline-none space-y-8 animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.cronStatusTitle || 'WP-Cron Engine'}
                description={data.cron.is_system ? (t.systemCron || 'System Cron (Server-side)') : (t.wpCron || 'WP-Cron (Internal)')}
                icon={Clock}
                rightAction={
                  <div className="flex items-center gap-3">
                    {data.cron.status && getStatusChip(data.cron.status)}
                    <Badge className={`rounded-[3px] px-3 py-1 font-bold uppercase text-[10px] border-none shadow-none tracking-tight ${data.cron.enabled ? 'bg-emerald-500 text-white' : 'bg-rose-500 text-white'}`}>
                      {data.cron.enabled ? (t.scheduled || 'Scheduled') : (t.disabled || 'Disabled')}
                    </Badge>
                  </div>
                }
              />
              <div className="p-8 space-y-8">
                {data.cron.message && (
                  <div className={`p-5 rounded-[5px] flex items-start gap-5 border ${data.cron.level === 'error' ? 'bg-rose-50/30 border-rose-100 text-rose-800' : 'bg-amber-50/30 border-amber-100 text-amber-800'}`}>
                    <Info className="w-5 h-5 flex-shrink-0 mt-0.5" />
                    <div className="space-y-1 text-start">
                      <p className="text-xs font-bold uppercase tracking-tight">{t.cronDiagnostics || 'Diagnostics'}:</p>
                      <p className="text-[13px] font-medium leading-relaxed">{data.cron.message}</p>
                      {data.cron.last_hit && (
                        <p className="text-[11px] opacity-70 font-bold mt-2">{t.lastCronHit || 'Last fired'}: {data.cron.last_hit}</p>
                      )}
                    </div>
                  </div>
                )}

                {data.cron.url && (
                  <div className="space-y-2">
                    <label className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">{t.cronUrlLabel || 'System Cron URL (Host)'}</label>
                    <div className="flex items-center gap-2 p-3 bg-slate-50 border border-slate-100 rounded-[5px] group">
                      <code className="text-[11px] font-mono font-bold text-indigo-600 flex-1 truncate">{data.cron.url}</code>
                      <OutlineButton size="sm" className="h-7 px-2 text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 rounded border-none" onClick={() => {
                        navigator.clipboard.writeText(data.cron.url || '');
                        toast.success('URL copied to clipboard');
                      }}>
                        <Copy className="w-3.5 h-3.5" />
                      </OutlineButton>
                    </div>
                    <p className="text-[10px] text-gray-400 italic px-1">{t.cronUrlInstruction || 'Use this URL to set up a real CRON job in your hosting control panel (e.g. cPanel).'}</p>
                  </div>
                )}
              </div>
            </SettingCard>

            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.cronEventsTitle || 'Scheduled Tasks Monitoring'}
                description="View and manage scheduled background tasks"
                icon={Clock}
              />
              <div className="divide-y divide-slate-50">
                {data.cron.events.map((event, i: number) => (
                  <div key={i} className="flex flex-row items-center justify-between p-6 hover:bg-slate-50 transition-all group">
                    <div className="flex flex-col text-start">
                      <span className="text-[14px] font-bold text-slate-800">{event.hook}</span>
                      <span className="text-[10px] font-medium text-slate-400 mt-1 uppercase tracking-wider">{event.next_run}</span>
                    </div>
                    <div className="flex items-center gap-5">
                      {getStatusChip(event.status)}
                      {event.state !== 'scheduled' && (
                        <OutlineButton size="sm" className="h-8 px-4 text-[10px] font-bold border-slate-200 text-slate-600 hover:bg-slate-50 rounded-[4px]" onClick={() => handleScheduleCron(event.hook)}>
                          <Zap className="w-3.5 h-3.5 mr-2" /> {t.btnRunNow || 'Run'}
                        </OutlineButton>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </SettingCard>
          </TabsContent>

          <TabsContent value="health" className="focus:outline-none animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.pluginHealthTitle || 'Wawp System Health'}
                description="Status of critical system components"
                icon={Activity}
              />
              <div className="divide-y divide-slate-50">
                {data.health_checks.map((check, i: number) => (
                  <div key={i} className="flex flex-col p-6 hover:bg-slate-50/50 transition-all gap-2 text-start">
                    <div className="flex items-center justify-between">
                      <span className="text-[14px] font-bold text-gray-700">{check.label}</span>
                      {getStatusChip(check.status)}
                    </div>
                    <p className="text-[11px] text-gray-400 font-medium opacity-80">{check.details}</p>
                  </div>
                ))}
              </div>
            </SettingCard>
          </TabsContent>

          <TabsContent value="database" className="focus:outline-none animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.databaseStatusTitle || 'Database Health'}
                description="Status and tools for database tables"
                icon={Database}
              />
              <div className="divide-y divide-slate-50">
                {data.database.map((table, i: number) => (
                  <div key={i} className="flex flex-col p-7 hover:bg-slate-50/50 transition-all gap-6">
                    <div className="flex items-center justify-between">
                      <span className="text-[14px] font-bold text-gray-800">{table.name}</span>
                      <div className="flex items-center gap-4">
                        {table.missing && <Badge className="text-[10px] h-6 px-3 bg-rose-500 text-white border-none font-bold uppercase tracking-widest rounded-[3px]">{table.missing}</Badge>}
                        {getStatusChip(table.status)}
                      </div>
                    </div>
                    <div className="flex items-center justify-end gap-3 pt-2">
                      {table.can_create && <PrimaryButton size="sm" className="h-9 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-[11px] uppercase tracking-widest px-6 rounded-[4px] border-none" onClick={() => handleDbAction('create', table.name)}>{t.btnCreate || 'Create'}</PrimaryButton>}
                      {table.can_repair && <OutlineButton size="sm" className="h-9 border-amber-200 text-amber-700 bg-amber-50/50 hover:bg-amber-100 font-bold text-[11px] uppercase tracking-widest px-6 rounded-[4px]" onClick={() => handleDbAction('repair', table.name)}>{t.btnRepair || 'Repair'}</OutlineButton>}
                      {table.can_truncate && (
                        <OutlineButton size="sm" className="h-9 text-slate-400 font-bold text-[11px] uppercase tracking-widest hover:bg-rose-50 hover:text-rose-600 px-4 rounded-[4px] border-none" onClick={() => handleDbAction('truncate', table.name)}>
                          <Eraser className="w-4 h-4 mr-2" /> {t.btnEmptyTable || 'Empty'}
                        </OutlineButton>
                      )}
                      {table.can_delete && (
                        <OutlineButton size="sm" className="h-9 text-rose-300 font-bold text-[11px] uppercase tracking-widest hover:bg-rose-600 hover:text-white px-4 rounded-[4px] transition-all border-none" onClick={() => handleDbAction('delete', table.name)}>
                          <Trash2 className="w-4 h-4 mr-2" /> {t.btnDeleteTable || 'Drop'}
                        </OutlineButton>
                      )}
                    </div>
                  </div>
                ))}

                <div className="p-4 bg-amber-50/60 border-t border-amber-100 flex items-center justify-between px-7 py-5">
                  <div className="flex items-center gap-4 text-start">
                    <div className="p-2.5 bg-amber-100 rounded-lg text-amber-600 border border-amber-200">
                      <RefreshCw size={20} />
                    </div>
                    <div>
                      <p className="text-[14px] font-bold text-amber-900 leading-tight mb-1">Legacy Data Migration</p>
                      <p className="text-[12px] text-amber-600 font-medium">Sync missing elements from old registration form layout to the new system.</p>
                    </div>
                  </div>
                  <OutlineButton
                    size="sm"
                    className="bg-white border-amber-200 text-amber-700 hover:bg-amber-600 hover:text-white font-black text-[11px] uppercase px-6 h-10 transition-all shadow-none"
                    onClick={async () => {
                      setLoading(true);
                      try {
                        const res = await fetch(`${dashboardData.global.apiRestUrl}/system/migrate-signup`, {
                          method: 'POST',
                          headers: {
                            'Content-Type': 'application/json',
                            'X-WP-Nonce': dashboardData.global.wpRestNonce
                          }
                        });
                        const json = await res.json();
                        if (json.success) {
                          toast.success(json.data?.message || 'Migration complete');
                          refreshStatus();
                        } else {
                          toast.error(json.data?.message || 'Migration failed');
                        }
                      } catch {
                        toast.error('Network error during migration');
                      } finally {
                        setLoading(false);
                      }
                    }}
                    disabled={loading}
                  >
                    <Zap size={14} className="mr-2 fill-amber-500 text-amber-500" />
                    Migrate Now
                  </OutlineButton>
                </div>

                <div className="p-4 bg-indigo-50/60 border-t border-indigo-100 flex items-center justify-between px-7 py-5">
                  <div className="flex items-center gap-4 text-start">
                    <div className="p-2.5 bg-indigo-100 rounded-lg text-indigo-600 border border-indigo-200">
                      <Activity size={20} />
                    </div>
                    <div>
                      <p className="text-[14px] font-bold text-indigo-900 leading-tight mb-1">{t.migrateNotifications || 'Notifications Migration'}</p>
                      <p className="text-[12px] text-indigo-600 font-medium">{t.migrateNotificationsDesc || 'Sync all existing notification rules to the new Flow structure.'}</p>
                    </div>
                  </div>
                  <OutlineButton
                    size="sm"
                    className="bg-white border-indigo-200 text-indigo-700 hover:bg-indigo-600 hover:text-white font-black text-[11px] uppercase px-6 h-10 transition-all shadow-none"
                    onClick={async () => {
                      setLoading(true);
                      try {
                        const res = await fetch(`${dashboardData.global.apiRestUrl}/system/migrate-notifications`, {
                          method: 'POST',
                          headers: {
                            'Content-Type': 'application/json',
                            'X-WP-Nonce': dashboardData.global.wpRestNonce
                          }
                        });
                        const json = await res.json();
                        if (json.success) {
                          toast.success(json.data?.message || 'Migration complete');
                          refreshStatus();
                        } else {
                          toast.error(json.data?.message || 'Migration failed');
                        }
                      } catch {
                        toast.error('Network error during migration');
                      } finally {
                        setLoading(false);
                      }
                    }}
                    disabled={loading}
                  >
                    <Zap size={14} className="mr-2 fill-indigo-500 text-indigo-500" />
                    Migrate Now
                  </OutlineButton>
                </div>
              </div>
            </SettingCard>
          </TabsContent>

          <TabsContent value="security" className="focus:outline-none animate-in slide-in-from-right-4 duration-500">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                title={t.securityTitle || 'Core & Security Configuration'}
                description="Security checks and core configurations"
                icon={ShieldCheck}
              />
              <div className="divide-y divide-slate-50">
                {data.security.map((item, i: number) => (
                  <div key={i} className="flex flex-col p-6 hover:bg-slate-50/50 transition-all gap-2 text-start">
                    <div className="flex items-center justify-between">
                      <span className="text-[14px] font-bold text-gray-700 transition-colors">{item.label}</span>
                      {getStatusChip(item.status)}
                    </div>
                    <p className="text-[11px] text-gray-400 font-medium opacity-90 text-start">{item.message}</p>
                  </div>
                ))}
              </div>
            </SettingCard>
          </TabsContent>
        </div>
      </Tabs>
    </SettingsLayout>
  );
}
