<!DOCTYPE html>

<html lang="en">
<head>
<title>ShrumHR</title>
<meta charset="utf-8"/>
<meta content="width=device-width,initial-scale=1" name="viewport"/>
<link crossorigin="anonymous" href="/assets/styles.css?v=client-role-hard-gate" integrity="sha384-+L2GkS6pY6HUjRVvnuopRZcTgzkpIi+sI4qO+azvOfQzpgprp6k9bymnoSoAmDoK" rel="stylesheet"/>
</head>
<body>
<header class="topbar">
<a class="brand" href="/dashboard">
<span class="brand-logo-wrap"><img alt="Shrum Consulting Group logo" class="brand-logo" src="/assets/scg-logo.png?v=client-role-hard-gate"/></span>
<span><strong>ShrumHR</strong><small>Secure HR Workspace</small></span>
</a>
<nav class="topnav" id="topNav">
<button class="btn ghost hidden" id="logoutBtn">Logout</button>
</nav>
</header>
<main id="app"><section class="card"><h1>Loading secure HR workspace...</h1></section></main>
<script crossorigin="anonymous" integrity="sha384-SQn5ElxLSH7xc1O48XNYt95iKZyLpN0UPjmYOrT4FNDye7foF0PcSWLzNv0jEUzU" src="/assets/supabase-js-2.js"></script>
<script crossorigin="anonymous" integrity="sha384-jX9EC4ebpzH5Vdm7xdbxX80yT0q36T1rKNyB9UDadq8QzkLm8ACmIp0YuEfNl25B" src="/config.js"></script>
<script>
(async()=>{
  const app=document.getElementById("app");
  const topNav=document.getElementById("topNav");
  const cfg=window.SHRUMHR_CONFIG||{};
  const esc=v=>String(v??"").replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;");

  if(!cfg.SUPABASE_URL || !cfg.SUPABASE_PUBLISHABLE_KEY){
    app.innerHTML='<section class="card"><h1>Configuration needed</h1><p>config.js is missing Supabase values.</p></section>';
    return;
  }

  const sb=window.supabase.createClient(cfg.SUPABASE_URL,cfg.SUPABASE_PUBLISHABLE_KEY);

  function setNav(role){
    if(role==="owner_admin" || role==="admin"){
      topNav.innerHTML=`
        <a href="/dashboard">Dashboard</a>
        <a href="/workspace">Workspace</a>
        <a href="/request-center">Requests</a>
        <a href="/client-portal">Client Portal</a>
        <a href="/employee-portal">Employee Portal</a>
        <a href="/client-files">Files</a><a href="/client-files">Client Files</a><a href="/reports">Reports</a>
        <a href="/admin">Admin</a>
        <button id="logoutBtn" class="btn ghost">Logout</button>`;
    } else if(["client_admin","client_manager","client_viewer","client_user"].includes(role)){
      topNav.innerHTML=`
        <a href="/dashboard">Dashboard</a>
        <a href="/request-center">Requests</a>
        <a href="/client-portal">Client Portal</a>
        <a href="/client-files">Files</a><a href="/client-files">Client Files</a><a href="/reports">Reports</a>
        <button id="logoutBtn" class="btn ghost">Logout</button>`;
    } else if(role==="employee_user"){
      topNav.innerHTML=`
        <a href="/dashboard">Dashboard</a>
        <a href="/employee-portal">Employee Portal</a>
        <a href="/request-center">Requests</a>
        <button id="logoutBtn" class="btn ghost">Logout</button>`;
    } else {
      topNav.innerHTML=`<button id="logoutBtn" class="btn ghost">Logout</button>`;
    }
    const btn=document.getElementById("logoutBtn");
    if(btn) btn.onclick=async()=>{await sb.auth.signOut(); location.href="/dashboard";};
  }

  function renderLogin(message=""){
    topNav.innerHTML="";
    app.innerHTML=`
      <section class="client-hero login-hero">
        <div>
          <p class="eyebrow">Secure HR Workspace</p>
          <h1>Welcome to ShrumHR</h1>
          <p>Sign in to manage HR operations, client requests, employee records, cases, tasks, payroll coordination, evidence, and reporting.</p>
        </div>
        <div class="hero-panel login-panel">
          <h2>Sign in</h2>
          <label>Email</label>
          <input id="email" class="input" type="email" autocomplete="email" placeholder="you@example.com"/>
          <label>Password</label>
          <input id="password" class="input" type="password" autocomplete="current-password" placeholder="Password"/>
          <button id="signInBtn" class="btn full-width">Sign in</button>
          <p id="loginMsg" class="small">${esc(message)}</p>
        </div>
      </section>`;
    document.getElementById("signInBtn").onclick=async()=>{
      const email=document.getElementById("email").value.trim();
      const password=document.getElementById("password").value;
      const msg=document.getElementById("loginMsg");
      if(!email || !password){msg.textContent="Enter email and password."; return;}
      msg.textContent="Signing in...";
      const {error}=await sb.auth.signInWithPassword({email,password});
      if(error){msg.textContent=error.message || "Sign in failed."; return;}
      location.href="/dashboard";
    };
    document.getElementById("password").addEventListener("keydown",e=>{
      if(e.key==="Enter") document.getElementById("signInBtn").click();
    });
  }

  const {data:sdata}=await sb.auth.getSession();
  if(!sdata.session){ renderLogin(); return; }

  const user=sdata.session.user;
  const {data:profile,error:profileError}=await sb
    .from("profiles")
    .select("id, full_name, role, company_id")
    .eq("id", user.id)
    .maybeSingle();

  if(profileError || !profile){
    setNav("unknown");
    app.innerHTML=`<section class="card"><h1>Profile access issue</h1><p>Your login succeeded, but no matching profile was found for this account.</p><p class="small">${esc(profileError?.message||"No profile row found.")}</p></section>`;
    return;
  }

  setNav(profile.role);

  async function count(table,fn){
    let q=sb.from(table).select("*",{count:"exact",head:true});
    if(fn) q=fn(q);
    const {count,error}=await q;
    return error?0:(count||0);
  }

  const isOwner = profile.role==="owner_admin" || profile.role==="admin";
  const isClient = ["client_admin","client_manager","client_viewer","client_user"].includes(profile.role);

  let companyName="Assigned Workspace";
  if(profile.company_id){
    const {data:company}=await sb.from("companies").select("company_name,name").eq("id",profile.company_id).maybeSingle();
    companyName = company?.company_name || company?.name || companyName;
  }

  const companyFilter = (q)=> isClient && profile.company_id ? q.eq("company_id", profile.company_id) : q;

  const [companies,employees,openCases,openTasks,requests,payroll,evidence,reports] = await Promise.all([
    isClient ? Promise.resolve(1) : count("companies"),
    count("employees", companyFilter),
    count("hr_cases", q=>companyFilter(q).neq("case_status","closed")),
    count("hris_tasks", q=>companyFilter(q).neq("task_status","complete")),
    count("portal_requests", q=>companyFilter(q).neq("request_status","closed")),
    count("payroll_item_register", companyFilter),
    isClient ? Promise.resolve(0) : count("evidence_vault_items"),
    count("report_snapshots")
  ]);

  if(isClient){
    app.innerHTML=`
      <section class="client-hero">
        <div>
          <p class="eyebrow">Client Workspace</p>
          <h1>${esc(companyName)}</h1>
          <p>You are viewing the HR workspace assigned to your company. Access is restricted by your role and company assignment.</p>
          <div class="hero-actions">
            <a class="btn" href="/request-center">Open Requests</a>
            <a class="btn ghost" href="/client-portal">Client Portal</a>
          </div>
        </div>
        <div class="hero-panel">
          <span class="status-pill">Company-Scoped Access</span>
          <h2>${esc(profile.role)}</h2>
          <p>${openCases} open cases · ${openTasks} open tasks · ${requests} open requests</p>
        </div>
      </section>
      <section class="grid four">
        <div class="kpi polish"><strong>${employees}</strong><span>Employees visible</span></div>
        <div class="kpi polish"><strong>${openCases}</strong><span>Open HR Cases</span></div>
        <div class="kpi polish"><strong>${openTasks}</strong><span>Open Tasks</span></div>
        <div class="kpi polish"><strong>${requests}</strong><span>Open Requests</span></div>
        <div class="kpi polish"><strong>${payroll}</strong><span>Payroll Coordination</span></div>
        <div class="kpi polish"><strong>${reports}</strong><span>Reports</span></div>
      </section>
      <section class="grid three">
        <a class="card action-card polished-card" href="/request-center"><h2>Request Center</h2><p>Submit and review company-scoped HR support requests.</p></a>
        <a class="card action-card polished-card" href="/client-portal"><h2>Client Portal</h2><p>View your assigned company workspace.</p></a>
        <a class="card action-card polished-card" href="/reports"><h2>Reports</h2><p>Review available client-facing reports.</p></a>
      </section>`;
  } else {
    app.innerHTML=`
      <section class="client-hero">
        <div>
          <p class="eyebrow">Secure HR Operations Platform</p>
          <h1>ShrumHR Owner Workspace</h1>
          <p>Manage HR requests, employee records, cases, tasks, payroll coordination, evidence tracking, and executive reporting from one clean workspace.</p>
          <div class="hero-actions"><a class="btn" href="/request-center">Open Requests</a><a class="btn ghost" href="/workspace">Go to Workspace</a></div>
        </div>
        <div class="hero-panel"><span class="status-pill">System Ready</span><h2>Operating Picture</h2><p>${openCases} open cases · ${openTasks} open tasks · ${requests} open requests</p></div>
      </section>
      <section class="grid four">
        <div class="kpi polish"><strong>${companies}</strong><span>Companies</span></div>
        <div class="kpi polish"><strong>${employees}</strong><span>Employees</span></div>
        <div class="kpi polish"><strong>${openCases}</strong><span>Open HR Cases</span></div>
        <div class="kpi polish"><strong>${openTasks}</strong><span>Open Tasks</span></div>
        <div class="kpi polish"><strong>${requests}</strong><span>Open Requests</span></div>
        <div class="kpi polish"><strong>${payroll}</strong><span>Payroll Items</span></div>
        <div class="kpi polish"><strong>${evidence}</strong><span>Evidence Records</span></div>
        <div class="kpi polish"><strong>${reports}</strong><span>Reports</span></div>
      </section>
      <section class="grid three">
        <a class="card action-card polished-card" href="/request-center"><h2>Request Center</h2><p>Track incoming HR, client, employee, payroll, and compliance requests.</p></a>
        <a class="card action-card polished-card" href="/workspace"><h2>Operations Workspace</h2><p>Work cases, tasks, onboarding, offboarding, and evidence reviews.</p></a>
        <a class="card action-card polished-card" href="/reports"><h2>Executive Reports</h2><p>Generate owner and client-ready operational summaries.</p></a>
      </section>`;
  }
})();
</script>
</body>
</html>