const workforceTabs = {
  employee: ["Today", "Check-in", "History", "Alerts"],
  supervisor: ["Team", "Approvals", "Shifts", "Reports"]
};

const workforceLoginPersonas = [
  {
    role: "employee",
    label: "Employee",
    icon: "user",
    name: "Musa Garba",
    email: "employee@ovo-workforce.demo",
    password: "ovo-demo",
    scope: "Shift, check-in/out, GPS validation, history, alerts"
  },
  {
    role: "supervisor",
    label: "Supervisor",
    icon: "users",
    name: "Rose Adeyemi",
    email: "supervisor@ovo-workforce.demo",
    password: "ovo-demo",
    scope: "Quick team monitoring, approvals, shift cover requests"
  }
];

function WorkforceLoginView({ onLogin }) {
  const [selectedRole, setSelectedRole] = React.useState("employee");
  const [email, setEmail] = React.useState("employee@ovo-workforce.demo");
  const [password, setPassword] = React.useState("ovo-demo");
  const [showPassword, setShowPassword] = React.useState(false);
  const [error, setError] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  function choosePersona(persona) {
    if (busy) return;
    setSelectedRole(persona.role);
    setEmail(persona.email);
    setPassword(persona.password);
    setError("");
  }

  function submitLogin(event) {
    event.preventDefault();
    if (busy) return;
    if (!email.trim() || !password) {
      setError("Enter your work account email and password to continue.");
      return;
    }
    const matchedPersona = workforceLoginPersonas.find((persona) => persona.email === email.trim().toLowerCase() && persona.password === password);
    if (!matchedPersona) {
      setError("Incorrect email or password. Use one of the demo accounts above.");
      return;
    }
    setError("");
    setBusy(true);
    setTimeout(() => onLogin(matchedPersona.role), 700);
  }

  return (
    <form className="campus-login" onSubmit={submitLogin}>
      <div className="campus-login-brand workforce-brand">
        <div className="login-mark">OVO</div>
        <div>
          <span>Workforce · Mobile</span>
          <h2>Welcome back</h2>
        </div>
      </div>

      <p className="login-explainer">
        <Icon name="lock" size={13} />
        Your role comes from your work account — there is no in-app role switching after login.
      </p>

      <div className="login-persona-list" role="radiogroup" aria-label="Demo accounts">
        {workforceLoginPersonas.map((persona) => (
          <button
            aria-pressed={selectedRole === persona.role}
            className={`login-persona ${selectedRole === persona.role ? "active" : ""}`}
            disabled={busy}
            key={persona.role}
            onClick={() => choosePersona(persona)}
            type="button"
          >
            <span className="persona-icon"><Icon name={persona.icon} size={17} /></span>
            <span className="persona-copy">
              <strong>{persona.label}</strong>
              <span>{persona.email}</span>
            </span>
            {selectedRole === persona.role && <Icon className="persona-check" name="checkcircle" size={16} />}
          </button>
        ))}
      </div>

      <label className="login-field">
        <span>Work email</span>
        <input
          autoComplete="username"
          disabled={busy}
          inputMode="email"
          onChange={(event) => setEmail(event.target.value)}
          placeholder="name@ovo-workforce.demo"
          type="email"
          value={email}
        />
      </label>

      <label className="login-field">
        <span>Password</span>
        <span className="login-password-wrap">
          <input
            autoComplete="current-password"
            disabled={busy}
            onChange={(event) => setPassword(event.target.value)}
            placeholder="Enter password"
            type={showPassword ? "text" : "password"}
            value={password}
          />
          <button
            aria-label={showPassword ? "Hide password" : "Show password"}
            className="login-eye"
            onClick={() => setShowPassword(!showPassword)}
            type="button"
          >
            <Icon name={showPassword ? "eyeoff" : "eye"} size={16} />
          </button>
        </span>
      </label>

      {error && (
        <div className="login-error">
          <Icon name="alert" size={14} />
          <span>{error}</span>
        </div>
      )}

      <button className="button success login-submit workforce-submit" disabled={busy} type="submit">
        {busy && <span className="login-spinner"></span>}
        {busy ? "Signing in…" : `Sign in as ${workforceLoginPersonas.find((p) => p.role === selectedRole)?.label || "Employee"}`}
      </button>

      <div className="login-footer">OVO Workforce demo tenant · Mock data only</div>
    </form>
  );
}

const WORKFORCE_IDENTITY = {
  employee: { name: "Musa Garba", initials: "MG", unit: "Security · North Gate" },
  supervisor: { name: "Rose Adeyemi", initials: "RA", unit: "Shift Supervisor" }
};

function WorkforceMobileApp({ dataset }) {
  const [authenticatedRole, setAuthenticatedRole] = React.useState(null);
  const [activeTab, setActiveTab] = React.useState(workforceTabs.employee[0]);
  const [showAccountSheet, setShowAccountSheet] = React.useState(false);
  const tabs = authenticatedRole ? workforceTabs[authenticatedRole] : [];
  const identity = authenticatedRole ? WORKFORCE_IDENTITY[authenticatedRole] : null;

  function loginAs(role) {
    setAuthenticatedRole(role);
    setActiveTab(workforceTabs[role][0]);
    setShowAccountSheet(false);
  }

  function logout() {
    setAuthenticatedRole(null);
    setActiveTab(workforceTabs.employee[0]);
    setShowAccountSheet(false);
  }

  function changeTab(tab) {
    setActiveTab(tab);
    setShowAccountSheet(false);
  }

  if (!authenticatedRole) {
    return (
      <PhoneFrame product="Workforce" hideNav>
        <WorkforceLoginView onLogin={loginAs} />
      </PhoneFrame>
    );
  }

  return (
    <PhoneFrame navItems={tabs} product="Workforce" activeNav={activeTab} onNavChange={changeTab}>
      <MobileAccountHeader
        accountName={identity.name}
        accountScope={identity.unit}
        dataset={dataset}
        onAccount={() => setShowAccountSheet(!showAccountSheet)}
        product="Workforce"
        role={authenticatedRole}
      />
      {showAccountSheet && (
        <MobileAccountSheet
          accountName={identity.name}
          onLogout={logout}
          product="Workforce"
          role={authenticatedRole}
          scope={`${authenticatedRole} account · ${identity.unit}`}
        />
      )}
      {authenticatedRole === "employee" ? (
        <WorkforceEmployeeView dataset={dataset} activeTab={activeTab} />
      ) : (
        <WorkforceSupervisorView dataset={dataset} activeTab={activeTab} />
      )}
    </PhoneFrame>
  );
}
function WorkforceEmployeeView({ dataset, activeTab }) {
  if (activeTab === "Check-in") {
    return (
      <div className="mobile-panel-stack">
        <div className="mobile-check-state success workforce">
          <div className="check-circle compact">✓</div>
          <h2>Checked in</h2>
          <p>North Gate · Morning shift</p>
        </div>
        <MobileList items={[
          { title: "Shift token", detail: "Server-authorised workplace token", state: "Valid", tone: "green" },
          { title: "Employee match", detail: "Security department assignment", state: "Matched", tone: "green" },
          { title: "Device signature", detail: "Android Keystore / TEE signature", state: "Verified", tone: "green" },
          { title: "Geofence", detail: "North Gate approved zone", state: "Inside", tone: "green" }
        ]} />
        <Button tone="success">Check out later</Button>
        <div className="mobile-note">Check-out uses the same authorised token flow as CampusOS attendance.</div>
      </div>
    );
  }

  if (activeTab === "History") {
    return (
      <div className="mobile-panel-stack">
        <h2 className="mobile-view-title">Attendance history</h2>
        <MobileList items={[
          { title: "Today", detail: "Checked in 07:58 · North Gate", state: "Present", tone: "green" },
          { title: "Yesterday", detail: "Checked out 16:03 · approved", state: "Complete", tone: "green" },
          { title: "Friday", detail: "Late arrival exception · reviewed by supervisor", state: "Reviewed", tone: "gold" }
        ]} />
        <div className="mobile-note">History reflects server-approved shift records only.</div>
      </div>
    );
  }

  if (activeTab === "Alerts") {
    return (
      <div className="mobile-panel-stack">
        <h2 className="mobile-view-title">Alerts</h2>
        <MobileList items={[
          { title: "Night shift cover requested", detail: "Tomorrow · South Gate · reply on web portal", state: "New", tone: "gold" },
          { title: "Geofence update", detail: "Engineering Block zone radius adjusted to 60m", state: "Info", tone: "blue" }
        ]} />
      </div>
    );
  }

  return (
    <div className="mobile-panel-stack">
      <div className="mobile-card-highlight workforce">
        <Badge tone="purple">Morning shift</Badge>
        <h2>Security · North Gate</h2>
        <p>07:30 - 16:00 · Supervisor: Rose Adeyemi</p>
      </div>
      <div className="mobile-stat-grid">
        <MobileStat label="Status" value="In" tone="green" />
        <MobileStat label="Hours" value="2.1h" tone="purple" />
      </div>
      <MobileList items={[
        { title: "Next action", detail: "Check out when leaving approved workplace", state: "Later", tone: "blue" },
        { title: "Notification", detail: "Night shift cover requested tomorrow", state: "New", tone: "gold" }
      ]} />
      <div className="mobile-note">Rosters and payroll remain on the Workforce web portal.</div>
    </div>
  );
}

function WorkforceSupervisorView({ dataset, activeTab }) {
  if (activeTab === "Approvals") {
    return (
      <div className="mobile-panel-stack">
        <h2 className="mobile-view-title">Approvals</h2>
        <MobileList items={[
          { title: "Late arrival", detail: "Ife Okoro · Admin Office · today 08:12", state: "Approve", tone: "gold" },
          { title: "Shift swap", detail: "Peter Mensah requests night cover swap", state: "Review", tone: "blue" },
          { title: "Location exception", detail: "Facilities team moved to Engineering Block", state: "Audit", tone: "purple" }
        ]} />
        <div className="mobile-note">Approval decisions sync to the supervisor web portal audit trail.</div>
      </div>
    );
  }

  if (activeTab === "Shifts") {
    return (
      <div className="mobile-panel-stack">
        <h2 className="mobile-view-title">Shifts</h2>
        <MobileList items={[
          { title: "Tonight · South Gate", detail: "Peter Mensah · cover requested", state: "Open", tone: "gold" },
          { title: "Tomorrow · North Gate", detail: "Musa Garba · confirmed", state: "Scheduled", tone: "blue" },
          { title: "Tomorrow · Facilities", detail: "Rose Adeyemi · confirmed", state: "Scheduled", tone: "blue" }
        ]} />
      </div>
    );
  }

  if (activeTab === "Reports") {
    return (
      <div className="mobile-panel-stack">
        <h2 className="mobile-view-title">Reports</h2>
        <MiniChart values={[71, 78, 74, 82, 85, 80]} />
        <MobileList items={[
          { title: "This week attendance", detail: "Security team average across shifts", state: "84%", tone: "green" },
          { title: "Open exceptions", detail: "1 late arrival pending approval", state: "1", tone: "gold" }
        ]} />
        <div className="mobile-note">Full reports and exports are available on the web portal.</div>
      </div>
    );
  }

  return (
    <div className="mobile-panel-stack">
      <div className="mobile-card-highlight workforce">
        <Badge tone="purple">Supervisor quick actions</Badge>
        <h2>{dataset.workforceUnit}</h2>
        <p>Full department administration remains web-based.</p>
      </div>
      <div className="mobile-stat-grid">
        <MobileStat label="Checked in" value="2" tone="green" />
        <MobileStat label="Pending" value="1" tone="gold" />
        <MobileStat label="Scheduled" value="1" tone="blue" />
        <MobileStat label="Exceptions" value="3" tone="purple" />
      </div>
      <MobileList items={dataset.workforce.map((employee) => ({
        title: employee.name,
        detail: `${employee.team} · ${employee.shift} · ${employee.location}`,
        state: employee.state,
        tone: employee.state === "Checked In" ? "green" : employee.state === "Pending" ? "gold" : "blue"
      }))} />
    </div>
  );
}

Object.assign(window, {
  WorkforceMobileApp,
  WorkforceLoginView,
  workforceLoginPersonas,
  workforceTabs
});
