// Settings Page Component (Enhanced)
window.SettingsPage = function SettingsPage({ user, onUpdateUser, showToast }) {
  const isOwner = user?.role === 'owner';

  const [currentPassword, setCurrentPassword] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');
  const [confirmPassword, setConfirmPassword] = React.useState('');

  const [newUsername, setNewUsername] = React.useState(user?.username || 'admin');
  const [newOwnerId, setNewOwnerId] = React.useState(user?.owner_id || '84920183');
  const [panelName, setPanelName] = React.useState(user?.app_name || 'IceX Modz');
  const [discordWebhookUrl, setDiscordWebhookUrl] = React.useState(user?.discord_webhook_url || '');
  const [saving, setSaving] = React.useState(false);

  const handleRandomOwnerId = () => {
    const random8 = Math.floor(10000000 + Math.random() * 90000000).toString();
    setNewOwnerId(random8);
    showToast(`สุ่ม Owner ID ใหม่: ${random8}`, 'info');
  };

  const handleChangeSettings = async (e) => {
    e.preventDefault();
    if (newPassword && newPassword !== confirmPassword) {
      return showToast('รหัสผ่านใหม่ไม่ตรงกัน', 'error');
    }
    if (newPassword && newPassword.length < 6) {
      return showToast('รหัสผ่านใหม่ต้องมีความยาวอย่างน้อย 6 ตัวอักษร', 'error');
    }
    if (isOwner && newOwnerId && !/^\d{8}$/.test(newOwnerId.trim())) {
      return showToast('Owner ID ต้องเป็นตัวเลข 8 หลักเท่านั้น (เช่น 84920183)', 'error');
    }

    setSaving(true);
    try {
      const res = await fetch('/api/auth/change-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({
          currentPassword,
          newPassword: newPassword || currentPassword,
          newUsername: isOwner ? newUsername : undefined,
          newOwnerId: isOwner ? newOwnerId : undefined,
          appName: isOwner ? panelName : undefined,
          discordWebhookUrl: isOwner ? discordWebhookUrl : undefined
        })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
        if (onUpdateUser) {
          onUpdateUser({
            ...user,
            username: isOwner ? newUsername : user.username,
            owner_id: isOwner ? newOwnerId : user.owner_id,
            app_name: isOwner ? panelName : user.app_name,
            discord_webhook_url: isOwner ? discordWebhookUrl : user.discord_webhook_url
          });
        }
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('เกิดข้อผิดพลาด: ' + err.message, 'error');
    } finally {
      setSaving(false);
    }
  };

  const handleTestDiscord = async () => {
    try {
      const res = await fetch('/api/security/test-discord', {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` }
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error sending test webhook', 'error');
    }
  };

  return (
    <div className="space-y-6 max-w-4xl animate-fade-in">
      {/* Header */}
      <div className="pb-4 border-b border-[#1E2D4A]">
        <h2 className="text-xl font-bold text-white font-brand flex items-center gap-2.5">
          <i className="fa-solid fa-gear text-cyan-400"></i>
          <span>ตั้งค่าระบบ & บัญชีผู้ใช้ (Settings)</span>
        </h2>
        <p className="text-xs text-slate-400 mt-0.5">
          กำหนดค่าข้อมูลพาเนล, เปลี่ยนรหัสผ่าน, ปรับแต่ง Owner ID และการแจ้งเตือน Discord Webhook
        </p>
      </div>

      <form onSubmit={handleChangeSettings} className="space-y-4">
        {/* Owner System Configuration */}
        {isOwner && (
          <div className="p-4 sm:p-6 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-4 shadow-xl">
            <div className="flex items-center gap-2 pb-3 border-b border-[#1E2D4A]">
              <i className="fa-solid fa-crown text-amber-400 text-xs"></i>
              <h3 className="text-sm font-semibold text-white font-brand">
                OWNER & PANEL CONFIGURATION (เฉพาะยศ Owner)
              </h3>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
              <div className="min-w-0">
                <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                  PANEL BRAND NAME (ชื่อเว็บพาเนล)
                </label>
                <input
                  type="text"
                  value={panelName}
                  onChange={(e) => setPanelName(e.target.value)}
                  className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none"
                />
              </div>

              <div className="min-w-0">
                <div className="flex items-center justify-between mb-1">
                  <label className="block text-xs font-medium text-slate-300 font-mono">
                    OWNER ID (ตัวเลข 8 หลัก) *
                  </label>
                  <button
                    type="button"
                    onClick={handleRandomOwnerId}
                    className="text-[11px] text-cyan-400 hover:text-cyan-300 font-mono flex items-center gap-1 transition"
                  >
                    <i className="fa-solid fa-dice text-[10px]"></i>
                    <span>สุ่มเลข 8 หลัก</span>
                  </button>
                </div>
                <input
                  type="text"
                  maxLength="8"
                  required
                  value={newOwnerId}
                  onChange={(e) => setNewOwnerId(e.target.value.replace(/\D/g, '').slice(0, 8))}
                  placeholder="เช่น 84920183"
                  className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none font-mono"
                />
                <p className="text-[10px] text-slate-500 mt-1 font-mono">
                  * ต้องเป็นตัวเลข 8 หลัก สำหรับใส่ในโปรเจ็คคู่กับ App Token
                </p>
              </div>

              <div className="sm:col-span-2 min-w-0">
                <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                  OWNER USERNAME
                </label>
                <input
                  type="text"
                  value={newUsername}
                  onChange={(e) => setNewUsername(e.target.value)}
                  className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none font-mono"
                />
              </div>
            </div>
          </div>
        )}

        {/* Discord Webhook Configuration */}
        {isOwner && (
          <div className="p-4 sm:p-6 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-4 shadow-xl">
            <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 pb-3 border-b border-[#1E2D4A]">
              <div className="flex items-center gap-2">
                <i className="fa-brands fa-discord text-indigo-400 text-sm"></i>
                <h3 className="text-sm font-semibold text-white font-brand">
                  DISCORD WEBHOOK NOTIFICATIONS (แจ้งเตือนเปิดคีย์ & การโจมตี)
                </h3>
              </div>
              <button
                type="button"
                onClick={handleTestDiscord}
                className="w-full sm:w-auto px-3 py-1.5 rounded-none bg-indigo-600/20 hover:bg-indigo-600/30 text-indigo-300 border border-indigo-500/30 text-xs font-mono transition text-center"
              >
                ทดสอบส่ง Webhook
              </button>
            </div>

            <div>
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                DISCORD WEBHOOK URL
              </label>
              <input
                type="url"
                value={discordWebhookUrl}
                onChange={(e) => setDiscordWebhookUrl(e.target.value)}
                placeholder="https://discord.com/api/webhooks/..."
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-xs text-white focus:border-indigo-500 outline-none font-mono"
              />
              <p className="text-[11px] text-slate-500 mt-1">
                * ระบบจะส่งข้อความแจ้งเตือนอัตโนมัติเมื่อมีคนเปิดใช้งานคีย์ครั้งแรก หรือมีการพยายามล็อกอินจาก IP/HWID ที่ถูกแบน
              </p>
            </div>
          </div>
        )}

        {/* Change Password */}
        <div className="p-4 sm:p-6 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-4 shadow-xl">
          <div className="flex items-center gap-2 pb-3 border-b border-[#1E2D4A]">
            <i className="fa-solid fa-lock text-cyan-400 text-xs"></i>
            <h3 className="text-sm font-semibold text-white font-brand">
              เปลี่ยนรหัสผ่าน (CHANGE PASSWORD)
            </h3>
          </div>

          <div className="space-y-3.5">
            <div>
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                รหัสผ่านปัจจุบัน (CURRENT PASSWORD) *
              </label>
              <input
                type="password"
                required
                value={currentPassword}
                onChange={(e) => setCurrentPassword(e.target.value)}
                placeholder="••••••••"
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none"
              />
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
              <div className="min-w-0">
                <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                  รหัสผ่านใหม่ (NEW PASSWORD)
                </label>
                <input
                  type="password"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  placeholder="ว่างไว้หากไม่ต้องการเปลี่ยน"
                  className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none"
                />
              </div>
              <div className="min-w-0">
                <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                  ยืนยันรหัสผ่านใหม่ (CONFIRM NEW PASSWORD)
                </label>
                <input
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  placeholder="พิมพ์รหัสผ่านใหม่อีกครั้ง"
                  className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none"
                />
              </div>
            </div>
          </div>
        </div>

        <div className="flex justify-end">
          <button
            type="submit"
            disabled={saving}
            className="w-full sm:w-auto px-6 py-2.5 rounded-none bg-[#1D63FF] hover:bg-[#3878FF] text-white font-semibold text-xs shadow-lg shadow-blue-600/30 transition flex items-center justify-center gap-2 disabled:opacity-50 font-mono"
          >
            {saving ? (
              <>
                <i className="fa-solid fa-circle-notch fa-spin text-xs"></i>
                <span>กำลังบันทึก...</span>
              </>
            ) : (
              <>
                <i className="fa-solid fa-check text-xs"></i>
                <span>บันทึกการตั้งค่า</span>
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
};
