/* ProHippo — PIN Lock (Setup + Entry) */

/* Simple hash using Web Crypto API — no library needed */
async function hashPin(pin) {
  const encoder = new TextEncoder();
  const data = encoder.encode("prohippo_v1_" + pin);
  const buf  = await crypto.subtle.digest("SHA-256", data);
  return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2,"0")).join("");
}

/* ── Shared: Dot indicator ───────────────────────── */
function PinDots({ count, error }) {
  return (
    <div className="pin-dots">
      {[0,1,2,3].map(i => (
        <div key={i} className={`pin-dot ${i < count ? "filled" : ""} ${error ? "shake" : ""}`}/>
      ))}
    </div>
  );
}

/* ── Shared: Numeric keypad ──────────────────────── */
function PinKeypad({ onKey, onDelete }) {
  return (
    <div className="pin-keypad">
      {[1,2,3,4,5,6,7,8,9].map(n => (
        <button key={n} className="pin-key" onClick={() => onKey(String(n))}>{n}</button>
      ))}
      <div/>
      <button className="pin-key" onClick={() => onKey("0")}>0</button>
      <button className="pin-key pin-key-del" onClick={onDelete}>⌫</button>
    </div>
  );
}

/* ── PIN Setup Screen (first time) ───────────────── */
function PinSetupScreen({ user, onComplete }) {
  const [stage, setStage]   = React.useState("set");   // "set" | "confirm"
  const [pin, setPin]       = React.useState("");
  const [confirm, setConfirm] = React.useState("");
  const [error, setError]   = React.useState(false);
  const [saving, setSaving] = React.useState(false);

  const handleKey = (key) => {
    if (stage === "set") {
      if (pin.length >= 4) return;
      const next = pin + key;
      setPin(next);
      if (next.length === 4) setTimeout(() => setStage("confirm"), 300);
    } else {
      if (confirm.length >= 4) return;
      const next = confirm + key;
      setConfirm(next);
      if (next.length === 4) verifyConfirm(next);
    }
  };

  const handleDelete = () => {
    if (stage === "set")  setPin(p  => p.slice(0,-1));
    else                  setConfirm(p => p.slice(0,-1));
  };

  const verifyConfirm = async (val) => {
    if (val !== pin) {
      setError(true);
      setTimeout(() => { setError(false); setConfirm(""); }, 800);
      return;
    }
    setSaving(true);
    try {
      const hashed = await hashPin(pin);
      // Save PIN hash to Firestore user document
      await firebase.firestore().collection("users").doc(user.uid).update({ pinHash: hashed });
    } catch(_) {
      // Firestore update failed — store locally as fallback
      try {
        const profile = JSON.parse(localStorage.getItem("ph_profile_" + user.uid) || "{}");
        profile.pinHash = await hashPin(pin);
        localStorage.setItem("ph_profile_" + user.uid, JSON.stringify(profile));
      } catch(_2){}
    }
    // Mark verified for this session
    sessionStorage.setItem("ph_pin_ok_" + user.uid, "1");
    onComplete();
  };

  const current = stage === "set" ? pin : confirm;

  return (
    <div className="pin-page">
      <div className="pin-card">
        <div className="pin-logo">
          <div className="auth-logo-mark" style={{width:52,height:52,borderRadius:16,background:"var(--p-primary)"}}>
            <svg viewBox="0 0 24 24" fill="none" style={{width:26,height:26}}>
              <path d="M6 4c3 0 3 4 6 4s3-4 6-4v16c-3 0-3-4-6-4s-3 4-6 4V4z" fill="white"/>
            </svg>
          </div>
        </div>

        <div className="pin-lock-icon">🔒</div>
        <h2 className="pin-title">
          {stage === "set" ? "Set a 4-digit PIN" : "Confirm your PIN"}
        </h2>
        <p className="pin-sub">
          {stage === "set"
            ? "You'll enter this PIN every time you open ProHippo"
            : "Re-enter the same PIN to confirm"}
        </p>

        <PinDots count={current.length} error={error}/>
        {error && <p className="pin-error-msg">PINs don't match — try again</p>}
        {!error && <p className="pin-error-msg" style={{opacity:0}}>_</p>}

        <PinKeypad onKey={handleKey} onDelete={handleDelete}/>

        {stage === "confirm" && !saving && (
          <button className="pin-back-link" onClick={() => { setStage("set"); setPin(""); setConfirm(""); }}>
            ← Change PIN
          </button>
        )}
        {saving && <p className="pin-saving">Setting up security…</p>}
      </div>
    </div>
  );
}

/* ── PIN Entry Screen (every login) ──────────────── */
function PinEntryScreen({ user, storedPinHash, onUnlock, onSignOut }) {
  const [pin, setPin]       = React.useState("");
  const [error, setError]   = React.useState(false);
  const [attempts, setAttempts] = React.useState(0);
  const [checking, setChecking] = React.useState(false);

  const handleKey = async (key) => {
    if (pin.length >= 4 || checking) return;
    const next = pin + key;
    setPin(next);
    if (next.length === 4) {
      setChecking(true);
      const hashed = await hashPin(next);
      if (hashed === storedPinHash) {
        sessionStorage.setItem("ph_pin_ok_" + user.uid, "1");
        onUnlock();
      } else {
        setError(true);
        setAttempts(a => a + 1);
        setTimeout(() => { setError(false); setPin(""); setChecking(false); }, 800);
      }
    }
  };

  const handleDelete = () => {
    if (checking) return;
    setPin(p => p.slice(0,-1));
  };

  return (
    <div className="pin-page">
      <div className="pin-card">
        <div className="pin-logo">
          <div className="auth-logo-mark" style={{width:52,height:52,borderRadius:16,background:"var(--p-primary)"}}>
            <svg viewBox="0 0 24 24" fill="none" style={{width:26,height:26}}>
              <path d="M6 4c3 0 3 4 6 4s3-4 6-4v16c-3 0-3-4-6-4s-3 4-6 4V4z" fill="white"/>
            </svg>
          </div>
        </div>

        <div className="pin-lock-icon">🔐</div>
        <h2 className="pin-title">Enter your PIN</h2>
        <p className="pin-sub">Verify it's you before accessing your workspace</p>

        <PinDots count={pin.length} error={error}/>
        {error && <p className="pin-error-msg">Incorrect PIN — try again</p>}
        {!error && <p className="pin-error-msg" style={{opacity:0}}>_</p>}

        <PinKeypad onKey={handleKey} onDelete={handleDelete}/>

        <div className="pin-footer-links">
          {attempts >= 3 && (
            <button className="pin-back-link" style={{color:"var(--p-danger)"}} onClick={onSignOut}>
              Forgot PIN? Sign out →
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

window.PinSetupScreen  = PinSetupScreen;
window.PinEntryScreen  = PinEntryScreen;
