// Unlock screen — wired to real PBKDF2 + Cloudflare auth + AES key derivation

const { useState: useStateUnlock, useEffect: useEffectUnlock } = React;

function UnlockScreen({ onUnlock, ambience }) {
  const [pwd, setPwd] = useStateUnlock("");
  const [shake, setShake] = useStateUnlock(false);
  const [unlocking, setUnlocking] = useStateUnlock(false);
  const [error, setError] = useStateUnlock(null);

  const submit = async (e) => {
    e.preventDefault();
    if (!pwd || unlocking) return;
    setError(null);

    if (!window.isSecureContext || !window.crypto?.subtle) {
      setError("此瀏覽器/連線不支援加密（需 HTTPS）");
      return;
    }

    setUnlocking(true);
    try {
      // 1. Compute PBKDF2 hash for server login (no plaintext sent)
      const loginHash = await window.LifeCrypto.computeLoginHash(pwd);
      try {
        await window.LifeAPI.authLogin(loginHash);
      } catch (e) {
        const msg = String(e);
        if (msg.includes('401')) throw new Error("密碼錯誤");
        if (msg.includes('503')) throw new Error("伺服器尚未設定密碼");
        throw e;
      }

      // 2. Derive AES key from same password (or generate salt on first use)
      const existingSalt = await window.LifeAPI.getSalt();
      if (existingSalt) {
        await window.LifeCrypto.unlock(pwd, existingSalt);
        const dates = await window.LifeAPI.listDiaryDates();
        if (dates.length > 0) {
          const probe = await window.LifeAPI.getDiary(dates[0]);
          if (probe && !(await window.LifeCrypto.tryDecrypt(probe))) {
            window.LifeCrypto.lock();
            throw new Error("資料無法解密（密碼不一致）");
          }
        }
      } else {
        const newSalt = await window.LifeCrypto.unlock(pwd);
        await window.LifeAPI.setSalt(newSalt);
      }

      // 3. Pre-load all data so app can render synchronously
      await window.LifeData.load();

      setPwd("");
      // Brief fade-out animation, then trigger unlock
      setTimeout(() => onUnlock(), 600);
    } catch (e) {
      console.error(e);
      setError(e?.message || String(e));
      setShake(true);
      setUnlocking(false);
      setTimeout(() => setShake(false), 400);
    }
  };

  const today = new Date();
  const dateStr = `${today.getFullYear()}.${String(today.getMonth()+1).padStart(2,"0")}.${String(today.getDate()).padStart(2,"0")}`;

  return (
    <div style={{
      position: "fixed", inset: 0,
      background: "radial-gradient(ellipse at 50% 60%, #2a2218 0%, #14100b 70%, #0a0806 100%)",
      overflow: "hidden",
      display: "flex", alignItems: "center", justifyContent: "center"
    }}>
      <Ambience mode={ambience} />

      <div style={{
        position: "absolute", top: 28, left: 36, right: 36,
        display: "flex", justifyContent: "space-between",
        color: "oklch(0.78 0.06 80 / 0.6)",
        fontFamily: "var(--font-en)", fontSize: 12, letterSpacing: "0.32em",
        textTransform: "uppercase"
      }}>
        <span>The Life Book · 一冊人生</span>
        <span className="mono" style={{ fontSize: 11, letterSpacing: "0.2em" }}>{dateStr}</span>
      </div>

      <div style={{
        position: "relative",
        width: 460,
        padding: "56px 52px 44px",
        background: "linear-gradient(180deg, oklch(0.18 0.02 60 / 0.85), oklch(0.14 0.02 60 / 0.92))",
        backdropFilter: "blur(8px)",
        border: "1px solid oklch(0.55 0.08 78 / 0.25)",
        boxShadow: "0 30px 80px oklch(0 0 0 / 0.5), inset 0 1px 0 oklch(1 0 0 / 0.05)",
        animation: shake ? "shake 0.4s" : (unlocking ? "fadeOut 0.7s forwards" : "none"),
      }}>
        {[
          { top: 8, left: 8, br: ["t","l"] },
          { top: 8, right: 8, br: ["t","r"] },
          { bottom: 8, left: 8, br: ["b","l"] },
          { bottom: 8, right: 8, br: ["b","r"] },
        ].map((c, i) => (
          <div key={i} style={{
            position: "absolute",
            width: 18, height: 18,
            ...c,
            borderTop: c.br.includes("t") ? "1px solid oklch(0.68 0.10 78 / 0.6)" : "none",
            borderBottom: c.br.includes("b") ? "1px solid oklch(0.68 0.10 78 / 0.6)" : "none",
            borderLeft: c.br.includes("l") ? "1px solid oklch(0.68 0.10 78 / 0.6)" : "none",
            borderRight: c.br.includes("r") ? "1px solid oklch(0.68 0.10 78 / 0.6)" : "none",
          }} />
        ))}

        <div style={{ display: "flex", justifyContent: "center", marginBottom: 18 }}>
          <LotusMark size={56} />
        </div>

        <h1 style={{
          margin: 0, textAlign: "center",
          fontFamily: "var(--font-han)", fontWeight: 500,
          fontSize: 30, color: "oklch(0.85 0.06 78)",
          letterSpacing: "0.4em", paddingLeft: "0.4em"
        }}>一 冊 人 生</h1>

        <div style={{
          textAlign: "center", marginTop: 6,
          fontFamily: "var(--font-en)", fontStyle: "italic",
          fontSize: 16, color: "oklch(0.65 0.06 78 / 0.8)",
          letterSpacing: "0.04em"
        }}>The Life Book</div>

        <div style={{
          margin: "28px auto 24px",
          width: 60, height: 1,
          background: "linear-gradient(90deg, transparent, oklch(0.68 0.10 78 / 0.6), transparent)"
        }} />

        <div style={{
          textAlign: "center",
          fontFamily: "var(--font-han)",
          fontSize: 14, color: "oklch(0.75 0.02 60 / 0.7)",
          letterSpacing: "0.2em", marginBottom: 22
        }}>{unlocking ? "解卷中⋯" : "輸入主密碼以開卷"}</div>

        <form onSubmit={submit}>
          <input
            type="password"
            value={pwd}
            onChange={e => setPwd(e.target.value)}
            disabled={unlocking}
            autoFocus
            placeholder="• • • • • • • •"
            style={{
              width: "100%",
              padding: "14px 16px",
              background: "oklch(0.97 0.015 80)",
              border: "1px solid oklch(0.68 0.10 78 / 0.4)",
              borderRadius: 2,
              fontFamily: "var(--font-mono)",
              fontSize: 16, letterSpacing: "0.4em",
              color: "oklch(0.24 0.02 60)",
              outline: "none",
              textAlign: "center",
              opacity: unlocking ? 0.6 : 1
            }}
          />
          <button
            type="submit"
            className="btn btn-gold"
            disabled={unlocking}
            style={{
              marginTop: 14, width: "100%", padding: "14px",
              fontSize: 15, letterSpacing: "0.5em",
              justifyContent: "center", fontWeight: 600,
              opacity: unlocking ? 0.6 : 1,
              cursor: unlocking ? "wait" : "pointer"
            }}
          >{unlocking ? "⋯" : "解 卷"}</button>
        </form>

        {error && (
          <div style={{
            marginTop: 16, textAlign: "center",
            fontFamily: "var(--font-han)", fontSize: 13,
            color: "oklch(0.65 0.13 25 / 0.9)",
            letterSpacing: "0.05em"
          }}>{error}</div>
        )}

        <div style={{
          marginTop: 22, textAlign: "center",
          fontFamily: "var(--font-han)",
          fontSize: 11.5, lineHeight: 1.9,
          color: "oklch(0.62 0.02 60 / 0.7)",
          letterSpacing: "0.05em"
        }}>
          同一組密碼用於登入與日記加密。<br/>
          遺失無法復原，建議存入 password manager。
        </div>

        <div style={{
          marginTop: 20, textAlign: "center",
          fontFamily: "var(--font-en)", fontStyle: "italic",
          fontSize: 13, color: "oklch(0.55 0.06 78 / 0.55)",
          letterSpacing: "0.04em"
        }}>
          <span style={{ opacity: 0.6 }}>—</span> at rest in the mud, untouched by it <span style={{ opacity: 0.6 }}>—</span>
        </div>
      </div>

      <style>{`
        @keyframes shake { 0%,100%{transform:translateX(0)} 25%{transform:translateX(-8px)} 75%{transform:translateX(8px)} }
        @keyframes fadeOut { to { opacity: 0; transform: scale(1.03); } }
      `}</style>
    </div>
  );
}

function LotusMark({ size = 56 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 56 56" style={{ display: "block" }}>
      <defs>
        <radialGradient id="lp" cx="50%" cy="60%">
          <stop offset="0%" stopColor="oklch(0.85 0.10 15)" />
          <stop offset="100%" stopColor="oklch(0.55 0.13 15 / 0)" />
        </radialGradient>
        <linearGradient id="lg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="oklch(0.78 0.10 78)" />
          <stop offset="100%" stopColor="oklch(0.55 0.11 70)" />
        </linearGradient>
      </defs>
      <circle cx="28" cy="36" r="22" fill="none" stroke="oklch(0.50 0.04 220 / 0.4)" strokeWidth="0.6" />
      {[-60, -30, 0, 30, 60].map((deg, i) => (
        <g key={i} transform={`rotate(${deg} 28 36)`}>
          <ellipse cx="28" cy="22" rx="5" ry="14" fill="url(#lp)" stroke="url(#lg)" strokeWidth="0.7" />
        </g>
      ))}
      <ellipse cx="28" cy="22" rx="3.4" ry="9" fill="url(#lp)" stroke="url(#lg)" strokeWidth="0.7" />
      <line x1="6" y1="40" x2="50" y2="40" stroke="oklch(0.68 0.10 78 / 0.5)" strokeWidth="0.5" />
    </svg>
  );
}

window.UnlockScreen = UnlockScreen;
window.LotusMark = LotusMark;
