/* ═══════════════════════════════════════════════════════════
   OpAgent Inside — Landing + Login
   ═══════════════════════════════════════════════════════════ */

function Landing({ onConnect }){
  const D = window.DEMO;
  const [open, setOpen] = useState(false);
  const [sel, setSel] = useState(null);       // selected emr object
  const [reqFor, setReqFor] = useState(null); // grayed emr the user requested access to
  const [reqDone, setReqDone] = useState(false);
  const ddRef = useRef(null);

  useEffect(()=>{
    function onDoc(e){ if(ddRef.current && !ddRef.current.contains(e.target)) setOpen(false); }
    document.addEventListener("mousedown", onDoc);
    return ()=>document.removeEventListener("mousedown", onDoc);
  },[]);

  function pick(emr){
    if(emr.live){ setSel(emr); setReqFor(null); setReqDone(false); setOpen(false); }
    else { setReqFor(emr); setReqDone(false); setOpen(false); }
  }

  return (
    <div className="land screen">
      <nav className="land-nav">
        <div className="land-brand"><Reticle size={30}/><Wordmark/><span className="brand-div"></span><span className="brand-inside">Inside</span></div>
        <div className="navlinks"><span>Platform</span><span>Inside</span><span>Evidence</span><span>Contact</span></div>
      </nav>

      <div className="land-hero">
        <div className="eyebrow">Your Operation, Our Intelligence</div>
        <h1>Anywhere,<br/><span className="ins">any EMR.</span></h1>
        <div className="neu-line"><b>neu-RCM</b> — reimbursement intelligence at the point of care.</div>

        <div className="connect" ref={ddRef}>
          <div className="clabel">Connect your EMR</div>
          <div className="dd">
            <button className={"dd-toggle"+(open?" open":"")} onClick={()=>setOpen(o=>!o)}>
              <span className="sel">
                {sel
                  ? <><span className="live-dot"></span><span className="nm">{sel.name}</span></>
                  : <span className="ph">Select your EMR…</span>}
              </span>
              <span className="car">▼</span>
            </button>
            {open && (
              <div className="dd-menu">
                {D.emrs.map(emr=>(
                  <div key={emr.id} className={"dd-item "+(emr.live?"active":"disabled")} onClick={()=>pick(emr)}>
                    <span className="l">
                      {emr.live && <span className="live-dot"></span>}
                      <span className="nm">{emr.name}</span>
                    </span>
                    {emr.live
                      ? <span className="live-tag">● Live</span>
                      : <span className="soon" title="Coming soon — request early access">Coming soon</span>}
                  </div>
                ))}
                <div className="dd-divider"></div>
                <div className="dd-note"><b>Epic &amp; athenahealth</b> available via direct API integration — the integrated path, not Inside.</div>
              </div>
            )}
          </div>

          {reqFor && (
            <div className="req-access">
              {!reqDone ? (
                <>
                  <div className="rt">Request early access — {reqFor.name}</div>
                  <div className="rf">
                    <input placeholder="work email" defaultValue="" />
                    <button className="rb" onClick={()=>setReqDone(true)}>Request access</button>
                  </div>
                </>
              ) : (
                <div className="done">✓ Thanks — we'll reach out about {reqFor.name} Inside access.</div>
              )}
            </div>
          )}

          <button className="cta-go" disabled={!sel} onClick={()=>onConnect(sel)}>
            {sel ? <>Connect to {sel.name} <span>→</span></> : <>Select an EMR to continue</>}
          </button>
        </div>

        <div className="trust">
          <span className="t"><span className="b"></span> proposes &amp; protects revenue</span>
          <span className="t"><span className="b"></span> every number traces to a claim</span>
          <span className="t"><span className="b"></span> PHI stays local</span>
        </div>
      </div>
    </div>
  );
}

function Login({ emr, onBack, onSignIn }){
  const [loading, setLoading] = useState(false);
  const [failed, setFailed] = useState(false);
  const [failMsg, setFailMsg] = useState("");
  const [headless, setHeadless] = useState(false);
  const [streamed, setStreamed] = useState(false);
  const loginPopupRef = useRef(null);
  const [stage, setStage] = useState("Reading live schedule & claims…");

  useEffect(()=>{
    const A = window.Adapters;
    if(!A) return;
    A.getJSON("/api/health", {}).then((h)=>{
      if(h && h.insideLoginMode === "headless") setHeadless(true);
      if(h && h.insideLoginMode === "interactive") setStreamed(true);
    });
  },[]);

  // Two-layer auth: the branded page is the OpAgent app entry; the real EMR
  // sign-in is the supervised Dr. Chrono popup the backend launches. We never
  // collect/POST the Dr. Chrono credentials — the human signs in inside the
  // popup window. Flow: if the session is already healthy, go straight in;
  // otherwise POST /api/inside/relogin and poll /api/inside/session.
  async function submit(e){
    e && e.preventDefault();
    setFailed(false);
    setFailMsg("");
    setLoading(true);
    const A = window.Adapters;
    const name = (emr && emr.name) || "DrChrono";
    const health = await A.getJSON("/api/health", {});
    const loginMode = health.insideLoginMode || "supervised";
    setHeadless(loginMode === "headless");
    setStreamed(loginMode === "interactive");

    setStage(`Checking ${name} session…`);
    let healthy = await A.sessionHealthy();

    if(!healthy){
      setStage(loginMode === "headless"
        ? `Signing in to ${name}…`
        : loginMode === "interactive"
          ? `Opening ${name} login tab — sign in there (incl. MFA)…`
          : `Opening secure ${name} login window — sign in there (incl. 2FA)…`);
      const relogin = await A.startRelogin();
      const mode = (relogin && relogin.mode) || loginMode;
      if(relogin && relogin.loginWindowUrl){
        const popup = window.open(relogin.loginWindowUrl, "drchrono-login", "width=1200,height=800,menubar=no,toolbar=no,location=yes,status=no");
        loginPopupRef.current = popup;
        if(!popup){
          setLoading(false);
          setFailed(true);
          setFailMsg("Popup blocked — allow popups for this site, then click Retry.");
          return;
        }
      }
      const closePopup = () => {
        const p = loginPopupRef.current;
        if(p && !p.closed) try { p.close(); } catch(_){}
        loginPopupRef.current = null;
      };
      const poll = await A.pollSession({
        onStage: setStage,
        onHealthy: closePopup,
        emr,
        loginMode: mode,
        timeoutMs: mode === "headless" ? 120_000 : undefined,
      });
      healthy = poll && poll.ok;
      if(!healthy){
        closePopup();
        if(poll && poll.error) setFailMsg(poll.error);
      }
    }

    if(healthy){
      setStage("Running OpAgent engines…");
      onSignIn();
    } else {
      setLoading(false);
      setFailed(true);
    }
  }

  return (
    <div className="login screen">
      <aside className="login-aside">
        <div className="la-brand"><Reticle size={30} color="#FDFCF9" dot="#C4973E"/><span className="wm" style={{color:"#FDFCF9",fontFamily:"var(--fd)",fontWeight:700,fontSize:21}}>OpAgent<span className="ai">.ai</span></span><span style={{width:1,height:19,background:"rgba(253,252,249,.32)",display:"inline-block",margin:"0 9px"}}></span><span style={{fontFamily:"var(--fd)",fontWeight:700,fontSize:21,color:"#C4973E"}}>Inside</span></div>
        <div className="la-pos">
          <div className="la-pos-1">Reimbursement Intelligence Layer</div>
          <div className="la-pos-2">Orthopedics &amp; Pain Management</div>
        </div>
        <div className="la-body">
          <h2>OpAgent signs in the way your <em>staff does.</em></h2>
          <div className="la-points">
            <div className="la-pt"><span className="mk">→</span><span>It reads your live data and proposes the actions that protect your revenue.</span></div>
            <div className="la-pt"><span className="mk">→</span><span>No API, no integration, no IT lift. It works the way a staff member would.</span></div>
            <div className="la-pt"><span className="mk">→</span><span>Every dollar it surfaces traces to a real claim. PHI stays local.</span></div>
          </div>
          <div className="la-foot">{emr?.name || "DrChrono"} · secured session</div>
        </div>
      </aside>

      <main className="login-main">
        <div className="login-card">
          {!loading ? (
            <form onSubmit={submit}>
              <div className="connecting"><Reticle size={16}/> connecting to: <span className="dc">{emr?.name || "DrChrono"}</span></div>
              <h3>Sign in</h3>
              <div className="field">
                <label>Work email</label>
                <input type="email" defaultValue="b.liabaud@hvspine.com" />
              </div>
              <div className="field">
                <label>Password</label>
                <input type="password" defaultValue="••••••••••••" />
              </div>
              <button type="submit" className="login-btn">Sign in <span>→</span></button>
              <div className="login-back">Wrong EMR? <button type="button" onClick={onBack}>Go back</button></div>
              <div className="login-back" style={{marginTop:8,opacity:.7,fontSize:11}}>{headless
                ? `OpAgent signs in to ${emr?.name || "DrChrono"} server-side with your practice's provisioned credentials — no popup window, no API integration.`
                : streamed
                  ? `OpAgent opens the real ${emr?.name || "DrChrono"} login in a separate tab so you can complete MFA. Allow popups for this site if prompted.`
                  : `OpAgent signs in the way your staff does — the real ${emr?.name || "DrChrono"} login opens in a separate secure window. No API, no integration; credentials never reach OpAgent.`}</div>
            </form>
          ) : failed ? (
            <div className="login-load">
              <div className="lt" style={{color:"#9A2A2A"}}><b>{emr?.name || "DrChrono"}</b> · sign-in not completed</div>
              <div className="lt" style={{marginTop:8,fontSize:12,opacity:.8}}>{failMsg || (headless
                ? "Server-side sign-in did not complete. Check DrChrono credentials in AWS Secrets Manager."
                : streamed
                  ? "The login tab timed out or was closed before sign-in finished. Allow popups and complete MFA in the DrChrono tab."
                  : "The secure login window timed out or was closed before sign-in finished.")}</div>
              <button type="button" className="login-btn" style={{marginTop:16}} onClick={submit}>Retry <span>→</span></button>
              <div className="login-back" style={{marginTop:10}}><button type="button" onClick={onBack}>Go back</button></div>
            </div>
          ) : (
            <div className="login-load">
              <div className="ring"></div>
              <div className="lt"><b>{emr?.name || "DrChrono"}</b> · {stage}</div>
            </div>
          )}
        </div>
      </main>
    </div>
  );
}

Object.assign(window, { Landing, Login });
