import { useState, useEffect } from "react";

const VALID_CODE = "123456"; // Simulation
const MAX_ATTEMPTS = 5;
const LOCKOUT_SECONDS = 15 * 60; // 15 Minuten

export default function OB03() {
  const [code, setCode]           = useState("");
  const [attempts, setAttempts]   = useState(0);
  const [error, setError]         = useState("");
  const [locked, setLocked]       = useState(false);
  const [lockRemaining, setLockRemaining] = useState(LOCKOUT_SECONDS);
  const [submitted, setSubmitted] = useState(false);
  const [copied, setCopied]       = useState(false);

  const SECRET = "JBSWY3DPEHPK3PXP";

  // Countdown bei Sperre
  useEffect(() => {
    if (!locked) return;
    if (lockRemaining <= 0) { setLocked(false); setAttempts(0); setError(""); return; }
    const t = setTimeout(() => setLockRemaining(s => s - 1), 1000);
    return () => clearTimeout(t);
  }, [locked, lockRemaining]);

  const formatTime = (s) => `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;

  const handleVerify = () => {
    if (locked || code.length !== 6) return;
    if (code === VALID_CODE) {
      setSubmitted(true);
    } else {
      const next = attempts + 1;
      setAttempts(next);
      if (next >= MAX_ATTEMPTS) {
        setLocked(true);
        setLockRemaining(LOCKOUT_SECONDS);
        setError(`Zu viele Fehlversuche. Bitte warten Sie 15 Minuten.`);
      } else {
        setError(`Falscher Code. Noch ${MAX_ATTEMPTS - next} Versuch${MAX_ATTEMPTS - next === 1 ? "" : "e"} übrig.`);
      }
      setCode("");
    }
  };

  const handleCopy = () => {
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  if (submitted) {
    return (
      <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 400, borderRadius: 8, overflow: "hidden" }}>
        <div style={{ background: "#1a1a18", padding: "10px 24px", display: "flex", alignItems: "center", justifyContent: "space-between", borderRadius: "8px 8px 0 0" }}>
          <span style={{ fontWeight: 700, color: "#fff", fontSize: 15 }}>DiveLogix360</span>
          <span style={{ fontSize: 11, color: "#888780" }}>Registrierung</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: 350, padding: 24 }}>
          <div style={{ textAlign: "center" }}>
            <div style={{ width: 56, height: 56, borderRadius: "50%", background: "#EAF3DE", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 24, marginBottom: 16 }}>✓</div>
            <div style={{ fontSize: 18, fontWeight: 500, color: "#1a1a18", marginBottom: 8 }}>2FA erfolgreich eingerichtet</div>
            <div style={{ fontSize: 13, color: "#5F5E5A", marginBottom: 24 }}>Weiter zu den Recovery-Codes.</div>
            <button onClick={() => alert("→ OB-04: Recovery-Codes")}
              style={{ padding: "10px 28px", fontSize: 13, fontWeight: 500, background: "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer" }}>
              Weiter zu den Recovery-Codes →
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 600, borderRadius: 8, overflow: "hidden" }}>

      {/* NAV */}
      <div style={{ background: "#1a1a18", padding: "10px 24px", display: "flex", alignItems: "center", justifyContent: "space-between", borderRadius: "8px 8px 0 0" }}>
        <span style={{ fontWeight: 700, color: "#fff", fontSize: 15 }}>DiveLogix360</span>
        <span style={{ fontSize: 11, color: "#888780" }}>Registrierung</span>
      </div>

      {/* FORTSCHRITTSLEISTE */}
      <div style={{ background: "#fff", borderBottom: "1px solid #D3D1C7", padding: "12px 24px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 0, maxWidth: 480, margin: "0 auto" }}>
          {[
            { n: "1", label: "Link",     done: true,  active: false },
            { n: "2", label: "Passwort", done: true,  active: false },
            { n: "3", label: "2FA",      done: false, active: true  },
            { n: "4", label: "Codes",    done: false, active: false },
            { n: "5", label: "Profil",   done: false, active: false },
          ].map((s, i, arr) => (
            <div key={s.n} style={{ display: "flex", alignItems: "center", flex: i < arr.length - 1 ? 1 : 0 }}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                <div style={{ width: 28, height: 28, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 600,
                  background: s.done ? "#EAF3DE" : s.active ? "#185FA5" : "#F1EFE8",
                  color: s.done ? "#3B6D11" : s.active ? "#fff" : "#B4B2A9",
                  border: s.active ? "2px solid #185FA5" : "2px solid transparent" }}>
                  {s.done ? "✓" : s.n}
                </div>
                <span style={{ fontSize: 9, color: s.active ? "#185FA5" : s.done ? "#3B6D11" : "#B4B2A9", fontWeight: s.active ? 600 : 400, whiteSpace: "nowrap" }}>{s.label}</span>
              </div>
              {i < arr.length - 1 && (
                <div style={{ flex: 1, height: 2, background: s.done ? "#3B6D11" : "#D3D1C7", margin: "0 6px", marginBottom: 16 }} />
              )}
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", justifyContent: "center", padding: "24px 24px 16px" }}>
        <div style={{ width: "100%", maxWidth: 480 }}>

          {/* TITEL */}
          <div style={{ marginBottom: 20 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
              <h1 style={{ fontSize: 20, fontWeight: 500, color: "#1a1a18", margin: 0 }}>2FA einrichten</h1>
              <span style={{ background: "#E6F1FB", color: "#185FA5", fontSize: 11, fontWeight: 500, padding: "2px 8px", borderRadius: 20 }}>OB-03</span>
            </div>
            <p style={{ fontSize: 12, color: "#5F5E5A", margin: 0 }}>Schützen Sie Ihren Account mit Zwei-Faktor-Authentifizierung (TOTP).</p>
          </div>

          {/* ANLEITUNG */}
          <div style={{ background: "#E6F1FB", border: "1px solid #B5D4F4", borderRadius: 6, padding: "10px 14px", fontSize: 11, color: "#185FA5", marginBottom: 16 }}>
            <strong>So richten Sie 2FA ein:</strong> Öffnen Sie Google Authenticator, Microsoft Authenticator oder eine andere TOTP-App und scannen Sie den QR-Code unten.
          </div>

          {/* FORMULAR CARD */}
          <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 10, padding: "20px 24px", marginBottom: 16 }}>

            {/* ZWEISPALTIGES LAYOUT: QR + Anleitung */}
            <div style={{ display: "grid", gridTemplateColumns: "160px 1fr", gap: 20, marginBottom: 20 }}>

              {/* QR-CODE (simuliert) */}
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
                <div style={{ width: 140, height: 140, background: "#F1EFE8", border: "2px solid #D3D1C7", borderRadius: 8, display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", gap: 4 }}>
                  {/* QR-Code Simulation */}
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 2, padding: 8 }}>
                    {Array.from({ length: 49 }, (_, i) => (
                      <div key={i} style={{ width: 10, height: 10, background: [0,1,2,3,4,5,6,7,13,14,20,21,22,23,24,25,26,28,34,35,41,42,43,44,45,46,48].includes(i) ? "#1a1a18" : "#F1EFE8", borderRadius: 1 }} />
                    ))}
                  </div>
                </div>
                <span style={{ fontSize: 9, color: "#888780", textAlign: "center" }}>QR-Code mit Authenticator-App scannen</span>
              </div>

              {/* Schritte */}
              <div>
                <div style={{ fontSize: 11, fontWeight: 500, color: "#1a1a18", marginBottom: 10 }}>Schritt für Schritt:</div>
                {[
                  "App öffnen (Google / Microsoft Authenticator)",
                  "«+» oder «Konto hinzufügen» tippen",
                  "«QR-Code scannen» wählen",
                  "QR-Code links abscannen",
                  "Angezeigten 6-stelligen Code eingeben",
                ].map((step, i) => (
                  <div key={i} style={{ display: "flex", gap: 8, marginBottom: 7, fontSize: 11 }}>
                    <div style={{ width: 18, height: 18, borderRadius: "50%", background: "#E6F1FB", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 9, fontWeight: 600, color: "#185FA5", flexShrink: 0 }}>
                      {i + 1}
                    </div>
                    <span style={{ color: "#5F5E5A", lineHeight: 1.5 }}>{step}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* MANUELLER SCHLÜSSEL */}
            <div style={{ background: "#F1EFE8", borderRadius: 6, padding: "10px 14px", marginBottom: 20 }}>
              <div style={{ fontSize: 11, color: "#888780", marginBottom: 6 }}>QR-Code nicht scanbar? Manueller Schlüssel:</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <code style={{ fontSize: 12, color: "#1a1a18", fontFamily: "monospace", letterSpacing: 2, flex: 1 }}>{SECRET}</code>
                <button onClick={handleCopy}
                  style={{ fontSize: 11, padding: "3px 10px", background: copied ? "#EAF3DE" : "#fff", border: `1px solid ${copied ? "#3B6D11" : "#B4B2A9"}`, borderRadius: 4, cursor: "pointer", color: copied ? "#3B6D11" : "#5F5E5A", whiteSpace: "nowrap" }}>
                  {copied ? "✓ Kopiert" : "Kopieren"}
                </button>
              </div>
            </div>

            {/* CODE EINGABE */}
            <div style={{ marginBottom: 8 }}>
              <label style={{ display: "block", fontSize: 12, fontWeight: 500, color: "#1a1a18", marginBottom: 8 }}>
                6-stelliger Code aus der App <span style={{ color: "#A32D2D" }}>*</span>
              </label>

              {/* Sperre-Banner */}
              {locked && (
                <div style={{ background: "#FCEBEB", border: "1px solid #F7C1C1", borderRadius: 6, padding: "10px 14px", fontSize: 12, color: "#A32D2D", marginBottom: 12 }}>
                  <strong>Zu viele Fehlversuche ({MAX_ATTEMPTS}/{MAX_ATTEMPTS}).</strong> Bitte warten Sie:
                  <div style={{ fontSize: 20, fontWeight: 700, fontFamily: "monospace", marginTop: 6, textAlign: "center" }}>
                    {formatTime(lockRemaining)}
                  </div>
                </div>
              )}

              {/* Code-Eingabefelder (6 einzelne Boxen) */}
              <div style={{ display: "flex", gap: 8, marginBottom: 8 }}>
                {Array.from({ length: 6 }, (_, i) => (
                  <div key={i} style={{ flex: 1, height: 48, background: locked ? "#F1EFE8" : "#fff", border: `2px solid ${error ? "#A32D2D" : code.length > i ? "#185FA5" : "#D3D1C7"}`, borderRadius: 8, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20, fontWeight: 600, color: "#1a1a18", fontFamily: "monospace" }}>
                    {code[i] || ""}
                  </div>
                ))}
              </div>

              {/* Unsichtbares echtes Input */}
              <input
                type="text" inputMode="numeric" maxLength={6}
                value={code}
                onChange={e => { if (!locked) { setCode(e.target.value.replace(/\D/g, "")); setError(""); } }}
                onKeyDown={e => e.key === "Enter" && handleVerify()}
                placeholder="Code hier eingeben..."
                style={{ width: "100%", boxSizing: "border-box", padding: "8px 12px", fontSize: 16, letterSpacing: 4, textAlign: "center", border: `1px solid ${error ? "#A32D2D" : "#B4B2A9"}`, borderRadius: 6, outline: "none", background: locked ? "#F1EFE8" : "#fff" }}
                disabled={locked}
              />

              {/* Fehler */}
              {error && !locked && (
                <div style={{ fontSize: 11, color: "#A32D2D", marginTop: 6 }}>⚠ {error}</div>
              )}

              {/* Versuchs-Anzeige */}
              {attempts > 0 && !locked && (
                <div style={{ fontSize: 10, color: "#888780", marginTop: 4, textAlign: "right" }}>
                  Versuche: {attempts}/{MAX_ATTEMPTS}
                </div>
              )}

              <div style={{ fontSize: 10, color: "#888780", marginTop: 6 }}>
                Tipp für Simulation: Code <strong>123456</strong> ist korrekt. Andere Codes simulieren F7.
              </div>
            </div>
          </div>

          {/* BUTTON */}
          <button onClick={handleVerify} disabled={code.length !== 6 || locked}
            style={{ width: "100%", padding: "12px", fontSize: 13, fontWeight: 500,
              background: code.length === 6 && !locked ? "#185FA5" : "#D3D1C7",
              border: "none", borderRadius: 8, color: "#fff",
              cursor: code.length === 6 && !locked ? "pointer" : "not-allowed" }}>
            Code bestätigen & weiter →
          </button>

          {/* METAINFO */}
          <div style={{ marginTop: 16, padding: "8px 12px", background: "#fff", border: "1px solid #D3D1C7", borderRadius: 6, fontSize: 10, color: "#888780" }}>
            Screen: OB-03  |  UC00 – Tenant-Onboarding  |  Akteur: tenant_admin  |  Folge-Screen: OB-04  |  v0.1 – April 2026
          </div>

        </div>
      </div>
    </div>
  );
}
