/* Al Hajar Employee Mobile App — standalone field self-service */
const EMA_TABS=[['home','Home','grid'],['attendance','Attendance','clock'],['leave','Leave','calendar'],['hse','HSE','helmet']];
/* iOS tab bars hold five items at most, so the remaining sections live behind More. */
const EMA_MORE=[['payslip','Payslip','receipt','Payslips, earnings and deductions'],['documents','Documents','documents','Visa, passport and labour card expiry'],['training','Training','certificate','Courses and certificate validity']];

const emaToday=()=>new Date().toISOString().slice(0,10),emaDays=d=>d?Math.ceil((new Date(d)-DB.TODAY)/DB.day):null;
function EmployeePicker({onPick}){return <main className="ema-picker"><div className="ema-picker-card"><img src="assets/aicos-mark.png" alt="AI-COS"/><div className="eyebrow">Employee mobile app</div><h1>Welcome to Al Hajar</h1><p className="muted">Choose any employee to demonstrate secure self-service.</p><div className="ema-people">{DB.employees.filter(x=>x.status!=='Demobilized').map(e=><button key={e.id} onClick={()=>onPick(e.id)}><span className="avatar">{e.name.split(' ').map(x=>x[0]).slice(0,2).join('')}</span><span><b>{e.name}</b><small>{e.designation} · {e.project}</small></span><Icon name="chevR"/></button>)}</div><div className="ema-offline"><Icon name="shield"/>Offline-capable workflow note: field entries can be captured locally and synchronised when connectivity returns.</div><div className="ema-powered"><span>Powered by</span><img src="assets/aicos-logo-white.png" alt="AI-COS"/></div></div></main>}
function EmaCard({title,sub,children,action}){return <section className="ema-card"><div className="ema-card-head"><div><b>{title}</b>{sub&&<span>{sub}</span>}</div>{action}</div>{children}</section>}
function HomeTab({employee,onTab}){const today=DB.attendance.find(x=>x.employee===employee.id&&x.date===emaToday())||DB.attendance.find(x=>x.employee===employee.id),project=DB.projectById(employee.project);return <div><div className="ema-hero"><span>Good day</span><h2>{employee.name.split(' ')[0]}</h2><p>{employee.designation} · {project?.name}</p><div><b>{today?.status||'Not clocked'}</b><small>Today's attendance</small></div></div><div className="ema-quick">{[['attendance','Clock in','clock'],['leave','Request leave','calendar'],['payslip','View payslip','receipt'],['hse','Report HSE','helmet']].map(x=><button key={x[0]} onClick={()=>onTab(x[0])}><Icon name={x[2]}/><span>{x[1]}</span></button>)}</div><EmaCard title="Next payday" sub="31 August 2026"><div className="ema-row"><Icon name="receipt"/><span>Salary through WPS</span><b>{window.money(employee.basicSalary+employee.allowances)}</b></div></EmaCard><div className="ema-offline"><Icon name="shield"/>Offline capture enabled for attendance, leave and HSE drafts.</div></div>}
function AttendanceTab({employee}){const [clocked,setClocked]=useState(false),rows=DB.attendance.filter(x=>x.employee===employee.id).sort((a,b)=>b.date.localeCompare(a.date)).slice(0,14),clock=()=>{const existing=DB.attendance.find(x=>x.employee===employee.id&&x.date===emaToday());if(existing){existing.status='Present';existing.hoursWorked=clocked?8:existing.hoursWorked;existing.clockOut=clocked?new Date().toLocaleTimeString():null;existing.clockIn=existing.clockIn||new Date().toLocaleTimeString();}else dbAdd('attendance',{id:`ATT-MOB-${Date.now()}`,employee:employee.id,project:employee.project,date:emaToday(),status:'Present',hoursWorked:clocked?8:0,overtimeHours:0,shift:'Day',clockIn:new Date().toLocaleTimeString()});setClocked(!clocked);toast(clocked?'Clocked out':'Clocked in','ok')};return <div><EmaCard title="Today" sub={new Date().toLocaleDateString('en-GB',{weekday:'long',day:'numeric',month:'long'})}><button className={`ema-primary ${clocked?'ema-clocked':''}`} onClick={clock}><Icon name={clocked?'logout':'clock'}/>{clocked?'Clock out':'Clock in'}</button><p className="ema-help">Simulation writes a live attendance row for this demo session.</p></EmaCard><EmaCard title="Recent days">{rows.map(x=><div className="ema-row" key={x.id}><span><b>{DB.fmt(x.date)}</b><small>{x.shift} shift · {x.hoursWorked}h {x.overtimeHours?`+ ${x.overtimeHours}h OT`:''}</small></span><Badge kind={x.status==='Present'?'ok':x.status==='Absent'?'bad':'warn'}>{x.status}</Badge></div>)}</EmaCard></div>}
function LeaveTab({employee}){const mine=DB.leaveRequests.filter(x=>x.employee===employee.id),used=mine.filter(x=>x.status==='Approved'&&x.type==='Annual').reduce((a,x)=>a+x.days,0),[form,setForm]=useState({type:'Annual',from:'',to:'',reason:''}),set=(k,v)=>setForm(x=>({...x,[k]:v})),submit=()=>{if(!form.from||!form.to)return toast('Select leave dates','bad');const days=Math.max(1,Math.ceil((new Date(form.to)-new Date(form.from))/DB.day)+1);dbAdd('leaveRequests',{id:`LV-MOB-${Date.now()}`,employee:employee.id,...form,days,balanceBefore:30-used,status:'Pending',approver:DB.employees[33].id});toast('Leave request submitted','ok');setForm({type:'Annual',from:'',to:'',reason:''})};return <div><div className="ema-balance"><span>Annual leave balance</span><b>{30-used}<small> / 30 days</small></b><div><i style={{width:`${(30-used)/30*100}%`}}/></div><small>30 calendar days after one year of service</small></div><EmaCard title="New request"><div className="ema-form"><label>Type<select value={form.type} onChange={e=>set('type',e.target.value)}>{['Annual','Sick','Emergency','Unpaid','Hajj'].map(x=><option key={x}>{x}</option>)}</select></label><div className="ema-form-two"><label>From<input type="date" value={form.from} onChange={e=>set('from',e.target.value)}/></label><label>To<input type="date" value={form.to} onChange={e=>set('to',e.target.value)}/></label></div><label>Reason<textarea value={form.reason} onChange={e=>set('reason',e.target.value)} rows="3"/></label><button className="ema-primary" onClick={submit}>Submit request</button></div></EmaCard><EmaCard title="My requests">{mine.length?mine.map(x=><div className="ema-row" key={x.id}><span><b>{x.type} · {x.days} days</b><small>{DB.fmt(x.from)} → {DB.fmt(x.to)}</small></span><StatusBadge status={x.status}/></div>):<p className="ema-help">No requests yet.</p>}</EmaCard></div>}
function PayslipTab({employee}){const print=run=>{document.title=`Payslip ${employee.name} ${run.period}`;window.print()};return <div><div className="ema-print-head"><b>{DB.company.name}</b><span>{DB.company.nameAr}</span></div>{DB.payrollRuns.slice().reverse().map(run=>{const overtime=Number((employee.basicSalary/240*8).toFixed(3)),gosi=employee.omani?employee.basicSalary*.07:0,ded=25,gross=employee.basicSalary+employee.allowances+overtime,net=gross-gosi-ded;return <EmaCard key={run.id} title={new Date(run.period+'-01').toLocaleDateString('en-GB',{month:'long',year:'numeric'})} sub={run.status} action={<button className="ema-icon" onClick={()=>print(run)}><Icon name="download"/></button>}><div className="ema-paygrid">{[['Basic',employee.basicSalary],['Allowances',employee.allowances],['Overtime',overtime],['Deductions',ded],['GOSI employee',gosi],['Net pay',net]].map(x=><div key={x[0]}><span>{x[0]}</span><b>{window.money(x[1])}</b></div>)}</div>{!employee.omani&&<p className="ema-help">Expatriate employee — GOSI exempt.</p>}</EmaCard>})}</div>}
/* Field reporting — two independent workflows, because an incident and an observation are
   different records with different statutory obligations:
     incident    → 3 steps (details → people & causes → review and notify)
     observation → 2 steps (details → evidence, follow-up and submit)
   Both support Save draft, photo/video evidence and a GPS stamp. */
const EMA_INC_TYPES=[['Near miss','alert'],['Injury','users'],['Environmental','leaf'],['Property damage','building'],['Road traffic','truck']];
const EMA_INJURY=[['First aid case','FAC'],['Medical treatment','MTC'],['Lost time injury','LTI']];
const EMA_OBS_CLASSES=[['Safe act','check'],['Unsafe act','alert'],['Safe condition','shield'],['Unsafe condition','flag'],['Positive intervention','star']];
const EMA_SEVERITY=['Low','Medium','High','Critical'];
const EMA_BODY=['Head','Eyes','Face','Neck','Shoulder','Back','Arm','Hand','Fingers','Leg','Knee','Foot','Multiple'];
const emaTime=()=>new Date().toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'});
const EMA_DRAFT_KEY='ahc-mobile-drafts';
const emaDrafts=()=>{try{return JSON.parse(localStorage.getItem(EMA_DRAFT_KEY)||'[]')}catch(e){return[]}};
const emaWriteDrafts=list=>{try{localStorage.setItem(EMA_DRAFT_KEY,JSON.stringify(list.slice(0,8)))}catch(e){}};
const emaSaveDraft=(kind,employee,step,data)=>emaWriteDrafts([{kind,employee,step,savedAt:new Date().toISOString(),data},...emaDrafts().filter(d=>!(d.kind===kind&&d.employee===employee))]);
const emaGetDraft=(kind,employee)=>emaDrafts().find(d=>d.kind===kind&&d.employee===employee)||null;
const emaDropDraft=(kind,employee)=>emaWriteDrafts(emaDrafts().filter(d=>!(d.kind===kind&&d.employee===employee)));

function EmaSteps({step,total,label}){return <div className="ema-steps"><div className="ema-steps-dots">{Array.from({length:total},(_,i)=><React.Fragment key={i}>{i>0&&<i className={'ema-step-line'+(i<step?' done':'')}/>}<span className={'ema-step'+(i+1===step?' on':i+1<step?' done':'')}>{i+1<step?<Icon name="check" size={12}/>:i+1}</span></React.Fragment>)}</div><div className="ema-steps-label">Step {step} of {total} · {label}</div></div>}
function EmaTiles({options,value,onPick,cols=3}){return <div className={'ema-tiles'+(options.length%cols?' span-last':'')} style={{gridTemplateColumns:`repeat(${cols},minmax(0,1fr))`}}>{options.map(o=><button type="button" key={o[0]} className={'ema-tile'+(value===o[0]?' on':'')} onClick={()=>onPick(o[0])}><Icon name={o[1]} size={17}/><span>{o[0]}</span></button>)}</div>}
function EmaChips({options,value,onPick,label}){return <div className="ema-fieldrow"><span className="ema-flabel">{label}</span><div className="ema-chiprow">{options.map(o=><button type="button" key={o} className={'ema-pick'+(value===o?' on '+o.toLowerCase():'')} onClick={()=>onPick(o)}>{o}</button>)}</div></div>}
function EmaToggle({label,on,onChange}){return <button type="button" className="ema-toggle" onClick={()=>onChange(!on)}><span>{label}</span><i className={on?'on':''}><b/></i></button>}
function EmaEvidence({media,setMedia,gps,setGps}){
  const fileRef=React.useRef(null);
  const locate=()=>{
    /* Demo shell: a real fix when the browser grants it, otherwise a labelled site coordinate
       so the workflow can still be shown on a desktop without location services. */
    const fallback=()=>{setGps({lat:23.58590,lng:58.40590,src:'Approximate site coordinates'});toast('Location attached (approximate)','info')};
    if(!navigator.geolocation)return fallback();
    navigator.geolocation.getCurrentPosition(
      p=>{setGps({lat:Number(p.coords.latitude.toFixed(5)),lng:Number(p.coords.longitude.toFixed(5)),src:'Device GPS'});toast('GPS location attached','ok')},
      fallback,{timeout:6000,maximumAge:60000});
  };
  return <div className="ema-evidence-block">
    <div className="ema-evidence">
      <button type="button" onClick={()=>fileRef.current&&fileRef.current.click()}><Icon name="camera" size={19}/><span>Add photo or video</span></button>
      <button type="button" className={gps?'on':''} onClick={locate}><Icon name="pin" size={19}/><span>Use current location</span></button>
    </div>
    <input ref={fileRef} type="file" accept="image/*,video/*" multiple style={{display:'none'}}
      onChange={e=>{const names=Array.from(e.target.files||[]).map(f=>f.name);if(names.length){setMedia(m=>[...m,...names]);toast(`${names.length} file${names.length>1?'s':''} attached`,'ok')}e.target.value=''}}/>
    {(media.length>0||gps)&&<div className="ema-chipset">
      {media.map((m,i)=><span className="ema-chip" key={m+i}><Icon name="camera" size={11}/>{m}<button type="button" onClick={()=>setMedia(x=>x.filter((_,j)=>j!==i))}><Icon name="x" size={10}/></button></span>)}
      {gps&&<span className="ema-chip"><Icon name="pin" size={11}/>{gps.lat}° N, {gps.lng}° E · {gps.src}<button type="button" onClick={()=>setGps(null)}><Icon name="x" size={10}/></button></span>}
    </div>}
  </div>;
}
function EmaFoot({onDraft,onBack,label,icon,onNext}){return <div className="ema-foot">{onBack?<button type="button" className="ema-ghost" onClick={onBack}><Icon name="chevL" size={15}/>Back</button>:<button type="button" className="ema-ghost" onClick={onDraft}><Icon name="documents" size={15}/>Save draft</button>}<button type="button" className="ema-primary" onClick={onNext}><Icon name={icon} size={16}/>{label}</button></div>}
function EmaReview({rows}){return <div className="ema-review">{rows.filter(r=>r[1]!==''&&r[1]!=null).map(r=><div key={r[0]}><span>{r[0]}</span><b>{r[1]}</b></div>)}</div>}

function HseTab({employee}){
  const [mode,setMode]=useState('observation');
  const proj=DB.projectById?DB.projectById(employee.project):null;
  const projectName=proj?proj.name:employee.project;
  const blankInc=()=>({typeTile:'Near miss',injuryClass:'FAC',date:emaToday(),time:emaTime(),site:projectName,location:'',title:'',description:'',immediateAction:'',severity:'Medium',injuredName:'',bodyPart:'Hand',side:'L',lostDays:'',witnesses:'',causes:[],rootCause:'',notifyNow:true});
  const blankObs=()=>({classification:'Unsafe condition',date:emaToday(),time:emaTime(),site:projectName,location:'',category:'PPE',title:'',description:'',riskLevel:'Medium',immediateAction:'',corrected:true,followUp:false,followUpTo:''});
  const [step,setStep]=useState(1);
  const [inc,setInc]=useState(blankInc);
  const [obs,setObs]=useState(blankObs);
  const [incMedia,setIncMedia]=useState([]),[incGps,setIncGps]=useState(null);
  const [obsMedia,setObsMedia]=useState([]),[obsGps,setObsGps]=useState(null);
  const [draftTick,setDraftTick]=useState(0);
  const draft=emaGetDraft(mode,employee.id);
  const setI=(k,v)=>setInc(x=>({...x,[k]:v})),setO=(k,v)=>setObs(x=>({...x,[k]:v}));
  const switchMode=m=>{setMode(m);setStep(1)};
  const isInjury=inc.typeTile==='Injury';
  const incType=isInjury?inc.injuryClass:inc.typeTile==='Road traffic'?'RTA':inc.typeTile;
  const mates=DB.employees.filter(e=>e.project===employee.project&&e.id!==employee.id).slice(0,10);

  const saveDraft=()=>{
    emaSaveDraft(mode,employee.id,step,mode==='incident'?{form:inc,media:incMedia,gps:incGps}:{form:obs,media:obsMedia,gps:obsGps});
    setDraftTick(t=>t+1);toast('Draft saved on this device','ok');
  };
  const resumeDraft=()=>{
    const d=emaGetDraft(mode,employee.id);if(!d)return;
    if(mode==='incident'){setInc(d.data.form);setIncMedia(d.data.media||[]);setIncGps(d.data.gps||null)}
    else{setObs(d.data.form);setObsMedia(d.data.media||[]);setObsGps(d.data.gps||null)}
    setStep(d.step||1);toast('Draft restored','ok');
  };
  const discardDraft=()=>{emaDropDraft(mode,employee.id);setDraftTick(t=>t+1);toast('Draft discarded','info')};

  const incNext=()=>{
    if(step===1){
      if(!inc.location.trim())return toast('Enter the exact location on site','bad');
      if(!inc.title.trim())return toast('Give the incident a short title','bad');
      if(!inc.description.trim())return toast('Describe what happened','bad');
      return setStep(2);
    }
    if(step===2){
      if(isInjury&&!inc.injuredName.trim())return toast('Name the injured person','bad');
      if(inc.injuryClass==='LTI'&&isInjury&&!String(inc.lostDays).trim())return toast('Lost time injuries need the days lost','bad');
      return setStep(3);
    }
    submitInc();
  };
  const submitInc=()=>{
    const rec={id:`INC-MOB-${DB.hseIncidents.length+1}`,project:employee.project,site:inc.site,location:inc.location,
      date:inc.date,time:inc.time,type:incType,title:inc.title,description:inc.description,immediateAction:inc.immediateAction,
      severity:inc.severity,injuredPerson:isInjury?inc.injuredName:null,bodyPart:isInjury?inc.bodyPart:null,side:isInjury?inc.side:'',
      lostDays:isInjury&&inc.injuryClass==='LTI'?Number(inc.lostDays)||0:0,recordable:['LTI','MTC'].includes(incType),
      witnesses:inc.witnesses,immediateCauses:inc.causes,rootCause:inc.rootCause,
      photos:incMedia.length,evidence:incMedia,gps:incGps,reportedVia:'Employee mobile app',
      status:'Open',reportedBy:employee.id};
    dbAdd('hseIncidents',rec);
    const to=inc.notifyNow?['HSE Manager','Project Manager']:['HSE Manager'];
    window.notify&&window.notify('hse-incident',to,`${incType} reported on ${projectName} — ${inc.title}`);
    emaDropDraft('incident',employee.id);setDraftTick(t=>t+1);
    setInc(blankInc());setIncMedia([]);setIncGps(null);setStep(1);
    toast(`${rec.id} submitted — QHSE Manager notified`,'ok');
  };
  const obsNext=()=>{
    if(step===1){
      if(!obs.location.trim())return toast('Enter the exact location on site','bad');
      if(!obs.title.trim())return toast('Give the observation a short title','bad');
      if(!obs.description.trim())return toast('Describe what you observed','bad');
      return setStep(2);
    }
    submitObs();
  };
  const submitObs=()=>{
    const closed=obs.corrected&&!obs.followUp;
    const rec={id:`OBS-MOB-${DB.hseObservations.length+1}`,project:employee.project,site:obs.site,location:obs.location,
      date:obs.date,time:obs.time,classification:obs.classification,category:obs.category,title:obs.title,
      description:obs.description,riskLevel:obs.riskLevel,immediateAction:obs.immediateAction,correctedOnSite:obs.corrected,
      assignedTo:obs.followUp?obs.followUpTo:null,photos:obsMedia.length,evidence:obsMedia,gps:obsGps,
      reportedVia:'Employee mobile app',raisedBy:employee.id,status:closed?'Closed':'Open',closeDate:closed?emaToday():null};
    dbAdd('hseObservations',rec);
    const owner=obs.followUp&&obs.followUpTo?DB.empById(obs.followUpTo):null;
    window.notify&&window.notify('hse-observation',['HSE Manager'],`${obs.classification} — ${obs.title} on ${projectName}${owner?` · follow-up assigned to ${owner.name}`:''}`);
    emaDropDraft('observation',employee.id);setDraftTick(t=>t+1);
    setObs(blankObs());setObsMedia([]);setObsGps(null);setStep(1);
    toast(`${rec.id} submitted${closed?' and closed on site':' — follow-up open'}`,'ok');
  };

  const training=DB.trainingRecords.filter(x=>x.employee===employee.id);
  return <div key={draftTick}>
    <div className="ema-seg">
      <button className={mode==='observation'?'on':''} onClick={()=>switchMode('observation')}>Report observation</button>
      <button className={mode==='incident'?'on':''} onClick={()=>switchMode('incident')}>Report incident</button>
    </div>
    {draft&&step===1&&<div className="ema-draftbar"><Icon name="documents" size={15}/><span><b>Draft saved</b><small>{new Date(draft.savedAt).toLocaleString('en-GB',{day:'numeric',month:'short',hour:'2-digit',minute:'2-digit'})} · step {draft.step}</small></span><button onClick={resumeDraft}>Resume</button><button className="ghost" onClick={discardDraft}>Discard</button></div>}

    {mode==='incident'?<EmaCard title="Report QHSE incident" sub="Report an incident or near miss quickly">
      <EmaSteps step={step} total={3} label={['Incident details','People and causes','Review and submit'][step-1]}/>
      {step===1&&<div className="ema-form">
        <div className="ema-fieldrow"><span className="ema-flabel">Incident type *</span><EmaTiles options={EMA_INC_TYPES} value={inc.typeTile} onPick={v=>setI('typeTile',v)}/></div>
        {isInjury&&<label>Injury classification<select value={inc.injuryClass} onChange={e=>setI('injuryClass',e.target.value)}>{EMA_INJURY.map(x=><option key={x[1]} value={x[1]}>{x[0]} ({x[1]})</option>)}</select></label>}
        <div className="ema-form-two"><label>Date *<input type="date" value={inc.date} onChange={e=>setI('date',e.target.value)}/></label><label>Time *<input type="time" value={inc.time} onChange={e=>setI('time',e.target.value)}/></label></div>
        <label>Project / site *<input value={inc.site} onChange={e=>setI('site',e.target.value)}/></label>
        <label>Exact location *<input value={inc.location} onChange={e=>setI('location',e.target.value)} placeholder="e.g. Block B, level 3 scaffold bay 4"/></label>
        <label>Incident title *<input value={inc.title} onChange={e=>setI('title',e.target.value)} placeholder="Brief title"/></label>
        <label>What happened? *<textarea rows="4" value={inc.description} onChange={e=>setI('description',e.target.value)} placeholder="Describe the incident clearly"/></label>
        <label>Immediate actions taken<textarea rows="3" value={inc.immediateAction} onChange={e=>setI('immediateAction',e.target.value)} placeholder="Describe actions taken"/></label>
        <EmaChips label="Severity" options={EMA_SEVERITY} value={inc.severity} onPick={v=>setI('severity',v)}/>
        <EmaEvidence media={incMedia} setMedia={setIncMedia} gps={incGps} setGps={setIncGps}/>
        <EmaToggle label="Notify QHSE Manager immediately" on={inc.notifyNow} onChange={v=>setI('notifyNow',v)}/>
        <div className="ema-note"><Icon name="shield" size={13}/> You can complete the investigation details later.</div>
        <EmaFoot onDraft={saveDraft} label="Continue" icon="chevR" onNext={incNext}/>
      </div>}
      {step===2&&<div className="ema-form">
        {isInjury?<React.Fragment>
          <label>Injured person *<input value={inc.injuredName} onChange={e=>setI('injuredName',e.target.value)} placeholder="Name or crew number"/></label>
          <div className="ema-form-two">
            <label>Body part<select value={inc.bodyPart} onChange={e=>setI('bodyPart',e.target.value)}>{EMA_BODY.map(x=><option key={x}>{x}</option>)}</select></label>
            <label>Side<select value={inc.side} onChange={e=>setI('side',e.target.value)}><option value="L">Left</option><option value="R">Right</option><option value="">Not applicable</option></select></label>
          </div>
          {inc.injuryClass==='LTI'&&<label>Days lost *<input type="number" min="1" value={inc.lostDays} onChange={e=>setI('lostDays',e.target.value)} placeholder="Estimated days away from work"/></label>}
        </React.Fragment>:<div className="ema-note">No injury recorded for a {incType.toLowerCase()} — capture the causes so the HSE team can act.</div>}
        <label>Witnesses<input value={inc.witnesses} onChange={e=>setI('witnesses',e.target.value)} placeholder="Names, if any"/></label>
        <div className="ema-fieldrow"><span className="ema-flabel">Immediate causes</span><div className="ema-chiprow">{['Unsafe act','Unsafe condition','PPE not used','Procedure not followed','Equipment failure','Housekeeping','Weather'].map(c=><button type="button" key={c} className={'ema-pick'+(inc.causes.includes(c)?' on':'')} onClick={()=>setInc(x=>({...x,causes:x.causes.includes(c)?x.causes.filter(y=>y!==c):[...x.causes,c]}))}>{c}</button>)}</div></div>
        <label>Suspected root cause<textarea rows="3" value={inc.rootCause} onChange={e=>setI('rootCause',e.target.value)} placeholder="Optional — the HSE team will investigate"/></label>
        <EmaFoot onBack={()=>setStep(1)} label="Continue" icon="chevR" onNext={incNext}/>
      </div>}
      {step===3&&<div className="ema-form">
        <EmaReview rows={[['Type',incType],['Severity',inc.severity],['When',`${DB.fmt(inc.date)} · ${inc.time}`],['Project / site',inc.site],['Exact location',inc.location],['Title',inc.title],['Injured person',isInjury?`${inc.injuredName} · ${inc.bodyPart}${inc.side?` (${inc.side})`:''}`:'None'],['Days lost',isInjury&&inc.injuryClass==='LTI'?inc.lostDays:null],['Immediate causes',inc.causes.join(', ')||'Not stated'],['Evidence',`${incMedia.length} file${incMedia.length===1?'':'s'}${incGps?' · GPS attached':''}`],['Recordable',['LTI','MTC'].includes(incType)?'Yes — OSHA recordable':'No']]}/>
        <div className="ema-note"><Icon name="bell" size={13}/> On submission this reaches the HSE Manager{inc.notifyNow?' and the Project Manager':''} immediately and opens an investigation record.</div>
        <EmaFoot onBack={()=>setStep(2)} label="Submit incident" icon="helmet" onNext={incNext}/>
      </div>}
    </EmaCard>:<EmaCard title="QHSE observation" sub="Report safe and unsafe workplace observations">
      <EmaSteps step={step} total={2} label={step===1?'Observation details':'Evidence and follow-up'}/>
      {step===1&&<div className="ema-form">
        <div className="ema-fieldrow"><span className="ema-flabel">Observation classification *</span><EmaTiles options={EMA_OBS_CLASSES} value={obs.classification} onPick={v=>setO('classification',v)} cols={2}/></div>
        <div className="ema-form-two"><label>Date *<input type="date" value={obs.date} onChange={e=>setO('date',e.target.value)}/></label><label>Time *<input type="time" value={obs.time} onChange={e=>setO('time',e.target.value)}/></label></div>
        <label>Project / site *<input value={obs.site} onChange={e=>setO('site',e.target.value)}/></label>
        <label>Exact location *<input value={obs.location} onChange={e=>setO('location',e.target.value)} placeholder="e.g. Zone C, pipe rack near gate 2"/></label>
        <label>Category *<select value={obs.category} onChange={e=>setO('category',e.target.value)}>{['PPE','Housekeeping','Work at height','Electrical','Lifting','Excavation','Traffic','Environment','Behaviour'].map(x=><option key={x}>{x}</option>)}</select></label>
        <label>Observation title *<input value={obs.title} onChange={e=>setO('title',e.target.value)} placeholder="Brief title"/></label>
        <label>Describe what you observed *<textarea rows="4" value={obs.description} onChange={e=>setO('description',e.target.value)} placeholder="Describe the act or condition clearly"/></label>
        <EmaChips label="Risk level" options={EMA_SEVERITY} value={obs.riskLevel} onPick={v=>setO('riskLevel',v)}/>
        <label>Immediate action taken<textarea rows="3" value={obs.immediateAction} onChange={e=>setO('immediateAction',e.target.value)} placeholder="Describe the correction or intervention"/></label>
        <EmaToggle label="Was the issue corrected immediately?" on={obs.corrected} onChange={v=>setO('corrected',v)}/>
        <EmaFoot onDraft={saveDraft} label="Continue" icon="chevR" onNext={obsNext}/>
      </div>}
      {step===2&&<div className="ema-form">
        <EmaEvidence media={obsMedia} setMedia={setObsMedia} gps={obsGps} setGps={setObsGps}/>
        <EmaToggle label="Assign for follow-up" on={obs.followUp} onChange={v=>setO('followUp',v)}/>
        {obs.followUp&&<label>Assign to<select value={obs.followUpTo} onChange={e=>setO('followUpTo',e.target.value)}><option value="">Select a colleague on this project</option>{mates.map(m=><option key={m.id} value={m.id}>{m.name} — {m.designation}</option>)}</select></label>}
        <EmaReview rows={[['Classification',obs.classification],['Risk level',obs.riskLevel],['Category',obs.category],['When',`${DB.fmt(obs.date)} · ${obs.time}`],['Exact location',obs.location],['Corrected on site',obs.corrected?'Yes':'No — remains open'],['Evidence',`${obsMedia.length} file${obsMedia.length===1?'':'s'}${obsGps?' · GPS attached':''}`]]}/>
        <div className="ema-note"><Icon name="shield" size={13}/> Your report helps prevent incidents and recognise good practice.</div>
        <EmaFoot onBack={()=>setStep(1)} label="Submit observation" icon="check" onNext={obsNext}/>
      </div>}
    </EmaCard>}
    {step===1&&<EmaCard title="My HSE certificates">{training.length?training.map(x=><div className="ema-row" key={x.id}><span><b>{x.course}</b><small>{x.certificateNo} · expires {DB.fmt(x.expiry)}</small></span><Badge kind={x.status==='Valid'?'ok':x.status==='Expiring'?'warn':'bad'}>{x.status}</Badge></div>):<div className="ema-empty">No assigned certificates in the demo data.</div>}</EmaCard>}
  </div>;
}

function DocumentsTab({employee}){const docs=[['Passport',employee.passportExpiry,'documents'],['Visa',employee.visaExpiry,'shield'],['Labour card',employee.labourCardExpiry,'certificate']].filter(x=>x[1]);return <div><EmaCard title="My documents" sub="Keep originals and renewal evidence with HR">{docs.map(x=>{const n=emaDays(x[1]);return <div className="ema-document" key={x[0]}><span><Icon name={x[2]}/></span><div><b>{x[0]}</b><small>Expires {DB.fmt(x[1])}</small></div><Badge kind={n<=60?'bad':n<=120?'warn':'ok'}>{n<0?`${-n}d overdue`:`${n} days`}</Badge></div>})}{!docs.length&&<div className="ema-row"><Icon name="check"/><span>Omani national record — no visa or labour card required.</span></div>}</EmaCard><div className="ema-offline"><Icon name="lock"/>Documents are shown read-only. Contact HR for renewal or corrections.</div></div>}
function TrainingTab({employee}){const mine=DB.trainingRecords.filter(x=>x.employee===employee.id);return <div><EmaCard title="My courses" sub="Competency and certificate validity">{mine.length?mine.map(x=><div className="ema-training" key={x.id}><div className="ema-training-icon"><Icon name="certificate"/></div><div><b>{x.course}</b><span>{x.provider}</span><small>Completed {DB.fmt(x.completed)} · expires {DB.fmt(x.expiry)}</small></div><Badge kind={x.status==='Valid'?'ok':x.status==='Expiring'?'warn':'bad'}>{x.status}</Badge></div>):<EmptyState title="No courses assigned" desc="Your assigned courses and certificate expiry will appear here."/>}</EmaCard></div>}
function IPhoneStatus(){return <div className="iph-status"><b>9:41</b><div className="iph-status-icons"><svg viewBox="0 0 18 12" aria-label="Cellular signal"><rect x="1" y="8" width="2.5" height="3" rx="1"/><rect x="5" y="6" width="2.5" height="5" rx="1"/><rect x="9" y="3" width="2.5" height="8" rx="1"/><rect x="13" y="1" width="2.5" height="10" rx="1"/></svg><svg viewBox="0 0 16 12" aria-label="Wi-Fi"><path d="M1 4c4-3.5 10-3.5 14 0M3.5 7c2.6-2.2 6.4-2.2 9 0M6.5 10c.9-.8 2.1-.8 3 0" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/></svg><span className="iph-battery"><i/></span></div></div>;}
function IPhoneFrame({children}){/* Scale the device so the whole handset — including the tab bar and home indicator —   always fits the viewport height, whatever the laptop screen. */const ref=React.useRef(null);React.useEffect(()=>{const fit=()=>{const el=ref.current;if(!el)return;const h=window.innerHeight||0;if(h<200)return;const s=Math.max(.5,Math.min(1,(h-96)/898));el.style.setProperty('--iph-scale',s.toFixed(3));};fit();window.addEventListener('resize',fit);return()=>window.removeEventListener('resize',fit);},[]);return <div className="iph-stage" ref={ref}><div className="iph-device"><i className="iph-action"/><i className="iph-volume iph-volume-up"/><i className="iph-volume iph-volume-down"/><i className="iph-power"/><div className="iph-screen"><div className="iph-island"/><IPhoneStatus/>{children}<div className="iph-home"/></div></div><div className="iph-caption"><b>Employee Mobile App</b> · iOS & Android · offline-capable field capture<small>Interactive demo shell · representative device frame</small></div></div>;}
function EmployeeMobileApp(){const [employeeId,setEmployeeId]=useState(()=>sessionStorage.getItem('ahc-mobile-employee')||''),[tab,setTab]=useState('home'),[moreOpen,setMoreOpen]=useState(false),employee=DB.empById(employeeId),pick=id=>{sessionStorage.setItem('ahc-mobile-employee',id);setEmployeeId(id)};if(!employee)return <IPhoneFrame><EmployeePicker onPick={pick}/></IPhoneFrame>;const props={employee,onTab:setTab},views={home:<HomeTab {...props}/>,attendance:<AttendanceTab {...props}/>,leave:<LeaveTab {...props}/>,payslip:<PayslipTab {...props}/>,hse:<HseTab {...props}/>,documents:<DocumentsTab {...props}/>,training:<TrainingTab {...props}/>};return <IPhoneFrame><div className="ema-shell"><header className="ema-top"><img src="assets/aicos-mark.png" alt="AI-COS"/><div><b>Al Hajar</b><span>Employee App</span></div><button onClick={()=>{sessionStorage.removeItem('ahc-mobile-employee');setEmployeeId('')}}><Icon name="users"/></button></header><main className="ema-content">{views[tab]}</main><nav className="ema-nav">{EMA_TABS.map(x=><button key={x[0]} className={tab===x[0]?'active':''} onClick={()=>{setTab(x[0]);setMoreOpen(false)}}><Icon name={x[2]}/><span>{x[1]}</span></button>)}<button className={(EMA_MORE.some(m=>m[0]===tab)||moreOpen)?'active':''} onClick={()=>setMoreOpen(o=>!o)}><Icon name="menu"/><span>More</span></button></nav>{moreOpen&&<><div className="ema-sheet-scrim" onClick={()=>setMoreOpen(false)}/><div className="ema-sheet"><div className="ema-sheet-grip"/><div className="ema-sheet-title">More</div>{EMA_MORE.map(m=><button key={m[0]} className={'ema-sheet-row'+(tab===m[0]?' on':'')} onClick={()=>{setTab(m[0]);setMoreOpen(false)}}><span className="ema-sheet-ico"><Icon name={m[2]}/></span><span className="ema-sheet-text"><b>{m[1]}</b><small>{m[3]}</small></span><Icon name="chevR" size={14}/></button>)}<button className="ema-sheet-row" onClick={()=>{sessionStorage.removeItem('ahc-mobile-employee');setEmployeeId('');setMoreOpen(false)}}><span className="ema-sheet-ico"><Icon name="users"/></span><span className="ema-sheet-text"><b>Switch employee</b><small>Demo — choose another persona</small></span><Icon name="chevR" size={14}/></button></div></>}<ToastHost/></div></IPhoneFrame>}
ReactDOM.createRoot(document.getElementById('root')).render(<EmployeeMobileApp/>);
