/* =====================================================================
   CLIENT PORTAL SIDECAR — slide-out sign-in panel (no full page)
   Global opener: window.openPortalSidecar()
   ===================================================================== */
let _portalSet = null;
function openPortalSidecar() { if (_portalSet) _portalSet(true); else navigate("/portal"); }
function closePortalSidecar() { if (_portalSet) _portalSet(false); }

function PortalSidecar() {
  const s = useStore();
  const G = window.GLR;
  const [open, setOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const ses = G.session();
  const [email, setEmail] = useState(ses.email);
  const mine = s.requests.filter((r) => r.email === (email || ses.email));

  useEffect(() => { _portalSet = (v) => { if (v) setEmail(G.session().email); setOpen(v); }; return () => { _portalSet = null; }; }, []);
  useEffect(() => {
    if (open) { setMounted(true); document.body.style.overflow = "hidden"; }
    else { document.body.style.overflow = ""; }
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  const signIn = () => {
    const cur = G.session();
    const known = s.requests.find((r) => r.email.toLowerCase() === (email || "").toLowerCase());
    const name = known ? known.name : (cur.name || (email ? email.split("@")[0].replace(/[._]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) : "Client"));
    const company = known ? known.company : (cur.company || "");
    G.setSession({ name, company, email: email || cur.email });
    setOpen(false);
    navigate("/portal");
    showToast("Signed in to your deal rooms");
  };
  const goRoom = (slug) => { setOpen(false); navigate("/portal/" + slug); };

  if (!mounted && !open) return null;

  return (
    <div className={"sc-scrim" + (open ? " on" : "")} onClick={() => setOpen(false)}
      onTransitionEnd={() => { if (!open) setMounted(false); }}>
      <aside className={"sc-panel" + (open ? " on" : "")} onClick={(e) => e.stopPropagation()} role="dialog" aria-label="Client portal sign in">
        {/* navy header */}
        <div className="sc-head">
          <div className="row jb ac">
            <Logo onNavy onClick={() => { setOpen(false); navigate("/"); }} />
            <button className="sc-close" aria-label="Close" onClick={() => setOpen(false)}><Icon name="x" size={18} /></button>
          </div>
          <div className="seal-est" style={{ marginTop: 26, color: "var(--brass)" }}>Secure client portal</div>
          <h2 style={{ color: "#fff", fontSize: 26, fontWeight: 700, letterSpacing: "-0.025em", marginTop: 12, lineHeight: 1.05 }}>The war room.</h2>
          <p style={{ color: "#bcccdd", fontSize: 14, marginTop: 10, lineHeight: 1.5 }}>Access deal documents, financials, and secure data rooms for the properties you're under NDA on.</p>
        </div>

        {/* body */}
        <div className="sc-body scroll-y">
          <div className="field"><label>Email</label>
            <input className="input" placeholder="jane@fund.com" value={email} onChange={(e) => setEmail(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") signIn(); }} />
          </div>
          <div className="field" style={{ marginTop: 14 }}><label>Password</label>
            <input className="input" type="password" placeholder="••••••••" onKeyDown={(e) => { if (e.key === "Enter") signIn(); }} />
          </div>
          <button className="btn lg block" style={{ marginTop: 18 }} onClick={signIn}><Icon name="lock" size={16} /> Sign in</button>
          <div className="row jb ac" style={{ marginTop: 14 }}>
            <button className="linklike small" onClick={signIn}>Use a sign-in link</button>
            <span className="small muted" style={{ cursor: "pointer" }}>Forgot?</span>
          </div>

          {mine.length > 0 && (
            <div style={{ marginTop: 24 }}>
              <hr className="divider" />
              <div className="label" style={{ margin: "18px 0 12px" }}>Your deal rooms</div>
              <div className="col gap10">
                {mine.slice(0, 4).map((r) => {
                  const l = s.listings.find((x) => x.slug === r.slug);
                  if (!l) return null;
                  const approved = r.status === "approved";
                  return (
                    <button key={r.id} className="sc-room" onClick={() => approved ? goRoom(l.slug) : (setOpen(false), navigate("/portal"))}>
                      <span style={{ width: 38, height: 38, borderRadius: 4, flex: "none", overflow: "hidden", background: "var(--paper-3)" }}>
                        <PhotoBox dataUrl={l.photo} type={l.type} h={38} />
                      </span>
                      <span style={{ flex: 1, minWidth: 0, textAlign: "left" }}>
                        <span className="small b6" style={{ display: "block", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{l.address}</span>
                        <span className="xsmall" style={{ color: approved ? "var(--avail)" : "var(--loi)" }}>
                          {approved ? "● Access granted" : "● Awaiting approval"}
                        </span>
                      </span>
                      {approved && <Icon name="chevR" size={16} style={{ color: "var(--slate-2)", flex: "none" }} />}
                    </button>
                  );
                })}
              </div>
            </div>
          )}
        </div>

        {/* footer trust strip */}
        <div className="sc-foot">
          <div className="row gap16">
            <span className="row gap6 ac xsmall" style={{ color: "var(--slate)" }}><Icon name="shield" size={14} /> 2-factor secured</span>
            <span className="row gap6 ac xsmall" style={{ color: "var(--slate)" }}><Icon name="lock" size={14} /> Watermarked files</span>
          </div>
          <p className="xsmall muted" style={{ marginTop: 10 }}>No access yet? <button className="linklike xsmall" onClick={() => { setOpen(false); navigate("/properties"); }}>Browse properties</button> and request an NDA.</p>
        </div>
      </aside>
    </div>
  );
}

Object.assign(window, { PortalSidecar, openPortalSidecar, closePortalSidecar });
