// Klyvio — Auth.jsx v3
// Un seul écran de connexion — admin ou client selon les identifiants

const ADMIN_EMAIL = "romain@klyvio.fr";
const ADMIN_PASSWORD = "KYakana28*";

function LoginView({ onAdminSuccess, onClientSuccess }) {
  const [email, setEmail]     = useState("");
  const [secret, setSecret]   = useState("");
  const [err, setErr]         = useState("");
  const [loading, setLoading] = useState(false);

  // Code client = 6 car. alphanumériques ET email != admin
  const isAdminEmail = email.trim().toLowerCase() === ADMIN_EMAIL;
  const looksLikeCode = !isAdminEmail && /^[A-Z0-9]{6}$/.test(secret.toUpperCase());

  const submit = () => {
    setErr("");
    if (!email || !secret) { setErr("Veuillez remplir tous les champs."); return; }
    setLoading(true);

    setTimeout(() => {
      // Tentative admin
      if (email.trim().toLowerCase() === ADMIN_EMAIL && secret === ADMIN_PASSWORD) {
        onAdminSuccess();
        return;
      }

      // Tentative client (email + code 6 car.)
      try {
        const all = JSON.parse(localStorage.getItem("klyvio_audits") || "[]");
        const found = all.find(a =>
          (a.email || "").toLowerCase().trim() === email.toLowerCase().trim() &&
          (a.id || "") === secret.toUpperCase()
        );
        if (found) { onClientSuccess(found); return; }
      } catch {}

      setErr("Identifiants incorrects. Vérifiez votre email et votre code d'accès ou mot de passe.");
      setLoading(false);
    }, 700);
  };

  return (
    <div style={{
      flex: 1, display: "flex", flexDirection: "column",
      alignItems: "center", justifyContent: "center",
      minHeight: "calc(100vh - 60px)", padding: "2rem",
    }}>
      <div style={{ width: "100%", maxWidth: 440 }}>

        <div className="eyebrow-line" style={{ marginBottom: 14 }}>Klyvio — Audit IA</div>
        <h1 className="display" style={{ fontSize: 42, margin: "0 0 8px", color: "var(--white)" }}>
          Se connecter
        </h1>
        <p style={{ fontSize: 14, color: "var(--gray)", margin: "0 0 40px", lineHeight: 1.6 }}>
          Accédez à votre rapport ou à l'espace administrateur.
        </p>

        <div className="field" style={{ marginBottom: 16 }}>
          <label>Email</label>
          <input
            className="input"
            type="email"
            value={email}
            onChange={e => setEmail(e.target.value)}
            placeholder="votre@email.fr"
            autoFocus
          />
        </div>

        <div className="field" style={{ marginBottom: 8 }}>
          <label>Code d'accès ou mot de passe</label>
          <input
            className="input"
            type={looksLikeCode ? "text" : "password"}
            value={secret}
            onChange={e => setSecret(looksLikeCode ? e.target.value.toUpperCase() : e.target.value)}
            onKeyDown={e => e.key === "Enter" && submit()}
            placeholder="ABC123 ou ••••••••"
            style={looksLikeCode ? {
              textTransform: "uppercase",
              letterSpacing: "0.25em",
              fontFamily: "var(--mono, monospace)",
              fontSize: 20,
              textAlign: "center",
            } : {}}
          />
        </div>

        <p style={{ fontSize: 12, color: "var(--text-mute)", margin: "0 0 28px", lineHeight: 1.5 }}>
          Clients : entrez le code à 6 caractères reçu à la fin de l'audit.<br />
          Administrateur : entrez votre mot de passe habituel.
        </p>

        {err && (
          <div style={{
            fontSize: 13, color: "var(--danger, #EF4444)", marginBottom: 20,
            padding: "10px 14px", background: "rgba(239,68,68,0.08)",
            border: "1px solid rgba(239,68,68,0.2)", borderRadius: 8,
          }}>
            {err}
          </div>
        )}

        <button
          className="btn btn-primary btn-lg"
          style={{ width: "100%", opacity: loading ? 0.6 : 1 }}
          onClick={submit}
          disabled={loading}
        >
          {loading ? "Vérification…" : "Se connecter"}
          {!loading && <Icon name="arrowRight" size={14} />}
        </button>

      </div>
    </div>
  );
}

// CodeReveal — affiché après génération du rapport
function CodeReveal({ code, company, onContinue }) {
  const [copied, setCopied] = useState(false);

  const copyCode = () => {
    const done = () => { setCopied(true); setTimeout(() => setCopied(false), 2500); };
    // Méthode moderne (HTTPS)
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(code).then(done).catch(() => fallback());
    } else {
      fallback();
    }
    function fallback() {
      // Méthode universelle — fonctionne sans HTTPS (Claude Design, Live Server)
      const el = document.createElement("textarea");
      el.value = code;
      el.style.cssText = "position:fixed;top:0;left:0;opacity:0;pointer-events:none";
      document.body.appendChild(el);
      el.focus();
      el.select();
      try { document.execCommand("copy"); done(); } catch {}
      document.body.removeChild(el);
    }
  };

  return (
    <div style={{
      flex: 1, display: "flex", flexDirection: "column",
      alignItems: "center", justifyContent: "center",
      minHeight: "calc(100vh - 60px)", padding: "2rem", textAlign: "center",
    }}>
      <div style={{ maxWidth: 500, width: "100%" }}>
        <div style={{
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          width: 68, height: 68, borderRadius: 20,
          background: "rgba(16,185,129,0.12)", border: "1px solid rgba(16,185,129,0.3)",
          marginBottom: 32,
        }}>
          <Icon name="check" size={30} color="#10B981" />
        </div>

        <div className="eyebrow" style={{ marginBottom: 14 }}>Audit généré avec succès</div>
        <h1 className="display" style={{ fontSize: 42, margin: "0 0 14px", color: "var(--white)" }}>
          Votre rapport est prêt.
        </h1>
        <p style={{ fontSize: 15, color: "var(--gray)", margin: "0 0 44px", lineHeight: 1.6 }}>
          Conservez ce code — il vous permettra de retrouver votre rapport et de modifier vos réponses à tout moment.
        </p>

        <div style={{
          padding: "28px 36px 24px", marginBottom: 14,
          background: "rgba(255,255,255,0.03)",
          border: "1px solid rgba(255,255,255,0.1)",
          borderRadius: 18,
        }}>
          <div style={{ fontSize: 12, color: "var(--text-mute)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 14 }}>
            Votre code d'accès
          </div>
          <div className="mono" style={{ fontSize: 52, fontWeight: 700, color: "var(--accent)", letterSpacing: "0.28em", marginBottom: 18, lineHeight: 1 }}>
            {code}
          </div>
          <div style={{ fontSize: 13, color: "var(--text-soft)" }}>
            Email associé :{" "}
            <span style={{ color: "var(--white)", fontWeight: 500 }}>
              {company?.email || "non renseigné"}
            </span>
          </div>
        </div>

        <button
          className="btn btn-ghost"
          style={{ width: "100%", marginBottom: 10, color: copied ? "#10B981" : "var(--white)", borderColor: copied ? "rgba(16,185,129,0.4)" : undefined }}
          onClick={copyCode}
        >
          <Icon name={copied ? "check" : "copy"} size={13} color={copied ? "#10B981" : undefined} />
          {copied ? "Code copié !" : "Copier le code"}
        </button>

        <button className="btn btn-primary btn-lg" style={{ width: "100%" }} onClick={onContinue}>
          <Icon name="arrowRight" size={14} /> Accéder à mon rapport
        </button>
      </div>
    </div>
  );
}

window.LoginView  = LoginView;
window.CodeReveal = CodeReveal;
