// Compliance Pro — roc-comply-pro.jsx  v3.0
const { useState, useEffect, useRef, useCallback } = React;

const C = {
  navy:"#1e3a5f", blue:"#2563eb", indigo:"#4f46e5", sky:"#0ea5e9",
  green:"#16a34a", amber:"#d97706", red:"#dc2626", slate:"#64748b",
  light:"#f1f5f9", white:"#ffffff", border:"#e2e8f0", text:"#1e293b", muted:"#94a3b8",
};

const api = async (method, url, body) => {
  const opts = { method, headers:{"Content-Type":"application/json"} };
  if (body) opts.body = JSON.stringify(body);
  const r = await fetch(url, opts); return r.json();
};
const GET  = url      => api("GET",    url);
const POST = (url,b)  => api("POST",   url, b);
const PUT  = (url,b)  => api("PUT",    url, b);
const DEL  = url      => api("DELETE", url);

const fmtDate = d => { if (!d) return "—"; try { return new Date(d).toLocaleDateString("en-IN",{day:"2-digit",month:"short",year:"numeric"}); } catch { return d; } };
const daysUntil = d => { if (!d) return null; return Math.ceil((new Date(d)-new Date())/(864e5)); };
const statusColor = s => ({filed:C.green,pending:C.amber,overdue:C.red,na:C.muted}[s]||C.muted);
const statusBg    = s => ({filed:"#dcfce7",pending:"#fef9c3",overdue:"#fee2e2",na:"#f1f5f9"}[s]||"#f1f5f9");
const healthDot   = h => ({green:{bg:"#dcfce7",fg:C.green,label:"Compliant"},amber:{bg:"#fef9c3",fg:C.amber,label:"Attention"},red:{bg:"#fee2e2",fg:C.red,label:"At Risk"}}[h]||{bg:"#f1f5f9",fg:C.muted,label:"Unknown"});

const ENTITY_TYPE_OPTIONS = [
  {value:"private",label:"Private Limited Company"},{value:"public",label:"Public Limited Company"},
  {value:"opc",label:"One Person Company (OPC)"},{value:"section8",label:"Section 8 Company"},
  {value:"nidhi",label:"Nidhi Company"},{value:"producer",label:"Producer Company"},
  {value:"llp",label:"LLP (Limited Liability Partnership)"},
];
const DESIGNATIONS = ["Director","MD","WTD","CEO","CFO","CS","Designated Partner"];
const ROC_STATES = ["MCA - Delhi","MCA - Mumbai","MCA - Chennai","MCA - Kolkata","MCA - Ahmedabad","MCA - Hyderabad","MCA - Bengaluru","MCA - Pune","MCA - Jaipur","MCA - Chandigarh","Other"];
const MEETING_TYPES = ["BM","AGM","EGM","Others"];

// ── Shared UI ─────────────────────────────────────────────────────────────────
const Btn = ({onClick,children,variant="primary",small,disabled,style={}}) => {
  const base={display:"inline-flex",alignItems:"center",gap:6,padding:small?"6px 14px":"9px 20px",borderRadius:8,border:"none",cursor:disabled?"not-allowed":"pointer",fontWeight:600,fontSize:small?13:14,transition:"all .15s",opacity:disabled?.6:1,...style};
  const v={primary:{background:C.blue,color:"#fff"},danger:{background:C.red,color:"#fff"},success:{background:C.green,color:"#fff"},secondary:{background:C.light,color:C.text,border:`1px solid ${C.border}`},ghost:{background:"transparent",color:C.blue}};
  return <button style={{...base,...v[variant]}} onClick={onClick} disabled={disabled}>{children}</button>;
};
const Input = ({label,value,onChange,type="text",placeholder="",required,style={},helpText,disabled}) => (
  <div style={{display:"flex",flexDirection:"column",gap:4,...style}}>
    {label&&<label style={{fontSize:13,fontWeight:600,color:C.text}}>{label}{required&&<span style={{color:C.red}}> *</span>}</label>}
    <input type={type} value={value||""} placeholder={placeholder} disabled={disabled} onChange={e=>onChange(e.target.value)}
      style={{padding:"9px 12px",border:`1px solid ${C.border}`,borderRadius:8,fontSize:14,outline:"none",background:disabled?"#f8fafc":"#fff",color:C.text}}/>
    {helpText&&<span style={{fontSize:12,color:C.muted}}>{helpText}</span>}
  </div>
);
const Textarea = ({label,value,onChange,placeholder="",rows=3,style={}}) => (
  <div style={{display:"flex",flexDirection:"column",gap:4,...style}}>
    {label&&<label style={{fontSize:13,fontWeight:600,color:C.text}}>{label}</label>}
    <textarea value={value||""} placeholder={placeholder} rows={rows} onChange={e=>onChange(e.target.value)}
      style={{padding:"9px 12px",border:`1px solid ${C.border}`,borderRadius:8,fontSize:14,outline:"none",resize:"vertical",fontFamily:"inherit"}}/>
  </div>
);
const Select = ({label,value,onChange,options,required,style={}}) => (
  <div style={{display:"flex",flexDirection:"column",gap:4,...style}}>
    {label&&<label style={{fontSize:13,fontWeight:600,color:C.text}}>{label}{required&&<span style={{color:C.red}}> *</span>}</label>}
    <select value={value||""} onChange={e=>onChange(e.target.value)} style={{padding:"9px 12px",border:`1px solid ${C.border}`,borderRadius:8,fontSize:14,background:"#fff",color:C.text}}>
      <option value="">— Select —</option>
      {options.map(o=><option key={o.value||o} value={o.value||o}>{o.label||o}</option>)}
    </select>
  </div>
);
const Toggle = ({label,checked,onChange,helpText}) => (
  <div style={{display:"flex",alignItems:"flex-start",gap:12}}>
    <div onClick={()=>onChange(!checked)} style={{width:40,height:22,borderRadius:11,background:checked?C.blue:C.border,cursor:"pointer",position:"relative",flexShrink:0,marginTop:2,transition:"background .2s"}}>
      <div style={{position:"absolute",top:3,left:checked?20:2,width:16,height:16,borderRadius:"50%",background:"#fff",transition:"left .2s"}}/>
    </div>
    <div><div style={{fontSize:14,fontWeight:500,color:C.text}}>{label}</div>{helpText&&<div style={{fontSize:12,color:C.muted}}>{helpText}</div>}</div>
  </div>
);
const Card = ({children,style={}}) => <div style={{background:"#fff",borderRadius:12,border:`1px solid ${C.border}`,padding:24,...style}}>{children}</div>;
const Badge = ({label,color,bg,small}) => <span style={{display:"inline-block",padding:small?"2px 8px":"4px 10px",borderRadius:20,background:bg,color,fontSize:small?11:12,fontWeight:700,textTransform:"uppercase",letterSpacing:.5}}>{label}</span>;
const Modal = ({title,onClose,children,width=560}) => (
  <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,.5)",zIndex:1000,display:"flex",alignItems:"center",justifyContent:"center",padding:16}}>
    <div style={{background:"#fff",borderRadius:16,width:"100%",maxWidth:width,maxHeight:"92vh",overflowY:"auto"}}>
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"20px 24px",borderBottom:`1px solid ${C.border}`,position:"sticky",top:0,background:"#fff",zIndex:1}}>
        <h2 style={{fontSize:18,fontWeight:700,color:C.navy}}>{title}</h2>
        <button onClick={onClose} style={{background:"none",border:"none",fontSize:22,cursor:"pointer",color:C.muted}}>×</button>
      </div>
      <div style={{padding:24}}>{children}</div>
    </div>
  </div>
);
const Toast = ({msg,type="success",onClose}) => {
  useEffect(()=>{const t=setTimeout(onClose,4000);return()=>clearTimeout(t);},[]);
  return <div style={{position:"fixed",bottom:24,right:24,zIndex:2000,background:type==="error"?C.red:C.green,color:"#fff",padding:"12px 20px",borderRadius:12,fontWeight:600,fontSize:14,boxShadow:"0 4px 20px rgba(0,0,0,.2)",maxWidth:380}}>{type==="error"?"✕":"✓"} {msg}</div>;
};
const EmptyState = ({icon,title,subtitle,action}) => (
  <div style={{textAlign:"center",padding:"48px 24px"}}>
    <div style={{fontSize:48,marginBottom:12}}>{icon}</div>
    <h3 style={{fontSize:18,fontWeight:700,color:C.text,marginBottom:6}}>{title}</h3>
    <p style={{color:C.muted,fontSize:14,marginBottom:24}}>{subtitle}</p>
    {action}
  </div>
);
const StatCard = ({label,value,icon,color,sub,onClick}) => (
  <div onClick={onClick}
    onMouseEnter={e=>{if(onClick){e.currentTarget.style.transform="translateY(-2px)";e.currentTarget.style.boxShadow="0 6px 20px rgba(0,0,0,.1)";}}}
    onMouseLeave={e=>{if(onClick){e.currentTarget.style.transform="none";e.currentTarget.style.boxShadow="none";}}}
    style={{background:"#fff",borderRadius:12,border:`1px solid ${C.border}`,padding:"18px 20px",display:"flex",alignItems:"center",gap:16,cursor:onClick?"pointer":"default",transition:"transform .15s,box-shadow .15s"}}>
    <div style={{width:48,height:48,borderRadius:12,background:`${color}18`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:22}}>{icon}</div>
    <div>
      <div style={{fontSize:26,fontWeight:800,color}}>{value}</div>
      <div style={{fontSize:13,color:C.muted,fontWeight:500}}>{label}</div>
      {sub&&<div style={{fontSize:11,color:C.muted,marginTop:2}}>{sub}</div>}
      {onClick&&<div style={{fontSize:11,color,marginTop:3,fontWeight:600}}>Click to view →</div>}
    </div>
  </div>
);

// File reader helper
const readFileAsBase64 = file => new Promise((res,rej)=>{
  const r=new FileReader();
  r.onload=e=>res({name:file.name,data:e.target.result.split(",")[1],mime:file.type});
  r.onerror=rej;
  r.readAsDataURL(file);
});
const downloadFile = (data,name,mime) => {
  const bin=atob(data),arr=new Uint8Array(bin.length);
  for(let i=0;i<bin.length;i++)arr[i]=bin.charCodeAt(i);
  const url=URL.createObjectURL(new Blob([arr],{type:mime||"application/octet-stream"}));
  const a=document.createElement("a");a.href=url;a.download=name;a.click();URL.revokeObjectURL(url);
};

// ── Auth Screen ───────────────────────────────────────────────────────────────
const LoginScreen = ({onLogin}) => {
  const [screen,setScreen]=useState("login");
  const [error,setError]=useState(""); const [info,setInfo]=useState(""); const [loading,setLoading]=useState(false);
  const [email,setEmail]=useState(""); const [password,setPassword]=useState("");
  const [reg,setReg]=useState({entity_type:"",entity_name:"",entity_reg_number:"",director_name:"",email:"",password:"",confirm:""});
  const [fpEmail,setFpEmail]=useState(""); const [rpToken,setRpToken]=useState(""); const [rpPw,setRpPw]=useState(""); const [rpPw2,setRpPw2]=useState("");
  const sw=s=>{setError("");setInfo("");setScreen(s);};

  const handleLogin=async()=>{
    if(!email||!password){setError("Please enter email and password.");return;}
    setLoading(true);setError("");
    const res=await POST("/api/auth/login",{email,password});setLoading(false);
    if(res.ok){localStorage.setItem("rcp_user",JSON.stringify(res.user));onLogin(res.user);}
    else setError(res.error||"Login failed.");
  };
  const handleRegister=async()=>{
    if(!reg.entity_type){setError("Please select an Entity Type.");return;}
    if(!reg.entity_name){setError("Please enter the Name of the Entity.");return;}
    if(!reg.entity_reg_number){setError("Please enter the Entity Registration Number.");return;}
    if(!reg.email){setError("Please enter an Email Address.");return;}
    if(!reg.password){setError("Please enter a Password.");return;}
    if(reg.password!==reg.confirm){setError("Passwords do not match.");return;}
    if(reg.password.length<6){setError("Password must be at least 6 characters.");return;}
    setLoading(true);setError("");
    const res=await POST("/api/auth/register",{entity_type:reg.entity_type,entity_name:reg.entity_name,entity_reg_number:reg.entity_reg_number,director_name:reg.director_name,email:reg.email,password:reg.password});
    setLoading(false);
    if(res.ok){localStorage.setItem("rcp_user",JSON.stringify(res.user));onLogin(res.user);}
    else setError(res.error||"Registration failed.");
  };
  const handleForgot=async()=>{
    if(!fpEmail){setError("Please enter your registered email.");return;}
    setLoading(true);setError("");
    const res=await POST("/api/auth/forgot-password",{email:fpEmail});setLoading(false);
    if(res.ok){setInfo("Reset token sent to your email. Enter it below.");sw("reset");}
    else setError(res.error||"No account found with that email.");
  };
  const handleReset=async()=>{
    if(!rpToken||!rpPw){setError("Please fill all fields.");return;}
    if(rpPw!==rpPw2){setError("Passwords do not match.");return;}
    setLoading(true);setError("");
    const res=await POST("/api/auth/reset-password",{token:rpToken,password:rpPw});setLoading(false);
    if(res.ok){setInfo("Password reset successfully. Please sign in.");sw("login");}
    else setError(res.error||"Invalid or expired token.");
  };
  const R=k=>({value:reg[k],onChange:v=>setReg(p=>({...p,[k]:v}))});

  return (
    <div style={{minHeight:"100vh",background:`linear-gradient(135deg,${C.navy} 0%,#1e40af 100%)`,display:"flex",alignItems:"center",justifyContent:"center",padding:16}}>
      <div style={{width:"100%",maxWidth:screen==="register"?500:440}}>
        <div style={{textAlign:"center",marginBottom:28}}>
          <div style={{fontSize:42,marginBottom:8}}>⚖️</div>
          <h1 style={{color:"#fff",fontSize:28,fontWeight:800}}>Compliance Pro</h1>
          <p style={{color:"#93c5fd",fontSize:15,marginTop:6}}>Compliance Management Platform</p>
        </div>
        <Card style={{padding:32}}>
          {error&&<div style={{background:"#fee2e2",color:C.red,padding:"10px 14px",borderRadius:8,marginBottom:16,fontSize:14}}>{error}</div>}
          {info &&<div style={{background:"#dcfce7",color:C.green,padding:"10px 14px",borderRadius:8,marginBottom:16,fontSize:14}}>{info}</div>}

          {screen==="login"&&<>
            <h2 style={{fontSize:20,fontWeight:700,color:C.navy,marginBottom:20}}>Sign In</h2>
            <div style={{display:"flex",flexDirection:"column",gap:14}}>
              <Input label="Email Address" value={email} onChange={setEmail} type="email" placeholder="you@example.com" required/>
              <Input label="Password" value={password} onChange={setPassword} type="password" placeholder="••••••••" required/>
              <Btn onClick={handleLogin} disabled={loading} style={{width:"100%",justifyContent:"center",marginTop:4}}>{loading?"Signing in…":"Sign In →"}</Btn>
            </div>
            <div style={{display:"flex",justifyContent:"space-between",marginTop:18}}>
              <button onClick={()=>sw("register")} style={{background:"none",border:"none",color:C.blue,cursor:"pointer",fontSize:13,fontWeight:600}}>Create New Account</button>
              <button onClick={()=>sw("forgot")} style={{background:"none",border:"none",color:C.slate,cursor:"pointer",fontSize:13}}>Forgot Password?</button>
            </div>
          </>}

          {screen==="register"&&<>
            <h2 style={{fontSize:20,fontWeight:700,color:C.navy,marginBottom:6}}>Create Account</h2>
            <p style={{fontSize:13,color:C.muted,marginBottom:18}}>Register your company or LLP to get started.</p>
            <div style={{display:"flex",flexDirection:"column",gap:13}}>
              <Select label="Entity Type" required options={ENTITY_TYPE_OPTIONS} {...R("entity_type")}/>
              <Input label="Name of Entity" required placeholder="e.g. ABC Private Limited / XYZ LLP" {...R("entity_name")}/>
              <Input label="Entity Registration Number" required placeholder="CIN for Companies / LLPIN for LLPs" helpText="21-char CIN (e.g. U12345MH2020PTC000000) or LLPIN" {...R("entity_reg_number")}/>
              <Input label="Name of Director / Designated Partner" placeholder="Full name (optional)" {...R("director_name")}/>
              <Input label="Email Address" required type="email" placeholder="your@email.com" {...R("email")}/>
              <Input label="Password" required type="password" placeholder="Minimum 6 characters" {...R("password")}/>
              <Input label="Retype Password" required type="password" placeholder="Confirm your password" {...R("confirm")}/>
              <Btn onClick={handleRegister} disabled={loading} style={{width:"100%",justifyContent:"center",marginTop:4}}>{loading?"Creating Account…":"Create Account →"}</Btn>
            </div>
            <div style={{textAlign:"center",marginTop:16}}>
              <button onClick={()=>sw("login")} style={{background:"none",border:"none",color:C.blue,cursor:"pointer",fontSize:13,fontWeight:600}}>← Back to Sign In</button>
            </div>
          </>}

          {screen==="forgot"&&<>
            <h2 style={{fontSize:20,fontWeight:700,color:C.navy,marginBottom:8}}>Forgot Password</h2>
            <p style={{fontSize:13,color:C.muted,marginBottom:18}}>Enter your registered email — we'll send a reset token.</p>
            <div style={{display:"flex",flexDirection:"column",gap:14}}>
              <Input label="Registered Email" required type="email" value={fpEmail} onChange={setFpEmail} placeholder="your@email.com"/>
              <Btn onClick={handleForgot} disabled={loading} style={{width:"100%",justifyContent:"center"}}>{loading?"Sending…":"Send Reset Token"}</Btn>
            </div>
            <div style={{display:"flex",justifyContent:"space-between",marginTop:16}}>
              <button onClick={()=>sw("login")} style={{background:"none",border:"none",color:C.blue,cursor:"pointer",fontSize:13,fontWeight:600}}>← Back to Sign In</button>
              <button onClick={()=>sw("reset")} style={{background:"none",border:"none",color:C.slate,cursor:"pointer",fontSize:13}}>I have a token</button>
            </div>
          </>}

          {screen==="reset"&&<>
            <h2 style={{fontSize:20,fontWeight:700,color:C.navy,marginBottom:8}}>Reset Password</h2>
            <p style={{fontSize:13,color:C.muted,marginBottom:18}}>Enter the token from your email and set a new password.</p>
            <div style={{display:"flex",flexDirection:"column",gap:14}}>
              <Input label="Reset Token" required value={rpToken} onChange={setRpToken} placeholder="Paste token from email"/>
              <Input label="New Password" required type="password" value={rpPw} onChange={setRpPw} placeholder="Minimum 6 characters"/>
              <Input label="Confirm New Password" required type="password" value={rpPw2} onChange={setRpPw2} placeholder="Retype new password"/>
              <Btn onClick={handleReset} disabled={loading} style={{width:"100%",justifyContent:"center"}}>{loading?"Resetting…":"Reset Password"}</Btn>
            </div>
            <div style={{textAlign:"center",marginTop:16}}>
              <button onClick={()=>sw("login")} style={{background:"none",border:"none",color:C.blue,cursor:"pointer",fontSize:13,fontWeight:600}}>← Back to Sign In</button>
            </div>
          </>}
        </Card>
      </div>
    </div>
  );
};

// ── Sidebar ───────────────────────────────────────────────────────────────────
const NAV = [
  {id:"dashboard",  icon:"📊",label:"Dashboard"},
  {id:"entities",   icon:"🏢",label:"Entities"},
  {id:"calendar",   icon:"📅",label:"Compliance Calendar"},
  {id:"meetings",   icon:"📋",label:"Board Meetings"},
  {id:"vault",      icon:"🔐",label:"Password Vault"},
  {id:"audit",      icon:"📜",label:"Audit Tracker"},
  {id:"notices",    icon:"📬",label:"Notice Tracker"},
  {id:"library",    icon:"📚",label:"Library"},
  {id:"files",      icon:"🗂️", label:"File Management"},
  {id:"admin",      icon:"⚙️",label:"Admin",adminOnly:true},
];
const Sidebar = ({page,setPage,user,onLogout,collapsed,setCollapsed}) => (
  <div style={{width:collapsed?64:240,flexShrink:0,background:C.navy,display:"flex",flexDirection:"column",transition:"width .2s",minHeight:"100vh"}}>
    <div style={{padding:collapsed?"18px 0":"18px 20px",display:"flex",alignItems:"center",justifyContent:collapsed?"center":"space-between",borderBottom:"1px solid rgba(255,255,255,.1)"}}>
      {!collapsed&&<span style={{color:"#fff",fontWeight:800,fontSize:15}}>⚖️ Compliance Pro</span>}
      <button onClick={()=>setCollapsed(!collapsed)} style={{background:"none",border:"none",cursor:"pointer",color:"#94a3b8",fontSize:18,padding:4}}>{collapsed?"→":"←"}</button>
    </div>
    <nav style={{flex:1,padding:"12px 0"}}>
      {NAV.filter(n=>!n.adminOnly||user.role==="admin").map(n=>{
        const active=page===n.id;
        return <button key={n.id} onClick={()=>setPage(n.id)} style={{width:"100%",display:"flex",alignItems:"center",gap:12,padding:collapsed?"12px 0":"12px 20px",justifyContent:collapsed?"center":"flex-start",background:active?"rgba(255,255,255,.12)":"none",border:"none",cursor:"pointer",color:active?"#fff":"#94a3b8",fontWeight:active?700:500,fontSize:14,borderLeft:active?`3px solid ${C.sky}`:"3px solid transparent"}}>
          <span style={{fontSize:18}}>{n.icon}</span>
          {!collapsed&&n.label}
        </button>;
      })}
    </nav>
    <div style={{padding:collapsed?"12px 0":"12px 20px",borderTop:"1px solid rgba(255,255,255,.1)"}}>
      {!collapsed&&<div style={{marginBottom:10}}><div style={{color:"#fff",fontSize:13,fontWeight:600}}>{user.name}</div><div style={{color:"#94a3b8",fontSize:11}}>{user.role==="admin"?"Administrator":user.entity_name||"User"}</div></div>}
      <button onClick={onLogout} style={{width:"100%",padding:collapsed?"8px 0":"8px 12px",background:"rgba(255,255,255,.08)",border:"none",borderRadius:8,cursor:"pointer",color:"#94a3b8",fontSize:13,display:"flex",alignItems:"center",gap:8,justifyContent:collapsed?"center":"flex-start"}}>🚪{!collapsed&&" Sign Out"}</button>
    </div>
  </div>
);

// ── Dashboard ─────────────────────────────────────────────────────────────────
const Dashboard = ({user,onNavigate}) => {
  const [data,setData]=useState(null);
  useEffect(()=>{GET("/api/dashboard").then(r=>{if(r.ok)setData(r);});},[]);
  if (!data) return <div style={{padding:40,textAlign:"center",color:C.muted}}>Loading dashboard…</div>;
  const {totals,entities,fy}=data;
  return (
    <div style={{padding:32}}>
      <div style={{marginBottom:28}}>
        <h1 style={{fontSize:24,fontWeight:800,color:C.navy}}>Compliance Dashboard</h1>
        <p style={{color:C.muted,marginTop:4}}>Financial Year {fy} · {new Date().toLocaleDateString("en-IN",{weekday:"long",day:"2-digit",month:"long",year:"numeric"})}</p>
      </div>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(180px,1fr))",gap:16,marginBottom:32}}>
        <StatCard label="Total Entities"  value={totals.entities}   icon="🏢" color={C.navy}   onClick={()=>onNavigate("entities")}/>
        <StatCard label="Overdue Filings" value={totals.overdue}    icon="⚠️"  color={C.red}    onClick={()=>onNavigate("calendar")} sub="Immediate action required"/>
        <StatCard label="Due in 30 Days"  value={totals.upcoming30} icon="📅" color={C.amber}  onClick={()=>onNavigate("calendar")}/>
        <StatCard label="Filed This FY"   value={totals.filed}      icon="✅" color={C.green}  onClick={()=>onNavigate("calendar")}/>
        <StatCard label="Pending"         value={totals.pending}    icon="⏳" color={C.indigo} onClick={()=>onNavigate("calendar")}/>
      </div>
      <Card>
        <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:20}}>
          <h2 style={{fontSize:17,fontWeight:700,color:C.navy}}>Entity Portfolio — Compliance Health</h2>
          <Btn small variant="secondary" onClick={()=>onNavigate("entities")}>+ Add Entity</Btn>
        </div>
        {entities.length===0?<EmptyState icon="🏢" title="No entities yet" subtitle="Add your first company or LLP." action={<Btn onClick={()=>onNavigate("entities")}>Add Entity</Btn>}/>:(
          <div style={{overflowX:"auto"}}>
            <table style={{width:"100%",borderCollapse:"collapse",fontSize:14}}>
              <thead><tr style={{background:C.light}}>{["Entity","Type","CIN/LLPIN","State","Health","Filed","Pending","Overdue",""].map(h=><th key={h} style={{padding:"10px 12px",textAlign:"left",fontSize:12,fontWeight:700,color:C.slate,borderBottom:`1px solid ${C.border}`}}>{h}</th>)}</tr></thead>
              <tbody>{entities.map(e=>{const hd=healthDot(e.health);return(
                <tr key={e.id} style={{borderBottom:`1px solid ${C.border}`,cursor:"pointer"}} onClick={()=>onNavigate("entities",e.id)}>
                  <td style={{padding:"12px"}}><strong>{e.name}</strong></td>
                  <td style={{padding:"12px",color:C.muted,textTransform:"capitalize"}}>{e.subType||e.type}</td>
                  <td style={{padding:"12px",color:C.muted,fontFamily:"monospace",fontSize:12}}>{e.cin||"—"}</td>
                  <td style={{padding:"12px",color:C.muted}}>{e.state||"—"}</td>
                  <td style={{padding:"12px"}}><span style={{display:"inline-flex",alignItems:"center",gap:6,background:hd.bg,color:hd.fg,padding:"4px 10px",borderRadius:20,fontSize:12,fontWeight:700}}><span style={{width:7,height:7,borderRadius:"50%",background:hd.fg}}/>{hd.label}</span></td>
                  <td style={{padding:"12px",color:C.green,fontWeight:700}}>{e.filed}</td>
                  <td style={{padding:"12px",color:C.amber,fontWeight:700}}>{e.pending}</td>
                  <td style={{padding:"12px",color:C.red,fontWeight:700}}>{e.overdue}</td>
                  <td style={{padding:"12px"}}><Btn small variant="ghost" onClick={ev=>{ev.stopPropagation();onNavigate("calendar",e.id);}}>View →</Btn></td>
                </tr>);})}</tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
};

// ── Entity Form Modal ─────────────────────────────────────────────────────────
const EntityFormModal = ({entity,onClose,onSaved,user}) => {
  const isEdit=!!entity;
  const [form,setForm]=useState({name:"",sub_type:"private",cin:"",llpin:"",date_of_incorporation:"",registered_address:"",state:"",roc_jurisdiction:"",paid_up_capital:"",authorised_capital:"",auditor_name:"",auditor_firm_reg:"",auditor_appointed_date:"",accepts_deposits:false,is_msme_applicable:false,is_cost_audit:false,is_sbo_applicable:false,...(entity||{}),accepts_deposits:!!entity?.accepts_deposits,is_msme_applicable:!!entity?.is_msme_applicable,is_cost_audit:!!entity?.is_cost_audit,is_sbo_applicable:!!entity?.is_sbo_applicable});
  const [saving,setSaving]=useState(false);const [error,setError]=useState("");
  const isLLP=form.sub_type==="llp";
  const save=async()=>{
    if(!form.name||!form.sub_type){setError("Name and entity type required.");return;}
    setSaving(true);setError("");
    const payload={...form,entity_type:isLLP?"llp":"company",created_by:user?.email||""};
    const res=isEdit?await PUT(`/api/entities/${entity.id}`,payload):await POST("/api/entities",payload);
    setSaving(false);if(res.ok)onSaved(res.entity);else setError(res.error||"Failed.");
  };
  const F=k=>({value:form[k],onChange:v=>setForm(p=>({...p,[k]:v}))});
  return (
    <Modal title={isEdit?"Edit Entity":"Add New Entity"} onClose={onClose} width={700}>
      {error&&<div style={{background:"#fee2e2",color:C.red,padding:10,borderRadius:8,marginBottom:16,fontSize:14}}>{error}</div>}
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16}}>
        <Select label="Entity Type" required options={ENTITY_TYPE_OPTIONS} {...F("sub_type")} style={{gridColumn:"1/-1"}}/>
        <Input label="Entity Name" required style={{gridColumn:"1/-1"}} {...F("name")}/>
        {isLLP?<Input label="LLPIN" placeholder="AAA-0000" {...F("llpin")}/>:<Input label="CIN" placeholder="U12345MH2020PTC000000" {...F("cin")}/>}
        <Input label="Date of Incorporation" type="date" {...F("date_of_incorporation")}/>
        <Select label="RoC Jurisdiction" options={ROC_STATES.map(s=>({label:s,value:s}))} {...F("roc_jurisdiction")}/>
        <Input label="State" placeholder="Maharashtra" {...F("state")}/>
        <Input label="Registered Address" style={{gridColumn:"1/-1"}} {...F("registered_address")}/>
        {/* AGM date removed — picked from Board Meeting Tracker */}
        <Input label="Authorised Capital (₹)" type="number" {...F("authorised_capital")}/>
        <Input label="Paid-up Capital (₹)" type="number" {...F("paid_up_capital")}/>
        <Input label="Auditor / Firm Name" {...F("auditor_name")}/>
        <Input label="Auditor Appointment Date" type="date" {...F("auditor_appointed_date")}/>
      </div>
      <div style={{marginTop:20,display:"flex",flexDirection:"column",gap:12}}>
        <h4 style={{fontSize:13,fontWeight:700,color:C.slate}}>Compliance Flags</h4>
        <Toggle label="Accepts Deposits (DPT-3 applicable)"  checked={form.accepts_deposits}   onChange={v=>setForm(p=>({...p,accepts_deposits:v}))}/>
        <Toggle label="MSME Payments Applicable (MSME-1)"    checked={form.is_msme_applicable} onChange={v=>setForm(p=>({...p,is_msme_applicable:v}))}/>
        <Toggle label="Cost Audit Applicable (CRA-4)"        checked={form.is_cost_audit}      onChange={v=>setForm(p=>({...p,is_cost_audit:v}))}/>
        <Toggle label="SBO Declaration Applicable (BEN-2)"   checked={form.is_sbo_applicable}  onChange={v=>setForm(p=>({...p,is_sbo_applicable:v}))}/>
      </div>
      <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
        <Btn variant="secondary" onClick={onClose}>Cancel</Btn>
        <Btn onClick={save} disabled={saving}>{saving?"Saving…":isEdit?"Save Changes":"Add Entity"}</Btn>
      </div>
    </Modal>
  );
};

// ── Director Form Modal ───────────────────────────────────────────────────────
const DirectorFormModal = ({entityId,director,onClose,onSaved}) => {
  const isEdit=!!director;
  const [form,setForm]=useState({name:"",din:"",pan:"",nationality:"Indian",date_of_appointment:"",date_of_cessation:"",designation:"Director",is_kmp:false,email:"",phone:"",dsc_expiry:"",active:1,...(director||{}),is_kmp:!!director?.is_kmp});
  const [saving,setSaving]=useState(false);
  const save=async()=>{setSaving(true);const res=isEdit?await PUT(`/api/directors/${director.id}`,form):await POST(`/api/entities/${entityId}/directors`,form);setSaving(false);if(res.ok)onSaved();};
  const F=k=>({value:form[k],onChange:v=>setForm(p=>({...p,[k]:v}))});
  return (
    <Modal title={isEdit?"Edit Director":"Add Director / Partner"} onClose={onClose} width={620}>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16}}>
        <Input label="Full Name" required style={{gridColumn:"1/-1"}} {...F("name")}/>
        <Input label="DIN" {...F("din")}/><Input label="PAN" {...F("pan")}/>
        <Select label="Designation" options={DESIGNATIONS.map(d=>({label:d,value:d}))} {...F("designation")}/>
        <Input label="Date of Appointment" type="date" {...F("date_of_appointment")}/>
        <Input label="Date of Cessation" type="date" {...F("date_of_cessation")}/>
        <Input label="Email" type="email" {...F("email")}/><Input label="Phone" {...F("phone")}/>
        <Input label="DSC Expiry Date" type="date" {...F("dsc_expiry")}/>
        <Select label="Nationality" options={[{label:"Indian",value:"Indian"},{label:"Foreign National",value:"Foreign"}]} {...F("nationality")}/>
      </div>
      <div style={{marginTop:16}}><Toggle label="Key Managerial Personnel (KMP)" checked={form.is_kmp} onChange={v=>setForm(p=>({...p,is_kmp:v}))}/></div>
      <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
        <Btn variant="secondary" onClick={onClose}>Cancel</Btn>
        <Btn onClick={save} disabled={saving}>{saving?"Saving…":isEdit?"Save":"Add"}</Btn>
      </div>
    </Modal>
  );
};

// ── Entities Page ─────────────────────────────────────────────────────────────
const EntitiesPage = ({user,selectedId}) => {
  const [entities,setEntities]=useState([]);
  const [selected,setSelected]=useState(null);
  const [directors,setDirectors]=useState([]);
  const [showForm,setShowForm]=useState(false);
  const [editEntity,setEditEntity]=useState(null);
  const [showDirForm,setShowDirForm]=useState(false);
  const [editDir,setEditDir]=useState(null);
  const [toast,setToast]=useState(null);
  const [confirmDel,setConfirmDel]=useState(null);
  const [tab,setTab]=useState("info");
  const [search,setSearch]=useState("");

  const loadEntities=useCallback(async()=>{
    const r=await GET("/api/entities");
    if(r.ok){setEntities(r.entities);if(selectedId){const f=r.entities.find(e=>e.id===selectedId);if(f)selectEntity(f);}}
  },[selectedId]);
  useEffect(()=>{loadEntities();},[loadEntities]);

  const selectEntity=async e=>{setSelected(e);setTab("info");const r=await GET(`/api/entities/${e.id}`);if(r.ok){setSelected(r.entity);setDirectors(r.directors||[]);}};

  const filtered=entities.filter(e=>!search||e.name.toLowerCase().includes(search.toLowerCase())||(e.cin||"").toLowerCase().includes(search.toLowerCase()));
  const TabBtn=({id,label})=><button onClick={()=>setTab(id)} style={{padding:"8px 18px",border:"none",borderBottom:tab===id?`2px solid ${C.blue}`:"2px solid transparent",background:"none",cursor:"pointer",fontWeight:tab===id?700:500,color:tab===id?C.blue:C.muted,fontSize:14}}>{label}</button>;

  return (
    <div style={{display:"flex",height:"100%",minHeight:"100vh"}}>
      <div style={{width:300,flexShrink:0,borderRight:`1px solid ${C.border}`,background:"#fff",overflowY:"auto",display:"flex",flexDirection:"column"}}>
        <div style={{padding:"16px 16px 8px",borderBottom:`1px solid ${C.border}`}}>
          <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
            <h2 style={{fontSize:15,fontWeight:700,color:C.navy}}>Entities ({entities.length})</h2>
            <Btn small onClick={()=>{setEditEntity(null);setShowForm(true);}}>+ Add</Btn>
          </div>
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search entities…" style={{width:"100%",padding:"7px 10px",border:`1px solid ${C.border}`,borderRadius:8,fontSize:13,outline:"none",boxSizing:"border-box"}}/>
        </div>
        <div style={{overflowY:"auto",flex:1}}>
          {filtered.length===0?<div style={{padding:24,textAlign:"center",color:C.muted,fontSize:14}}>No entities found.</div>:
            filtered.map(e=>{const isActive=selected?.id===e.id;return(
              <div key={e.id} onClick={()=>selectEntity(e)} style={{padding:"14px 16px",cursor:"pointer",background:isActive?`${C.blue}10`:"transparent",borderLeft:isActive?`3px solid ${C.blue}`:"3px solid transparent",borderBottom:`1px solid ${C.border}`}}>
                <div style={{fontWeight:700,fontSize:14,color:C.text}}>{e.name}</div>
                <div style={{fontSize:12,color:C.muted,marginTop:2}}>{e.cin||e.llpin||"No CIN/LLPIN"}</div>
                <div style={{marginTop:6}}><span style={{fontSize:11,background:`${C.navy}15`,color:C.navy,padding:"2px 8px",borderRadius:10,fontWeight:600,textTransform:"capitalize"}}>{e.sub_type||e.entity_type}</span></div>
              </div>);
            })
          }
        </div>
      </div>
      <div style={{flex:1,overflowY:"auto",padding:28}}>
        {!selected?<EmptyState icon="🏢" title="Select an entity" subtitle="Choose an entity from the list to view its details and directors."/>:(
          <>
            <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",marginBottom:20}}>
              <div>
                <h2 style={{fontSize:22,fontWeight:800,color:C.navy}}>{selected.name}</h2>
                <p style={{color:C.muted,fontSize:14,marginTop:4}}>{selected.cin||selected.llpin||"—"} · {selected.state||"—"} · {selected.roc_jurisdiction||"—"}</p>
              </div>
              <div style={{display:"flex",gap:10}}>
                <Btn small variant="secondary" onClick={()=>{setEditEntity(selected);setShowForm(true);}}>✏️ Edit</Btn>
                <Btn small variant="danger" onClick={()=>setConfirmDel(selected.id)}>🗑 Delete</Btn>
              </div>
            </div>
            <div style={{display:"flex",borderBottom:`1px solid ${C.border}`,marginBottom:24}}>
              <TabBtn id="info" label="Info"/><TabBtn id="directors" label={`Directors (${directors.length})`}/>
            </div>
            {tab==="info"&&(
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:24}}>
                <Card>
                  <h3 style={{fontSize:13,fontWeight:700,color:C.slate,marginBottom:16,textTransform:"uppercase",letterSpacing:.5}}>Entity Details</h3>
                  {[["Entity Type",(selected.sub_type||selected.entity_type||"").toUpperCase()],["Incorporated",fmtDate(selected.date_of_incorporation)],["Address",selected.registered_address||"—"],["AGM Date",fmtDate(selected.agm_date)]].map(([k,v])=>(
                    <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"8px 0",borderBottom:`1px solid ${C.border}`,fontSize:14}}><span style={{color:C.muted}}>{k}</span><span style={{fontWeight:500,maxWidth:200,textAlign:"right"}}>{v}</span></div>
                  ))}
                </Card>
                <Card>
                  <h3 style={{fontSize:13,fontWeight:700,color:C.slate,marginBottom:16,textTransform:"uppercase",letterSpacing:.5}}>Capital & Auditor</h3>
                  {[["Auth. Capital",selected.authorised_capital?`₹ ${Number(selected.authorised_capital).toLocaleString("en-IN")}`:"—"],["Paid-up Capital",selected.paid_up_capital?`₹ ${Number(selected.paid_up_capital).toLocaleString("en-IN")}`:"—"],["Auditor",selected.auditor_name||"—"],["Auditor Appointed",fmtDate(selected.auditor_appointed_date)]].map(([k,v])=>(
                    <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"8px 0",borderBottom:`1px solid ${C.border}`,fontSize:14}}><span style={{color:C.muted}}>{k}</span><span style={{fontWeight:500}}>{v}</span></div>
                  ))}
                </Card>
              </div>
            )}
            {tab==="directors"&&(
              <div>
                <div style={{display:"flex",justifyContent:"flex-end",marginBottom:16}}>
                  <Btn small onClick={()=>{setEditDir(null);setShowDirForm(true);}}>+ Add Director</Btn>
                </div>
                {directors.length===0?<EmptyState icon="👤" title="No directors" subtitle="Add directors or designated partners for this entity."/>:
                  <div style={{display:"grid",gap:12}}>{directors.map(d=>(
                    <Card key={d.id} style={{padding:"16px 20px",display:"flex",alignItems:"center",justifyContent:"space-between"}}>
                      <div style={{display:"flex",alignItems:"center",gap:16}}>
                        <div style={{width:44,height:44,borderRadius:"50%",background:`${C.navy}15`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:C.navy}}>{d.name?.[0]?.toUpperCase()}</div>
                        <div>
                          <div style={{fontWeight:700}}>{d.name}</div>
                          <div style={{fontSize:12,color:C.muted}}>{d.designation}{d.is_kmp?" · KMP":""} · DIN: {d.din||"—"}</div>
                          <div style={{fontSize:12,color:C.muted}}>Appointed: {fmtDate(d.date_of_appointment)}{d.dsc_expiry?` · DSC: ${fmtDate(d.dsc_expiry)}`:""}</div>
                        </div>
                      </div>
                      <div style={{display:"flex",gap:8}}>
                        <Btn small variant="secondary" onClick={()=>{setEditDir(d);setShowDirForm(true);}}>Edit</Btn>
                        <Btn small variant="danger" onClick={async()=>{await DEL(`/api/directors/${d.id}`);const r=await GET(`/api/entities/${selected.id}`);if(r.ok)setDirectors(r.directors||[]);}}>Remove</Btn>
                      </div>
                    </Card>
                  ))}</div>
                }
              </div>
            )}
          </>
        )}
      </div>
      {showForm&&<EntityFormModal entity={editEntity} user={user} onClose={()=>setShowForm(false)} onSaved={async()=>{setShowForm(false);await loadEntities();setToast({msg:editEntity?"Entity updated":"Entity added",type:"success"});}}/>}
      {showDirForm&&selected&&<DirectorFormModal entityId={selected.id} director={editDir} onClose={()=>setShowDirForm(false)} onSaved={async()=>{setShowDirForm(false);const r=await GET(`/api/entities/${selected.id}`);if(r.ok)setDirectors(r.directors||[]);setToast({msg:editDir?"Director updated":"Director added",type:"success"});}}/>}
      {confirmDel&&<Modal title="Delete Entity" onClose={()=>setConfirmDel(null)} width={400}><p style={{marginBottom:24,color:C.text}}>Are you sure? All compliance records for this entity will also be deleted.</p><div style={{display:"flex",gap:12,justifyContent:"flex-end"}}><Btn variant="secondary" onClick={()=>setConfirmDel(null)}>Cancel</Btn><Btn variant="danger" onClick={async()=>{await DEL(`/api/entities/${confirmDel}`);setSelected(null);setConfirmDel(null);loadEntities();setToast({msg:"Entity deleted",type:"success"});}}>Delete</Btn></div></Modal>}
      {toast&&<Toast msg={toast.msg} type={toast.type} onClose={()=>setToast(null)}/>}
    </div>
  );
};

// ── Mark Filed Modal (Enhanced) ───────────────────────────────────────────────
const MarkFiledModal = ({item,entityId,fy,user,onClose,onSaved}) => {
  const [form,setForm]=useState({
    status: item.status==="na"?"na":"filed",
    filed_date: item.filedDate||new Date().toISOString().split("T")[0],
    srn: item.srn||"",
    professional_id: item.professionalId||"",
    comments: item.comments||"",
    not_applicable: item.notApplicable||item.status==="na",
    due_date: item.dueDate||"",
  });
  const [att1,setAtt1]=useState(null);
  const [att2,setAtt2]=useState(null);
  const [saving,setSaving]=useState(false);
  const f1Ref=useRef(),f2Ref=useRef();

  // Try to auto-fill professional ID from vault
  useEffect(()=>{
    GET("/api/vault?category=professional").then(r=>{
      if(r.ok&&r.entries.length>0&&!form.professional_id){
        setForm(p=>({...p,professional_id:r.entries[0].username||""}));
      }
    });
  },[]);

  const handleFile=async(e,num)=>{
    const file=e.target.files[0]; if(!file)return;
    const result=await readFileAsBase64(file);
    if(num===1)setAtt1(result); else setAtt2(result);
  };

  const save=async()=>{
    setSaving(true);
    const payload={
      entity_id:parseInt(entityId), item_id:item.id, fy_year:fy,
      due_date:form.due_date, status:form.not_applicable?"na":"filed",
      filed_date:form.not_applicable?"":form.filed_date,
      srn:form.not_applicable?"":form.srn,
      filed_by:user.email, professional_id:form.professional_id,
      comments:form.comments, not_applicable:form.not_applicable?1:0,
      attachment1_name:att1?.name||(item.attachment1Name||""),
      attachment1_data:att1?.data||"",
      attachment2_name:att2?.name||(item.attachment2Name||""),
      attachment2_data:att2?.data||"",
    };
    await POST("/api/compliance-status",payload);
    setSaving(false);onSaved();
  };

  const F=k=>({value:form[k],onChange:v=>setForm(p=>({...p,[k]:v}))});

  return (
    <Modal title={`Update Status — ${item.formName}`} onClose={onClose} width={580}>
      <div style={{background:C.light,borderRadius:8,padding:"10px 14px",marginBottom:20,fontSize:13,color:C.slate}}>
        <strong>{item.formName}</strong> — {item.purpose}<br/>
        {item.dueDate&&<span>Due: {fmtDate(item.dueDate)}</span>}
      </div>

      {/* Not Applicable checkbox */}
      <div style={{background:"#fff7ed",border:"1px solid #fed7aa",borderRadius:8,padding:"12px 16px",marginBottom:20}}>
        <label style={{display:"flex",alignItems:"center",gap:10,cursor:"pointer",fontSize:14,fontWeight:600,color:"#9a3412"}}>
          <input type="checkbox" checked={form.not_applicable} onChange={e=>setForm(p=>({...p,not_applicable:e.target.checked}))} style={{width:16,height:16,cursor:"pointer"}}/>
          Mark as Not Applicable (N/A)
        </label>
        {form.not_applicable&&<p style={{fontSize:12,color:C.muted,marginTop:6,marginLeft:26}}>SRN and filing details will be cleared — only comments will be saved.</p>}
      </div>

      <div style={{display:"flex",flexDirection:"column",gap:14,opacity:form.not_applicable?.5:1,pointerEvents:form.not_applicable?"none":"auto"}}>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
          <Input label="Date of Filing" type="date" {...F("filed_date")}/>
          <Input label="SRN (Service Request Number)" placeholder="e.g. F12345678" {...F("srn")}/>
        </div>
        <Input label="Professional ID (CA/CS used for filing)" placeholder="Auto-filled from vault if available" {...F("professional_id")} helpText="This is the login ID of the professional used to file on MCA portal"/>
        <Textarea label="Comments" placeholder="Any relevant notes about this filing…" rows={3} {...F("comments")}/>

        {/* Attachments */}
        <div>
          <h4 style={{fontSize:13,fontWeight:700,color:C.text,marginBottom:10}}>Attachments (optional — max 2 files)</h4>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
            <div>
              <label style={{fontSize:13,fontWeight:600,color:C.text,display:"block",marginBottom:6}}>Attachment 1 — Form</label>
              <input ref={f1Ref} type="file" onChange={e=>handleFile(e,1)} accept=".pdf,.jpg,.png,.doc,.docx" style={{width:"100%",padding:"6px",border:`1px solid ${C.border}`,borderRadius:8,fontSize:13}}/>
              {(att1||item.attachment1Name)&&<div style={{fontSize:12,color:C.green,marginTop:4}}>✓ {att1?.name||item.attachment1Name}</div>}
            </div>
            <div>
              <label style={{fontSize:13,fontWeight:600,color:C.text,display:"block",marginBottom:6}}>Attachment 2 — Payment Challan</label>
              <input ref={f2Ref} type="file" onChange={e=>handleFile(e,2)} accept=".pdf,.jpg,.png,.doc,.docx" style={{width:"100%",padding:"6px",border:`1px solid ${C.border}`,borderRadius:8,fontSize:13}}/>
              {(att2||item.attachment2Name)&&<div style={{fontSize:12,color:C.green,marginTop:4}}>✓ {att2?.name||item.attachment2Name}</div>}
            </div>
          </div>
        </div>
      </div>

      {form.not_applicable&&<div style={{marginTop:14}}><Textarea label="Comments (optional)" placeholder="Reason why not applicable…" rows={2} {...F("comments")}/></div>}

      <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
        <Btn variant="secondary" onClick={onClose}>Cancel</Btn>
        <Btn variant={form.not_applicable?"secondary":"success"} onClick={save} disabled={saving}>
          {saving?"Saving…":form.not_applicable?"Save as N/A":"✓ Mark as Filed"}
        </Btn>
      </div>
    </Modal>
  );
};

// ── Compliance Calendar Page ───────────────────────────────────────────────────
const ComplianceCalendarPage = ({user,selectedEntityId}) => {
  const [entities,setEntities]=useState([]);
  const [masterItems,setMasterItems]=useState([]);
  const [entityId,setEntityId]=useState(selectedEntityId||"");
  const fyOpts=(()=>{const now=new Date(),m=now.getMonth()+1,y=now.getFullYear(),b=m>=4?y:y-1;return[b-1,b,b+1].map(x=>`${x}-${String(x+1).slice(2)}`);})();
  const [fy,setFy]=useState(fyOpts[1]);
  const [items,setItems]=useState([]);
  const [customItems,setCustomItems]=useState([]);
  const [loading,setLoading]=useState(false);
  const [filter,setFilter]=useState("all");
  const [markModal,setMarkModal]=useState(null);
  const [showAddMaster,setShowAddMaster]=useState(false);
  const [editMaster,setEditMaster]=useState(null);
  const [toast,setToast]=useState(null);
  const [showCustom,setShowCustom]=useState(false);
  const [customForm,setCustomForm]=useState({title:"",description:"",due_date:""});

  useEffect(()=>{
    GET("/api/entities").then(r=>{if(r.ok){setEntities(r.entities);if(selectedEntityId)setEntityId(String(selectedEntityId));}});
    GET("/api/compliance-master").then(r=>{if(r.ok)setMasterItems(r.items);});
  },[]);

  const reload=useCallback(()=>{
    if(!entityId||!fy)return;
    setLoading(true);
    GET(`/api/entities/${entityId}/compliance-calendar?fy=${fy}`).then(r=>{if(r.ok){setItems(r.items);setCustomItems(r.customItems||[]);}setLoading(false);});
  },[entityId,fy]);

  useEffect(()=>{reload();},[reload]);

  const restore=async item=>{await POST("/api/compliance-status/restore",{entity_id:parseInt(entityId),item_id:item.id,fy_year:fy});reload();setToast({msg:"Restored to pending",type:"success"});};
  const penaltyDays=item=>{if(!item.dueDate||item.status==="filed"||item.status==="na")return 0;const today=new Date(),due=new Date(item.dueDate);if(due>=today)return 0;return Math.ceil((today-due)/864e5);};
  const statusCounts=items.reduce((a,i)=>{a[i.status]=(a[i.status]||0)+1;return a;},{});
  const filtered=items.filter(i=>filter==="all"||i.status===filter);

  const downloadAttachment=async(entityId,itemId,fy,num)=>{
    const r=await GET(`/api/compliance-status/${entityId}/${itemId}/${fy}/attachment/${num}`);
    if(r.ok&&r.data)downloadFile(r.data,r.filename,"application/octet-stream");
  };

  return (
    <div style={{display:"flex",height:"100%",minHeight:"100vh"}}>
      {/* Left panel — compliance master list */}
      <div style={{width:280,flexShrink:0,borderRight:`1px solid ${C.border}`,background:"#fff",overflowY:"auto",display:"flex",flexDirection:"column"}}>
        <div style={{padding:"16px 16px 12px",borderBottom:`1px solid ${C.border}`,background:C.navy}}>
          <h3 style={{color:"#fff",fontSize:14,fontWeight:700,margin:"0 0 4px"}}>Annual Compliance Items</h3>
          <p style={{color:"#94c5f7",fontSize:11,margin:0}}>Master list — auto-populates for all entities</p>
        </div>
        <div style={{padding:12}}>
          <Btn small style={{width:"100%",justifyContent:"center",marginBottom:8}} onClick={()=>{setEditMaster(null);setShowAddMaster(true);}}>+ Add Item</Btn>
        </div>
        {["company","llp"].map(track=>(
          <div key={track}>
            <div style={{padding:"6px 16px",background:C.light,fontSize:11,fontWeight:700,color:C.slate,textTransform:"uppercase",letterSpacing:.5}}>
              {track==="company"?"Companies":"LLPs"}
            </div>
            {masterItems.filter(m=>m.track===track||m.track==="both").map(m=>(
              <div key={m.id} style={{padding:"10px 16px",borderBottom:`1px solid ${C.border}`,display:"flex",alignItems:"center",justifyContent:"space-between",opacity:m.active?1:.5}}>
                <div>
                  <div style={{fontSize:13,fontWeight:700,color:m.active?C.navy:C.muted}}>{m.form_name}</div>
                  <div style={{fontSize:11,color:C.muted,marginTop:1}}>{m.purpose.slice(0,40)}{m.purpose.length>40?"…":""}</div>
                  <div style={{fontSize:10,color:C.slate,marginTop:1}}>{m.filing_type} · {m.section_ref}</div>
                </div>
                <div style={{display:"flex",gap:4,flexShrink:0}}>
                  <button onClick={()=>{setEditMaster(m);setShowAddMaster(true);}} style={{background:"none",border:"none",cursor:"pointer",color:C.slate,fontSize:14}}>✏️</button>
                </div>
              </div>
            ))}
          </div>
        ))}
      </div>

      {/* Right panel — entity compliance */}
      <div style={{flex:1,overflowY:"auto",padding:24}}>
        <div style={{marginBottom:20}}>
          <h1 style={{fontSize:20,fontWeight:800,color:C.navy}}>Entity Compliance Calendar</h1>
          <p style={{color:C.muted,fontSize:13,marginTop:3}}>Select entity and FY to view and update compliance status</p>
        </div>

        <Card style={{marginBottom:16,padding:"14px 16px"}}>
          <div style={{display:"flex",gap:14,alignItems:"flex-end",flexWrap:"wrap"}}>
            <Select label="Entity" options={entities.map(e=>({label:e.name,value:String(e.id)}))} value={entityId} onChange={setEntityId} style={{minWidth:260}}/>
            <Select label="Financial Year" options={fyOpts.map(f=>({label:f,value:f}))} value={fy} onChange={setFy} style={{minWidth:130}}/>
          </div>
        </Card>

        {entityId&&fy&&<>
          {/* AGM warning banner */}
          {items.some(i=>i.agmMissing) && (
            <div style={{background:"#fffbeb",border:"1px solid #fde68a",borderRadius:10,padding:"12px 16px",marginBottom:16,display:"flex",alignItems:"center",gap:10,fontSize:13,color:"#92400e"}}>
              <span style={{fontSize:20}}>⚠️</span>
              <div>
                <strong>AGM not recorded for FY {fy}</strong> — Due dates for AOC-4, MGT-7, ADT-1 and other AGM-linked filings cannot be computed.
                <span style={{marginLeft:8,color:C.blue,cursor:"pointer",fontWeight:700,textDecoration:"underline"}} onClick={()=>alert("Go to Board Meetings tab → Record an AGM for this entity")}>How to fix →</span>
              </div>
            </div>
          )}

          {/* Status filter chips */}
          <div style={{display:"flex",gap:8,marginBottom:16,flexWrap:"wrap",alignItems:"center"}}>
            {[{key:"all",label:`All (${items.length})`,bg:"#f1f5f9",fg:C.slate},{key:"overdue",label:`Overdue (${statusCounts.overdue||0})`,bg:"#fee2e2",fg:C.red},{key:"pending",label:`Pending (${statusCounts.pending||0})`,bg:"#fef9c3",fg:C.amber},{key:"filed",label:`Filed (${statusCounts.filed||0})`,bg:"#dcfce7",fg:C.green},{key:"na",label:`N/A (${statusCounts.na||0})`,bg:"#f1f5f9",fg:C.slate}].map(({key,label,bg,fg})=>(
              <button key={key} onClick={()=>setFilter(key)} style={{padding:"5px 14px",borderRadius:20,border:`2px solid ${filter===key?fg:"transparent"}`,background:bg,color:fg,fontWeight:700,fontSize:12,cursor:"pointer"}}>{label}</button>
            ))}
            <div style={{marginLeft:"auto"}}><Btn small variant="secondary" onClick={()=>setShowCustom(true)}>+ Custom Item</Btn></div>
          </div>

          {loading?<div style={{textAlign:"center",padding:32,color:C.muted}}>Loading…</div>:(
            <Card style={{padding:0,overflow:"hidden"}}>
              <div style={{overflowX:"auto"}}>
                <table style={{width:"100%",borderCollapse:"collapse",fontSize:13}}>
                  <thead><tr style={{background:C.light}}>
                    {["Form","Purpose","Type","Due Date","Days","Status","Penalty","Filed By","Action"].map(h=><th key={h} style={{padding:"10px 12px",textAlign:"left",fontSize:11,fontWeight:700,color:C.slate,borderBottom:`1px solid ${C.border}`,whiteSpace:"nowrap"}}>{h}</th>)}
                  </tr></thead>
                  <tbody>
                    {filtered.length===0?<tr><td colSpan={9} style={{padding:32,textAlign:"center",color:C.muted}}>No items for this filter.</td></tr>:
                      filtered.map(item=>{
                        const days=daysUntil(item.dueDate);
                        const penalty=penaltyDays(item)*item.penaltyPerDay;
                        return(
                          <tr key={item.id} style={{borderBottom:`1px solid ${C.border}`}}>
                            <td style={{padding:"10px 12px",fontWeight:700,color:C.navy}}>{item.formName}</td>
                            <td style={{padding:"10px 12px",color:C.text,maxWidth:160,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{item.purpose}</td>
                            <td style={{padding:"10px 12px"}}><Badge label={item.filingType} color={C.indigo} bg={`${C.indigo}15`} small/></td>
                            <td style={{padding:"10px 12px",fontFamily:"monospace",whiteSpace:"nowrap",fontSize:12}}>
                              {item.agmMissing
                                ? <span style={{color:C.amber,fontSize:11,fontWeight:700}}>⚠️ Record AGM first</span>
                                : item.dueDate && item.dueDate!=="Invalid Date"
                                  ? fmtDate(item.dueDate)
                                  : <span style={{color:C.muted}}>Event-based</span>
                              }
                            </td>
                            <td style={{padding:"10px 12px",fontWeight:700,color:item.agmMissing?C.amber:days===null?C.muted:days<0?C.red:days<15?C.amber:C.green,whiteSpace:"nowrap"}}>
                              {item.agmMissing?"—":days===null?"—":days<0?`${Math.abs(days)}d late`:`${days}d`}
                            </td>
                            <td style={{padding:"10px 12px"}}>
                              <Badge label={item.status==="na"?"N/A":item.status} color={statusColor(item.status)} bg={statusBg(item.status)} small/>
                              {item.srn&&<div style={{fontSize:10,color:C.muted,marginTop:2}}>SRN: {item.srn}</div>}
                              {item.comments&&<div style={{fontSize:10,color:C.muted,marginTop:1,maxWidth:100,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}} title={item.comments}>💬 {item.comments}</div>}
                            </td>
                            <td style={{padding:"10px 12px",color:penalty>0?C.red:C.muted,fontWeight:penalty>0?700:400,whiteSpace:"nowrap"}}>
                              {penalty>0?`₹${penalty.toLocaleString("en-IN")}`:"—"}
                            </td>
                            <td style={{padding:"10px 12px",color:C.muted,fontSize:12,whiteSpace:"nowrap"}}>
                              {item.filedDate?<>{fmtDate(item.filedDate)}{item.professionalId&&<div style={{fontSize:10}}>{item.professionalId}</div>}</>:"—"}
                              {(item.attachment1Name||item.attachment2Name)&&(
                                <div style={{marginTop:3,display:"flex",gap:4}}>
                                  {item.attachment1Name&&<button onClick={()=>downloadAttachment(entityId,item.id,fy,"1")} style={{background:"none",border:"none",cursor:"pointer",color:C.blue,fontSize:11}}>📎 Form</button>}
                                  {item.attachment2Name&&<button onClick={()=>downloadAttachment(entityId,item.id,fy,"2")} style={{background:"none",border:"none",cursor:"pointer",color:C.blue,fontSize:11}}>📎 Challan</button>}
                                </div>
                              )}
                            </td>
                            <td style={{padding:"10px 12px"}}>
                              <div style={{display:"flex",gap:4,flexDirection:"column"}}>
                                {item.status!=="filed"&&item.status!=="na"&&<Btn small onClick={()=>setMarkModal(item)}>Update</Btn>}
                                {(item.status==="filed"||item.status==="na")&&<Btn small variant="secondary" onClick={()=>setMarkModal(item)}>Edit</Btn>}
                                {(item.status==="filed"||item.status==="na")&&<Btn small variant="ghost" onClick={()=>restore(item)}>Reset</Btn>}
                              </div>
                            </td>
                          </tr>
                        );
                      })
                    }
                  </tbody>
                </table>
              </div>
            </Card>
          )}

          {customItems.length>0&&(
            <Card style={{marginTop:16}}>
              <h3 style={{fontSize:14,fontWeight:700,color:C.navy,marginBottom:12}}>Custom / Ad-hoc Items</h3>
              {customItems.map(ci=>(
                <div key={ci.id} style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 0",borderBottom:`1px solid ${C.border}`}}>
                  <div><div style={{fontWeight:600}}>{ci.title}</div><div style={{fontSize:12,color:C.muted}}>{ci.description} · Due: {fmtDate(ci.due_date)}</div></div>
                  <div style={{display:"flex",gap:8}}>
                    <Badge label={ci.status} color={statusColor(ci.status)} bg={statusBg(ci.status)} small/>
                    {ci.status!=="filed"&&<Btn small onClick={async()=>{await PUT(`/api/custom-compliance/${ci.id}`,{status:"filed",filed_date:new Date().toISOString().split("T")[0]});reload();}}>Mark Filed</Btn>}
                    <Btn small variant="danger" onClick={async()=>{await DEL(`/api/custom-compliance/${ci.id}`);reload();}}>✕</Btn>
                  </div>
                </div>
              ))}
            </Card>
          )}
        </>}

        {!entityId&&<EmptyState icon="📅" title="Select an entity" subtitle="Choose an entity and financial year to view its compliance calendar."/>}
      </div>

      {/* Mark Filed Modal */}
      {markModal&&<MarkFiledModal item={markModal} entityId={entityId} fy={fy} user={user} onClose={()=>setMarkModal(null)} onSaved={()=>{setMarkModal(null);reload();setToast({msg:"Status updated",type:"success"});}}/>}

      {/* Add/Edit master item */}
      {showAddMaster&&<MasterItemModal item={editMaster} onClose={()=>{setShowAddMaster(false);setEditMaster(null);}} onSaved={()=>{setShowAddMaster(false);setEditMaster(null);GET("/api/compliance-master").then(r=>{if(r.ok)setMasterItems(r.items);});setToast({msg:editMaster?"Item updated":"Item added",type:"success"});}}/>}

      {/* Custom item */}
      {showCustom&&entityId&&<Modal title="Add Custom Compliance Item" onClose={()=>setShowCustom(false)} width={440}>
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          <Input label="Title" required placeholder="e.g. FEMA Return Filing" value={customForm.title} onChange={v=>setCustomForm(p=>({...p,title:v}))}/>
          <Input label="Description" value={customForm.description} onChange={v=>setCustomForm(p=>({...p,description:v}))} placeholder="Optional details"/>
          <Input label="Due Date" type="date" required value={customForm.due_date} onChange={v=>setCustomForm(p=>({...p,due_date:v}))}/>
        </div>
        <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
          <Btn variant="secondary" onClick={()=>setShowCustom(false)}>Cancel</Btn>
          <Btn onClick={async()=>{if(!customForm.title||!customForm.due_date)return;await POST("/api/custom-compliance",{...customForm,entity_id:parseInt(entityId),created_by:user.email});setShowCustom(false);setCustomForm({title:"",description:"",due_date:""});reload();setToast({msg:"Custom item added",type:"success"});}}>Add Item</Btn>
        </div>
      </Modal>}

      {toast&&<Toast msg={toast.msg} type={toast.type} onClose={()=>setToast(null)}/>}
    </div>
  );
};

// ── Compliance Master Item Modal ───────────────────────────────────────────────
const MasterItemModal = ({item,onClose,onSaved}) => {
  const isEdit=!!item;
  // Keep hidden fields with sensible defaults — only show what user needs
  const [form,setForm]=useState({
    id:"",form_name:"",purpose:"",track:"company",
    filing_type:"annual",due_date_type:"event_offset",offset_days:"30",
    fixed_date:"",applicable_to:"all",penalty_per_day:"200",section_ref:"",active:true,
    ...(item?{id:item.id,form_name:item.form_name,purpose:item.purpose,track:item.track,
      filing_type:item.filing_type,applicable_to:item.applicable_to,
      penalty_per_day:String(item.penalty_per_day),section_ref:item.section_ref,active:!!item.active}:{})
  });
  const [saving,setSaving]=useState(false);

  const buildLogic=()=>{
    if(form.due_date_type==="fixed_date") return JSON.stringify({type:"fixed_date",fixedDate:form.fixed_date});
    if(form.due_date_type==="agm_offset") return JSON.stringify({type:"agm_offset",offsetDays:parseInt(form.offset_days)});
    if(form.due_date_type==="incorp_offset") return JSON.stringify({type:"incorp_offset",offsetDays:parseInt(form.offset_days)});
    return JSON.stringify({type:"event_offset",offsetDays:parseInt(form.offset_days)});
  };

  const save=async()=>{
    setSaving(true);
    const payload={...form,due_date_logic:buildLogic(),penalty_per_day:parseFloat(form.penalty_per_day)||200};
    const res=isEdit?await PUT(`/api/compliance-master/${item.id}`,payload):await POST("/api/compliance-master",payload);
    setSaving(false);if(res.ok)onSaved();
  };
  const F=k=>({value:form[k],onChange:v=>setForm(p=>({...p,[k]:v}))});

  return (
    <Modal title={isEdit?"Edit Compliance Item":"Add Compliance Item"} onClose={onClose} width={480}>
      <div style={{display:"flex",flexDirection:"column",gap:16}}>
        {!isEdit&&<Input label="Form ID (unique)" required placeholder="e.g. CUSTOM-1" {...F("id")} helpText="A short unique code — cannot be changed after creation"/>}
        <Input label="Form Name" required placeholder="e.g. MGT-7" {...F("form_name")}/>
        <Input label="Purpose / Description" required placeholder="e.g. Annual Return of Company" {...F("purpose")}/>
        <Select label="Applicable To" options={[{label:"Company",value:"company"},{label:"LLP",value:"llp"},{label:"Both",value:"both"}]} value={form.track} onChange={v=>setForm(p=>({...p,track:v}))}/>
        <Input label="Due Date" type="date" value={form.fixed_date} onChange={v=>setForm(p=>({...p,fixed_date:v,due_date_type:"fixed_date"}))} helpText="Leave blank if due date depends on a trigger event (e.g. AGM, incorporation)"/>
        {isEdit&&<Toggle label="Active (visible in compliance calendars)" checked={form.active} onChange={v=>setForm(p=>({...p,active:v}))}/>}
      </div>
      <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
        <Btn variant="secondary" onClick={onClose}>Cancel</Btn>
        <Btn onClick={save} disabled={saving}>{saving?"Saving…":isEdit?"Save Changes":"Add Item"}</Btn>
      </div>
    </Modal>
  );
};

// ── Board Meetings Page ───────────────────────────────────────────────────────
const BoardMeetingsPage = ({user}) => {
  const [entities,setEntities]=useState([]);
  const [entityId,setEntityId]=useState("");
  const [meetings,setMeetings]=useState([]);
  const [showForm,setShowForm]=useState(false);
  const [form,setForm]=useState({meeting_type:"BM",meeting_date:"",notice_date:"",description:""});
  const [noticeFile,setNoticeFile]=useState(null);
  const [minutesFile,setMinutesFile]=useState(null);
  const [toast,setToast]=useState(null);
  const noticeRef=useRef(),minutesRef=useRef();

  useEffect(()=>{GET("/api/entities").then(r=>{if(r.ok)setEntities(r.entities);});},[]);
  const loadMeetings=()=>{if(entityId)GET(`/api/entities/${entityId}/board-meetings`).then(r=>{if(r.ok)setMeetings(r.meetings);});};
  useEffect(()=>{loadMeetings();},[entityId]);

  const handleFile=async(e,type)=>{const file=e.target.files[0];if(!file)return;const result=await readFileAsBase64(file);if(type==="notice")setNoticeFile(result);else setMinutesFile(result);};

  const [meetingError,setMeetingError]=useState("");
  const save=async()=>{
    if(!form.meeting_date){return;}
    if(form.notice_date && form.meeting_date < form.notice_date){
      setMeetingError("Meeting date cannot be earlier than the Notice date.");
      return;
    }
    setMeetingError("");
    await POST(`/api/entities/${entityId}/board-meetings`,{
      ...form,
      notice_filename:noticeFile?.name||"",notice_data:noticeFile?.data||"",
      minutes_filename:minutesFile?.name||"",minutes_data:minutesFile?.data||"",
    });
    setShowForm(false);
    setForm({meeting_type:"BM",meeting_date:"",notice_date:"",description:""});
    setNoticeFile(null);setMinutesFile(null);
    loadMeetings();setToast({msg:"Meeting recorded",type:"success"});
  };

  const remove=async id=>{await DEL(`/api/board-meetings/${id}`);loadMeetings();};
  const downloadAtt=async(id,type)=>{const r=await GET(`/api/board-meetings/${id}/attachment/${type}`);if(r.ok&&r.data)downloadFile(r.data,r.filename,"application/octet-stream");};

  const boardMeetings=meetings.filter(m=>m.meeting_type==="BM");
  const thisYear=boardMeetings.filter(m=>m.meeting_date&&new Date(m.meeting_date).getFullYear()===new Date().getFullYear());

  return (
    <div style={{padding:28}}>
      <h1 style={{fontSize:22,fontWeight:800,color:C.navy,marginBottom:6}}>Board Meetings</h1>
      <p style={{color:C.muted,marginBottom:24}}>Track Board Meetings, AGMs, EGMs and other meetings with notice and minutes attachments</p>
      <Card style={{marginBottom:20,padding:"14px 16px"}}>
        <div style={{display:"flex",gap:14,alignItems:"flex-end"}}>
          <Select label="Entity" options={entities.map(e=>({label:e.name,value:String(e.id)}))} value={entityId} onChange={setEntityId} style={{minWidth:280}}/>
          {entityId&&<Btn small onClick={()=>setShowForm(true)}>+ Record Meeting</Btn>}
        </div>
      </Card>

      {entityId&&<>
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(160px,1fr))",gap:16,marginBottom:24}}>
          <StatCard label="Board Meetings (This Yr)" value={thisYear.length} icon="📋" color={thisYear.length>=4?C.green:C.red} sub="Min 4 required / year"/>
          <StatCard label="Total Meetings" value={meetings.length} icon="📁" color={C.navy}/>
          <StatCard label="AGMs" value={meetings.filter(m=>m.meeting_type==="AGM").length} icon="🎯" color={C.indigo}/>
        </div>
        {thisYear.length<4&&<div style={{background:"#fee2e2",border:`1px solid ${C.red}`,borderRadius:10,padding:"12px 16px",marginBottom:20,color:C.red,fontSize:14,fontWeight:600}}>⚠️ Only {thisYear.length}/4 board meetings recorded for this calendar year.</div>}
        <Card style={{padding:0}}>
          {meetings.length===0?<EmptyState icon="📋" title="No meetings recorded" subtitle="Record board meetings, AGMs, and EGMs."/>:(
            <table style={{width:"100%",borderCollapse:"collapse",fontSize:13}}>
              <thead><tr style={{background:C.light}}>{["Type","Notice Date","Meeting Date","Description","Attachments",""].map(h=><th key={h} style={{padding:"10px 12px",textAlign:"left",fontSize:11,fontWeight:700,color:C.slate,borderBottom:`1px solid ${C.border}`}}>{h}</th>)}</tr></thead>
              <tbody>{meetings.map(m=><tr key={m.id} style={{borderBottom:`1px solid ${C.border}`}}>
                <td style={{padding:"10px 12px"}}><Badge label={m.meeting_type} color={C.indigo} bg={`${C.indigo}15`} small/></td>
                <td style={{padding:"10px 12px",color:C.muted}}>{fmtDate(m.notice_date)}</td>
                <td style={{padding:"10px 12px",fontWeight:600}}>{fmtDate(m.meeting_date)}</td>
                <td style={{padding:"10px 12px",color:C.muted,maxWidth:200}}>{m.description||"—"}</td>
                <td style={{padding:"10px 12px"}}>
                  <div style={{display:"flex",gap:6}}>
                    {m.notice_filename&&<button onClick={()=>downloadAtt(m.id,"notice")} style={{background:"none",border:`1px solid ${C.border}`,borderRadius:6,padding:"3px 8px",cursor:"pointer",fontSize:11,color:C.blue}}>📎 Notice</button>}
                    {m.minutes_filename&&<button onClick={()=>downloadAtt(m.id,"minutes")} style={{background:"none",border:`1px solid ${C.border}`,borderRadius:6,padding:"3px 8px",cursor:"pointer",fontSize:11,color:C.blue}}>📎 Minutes</button>}
                    {!m.notice_filename&&!m.minutes_filename&&<span style={{color:C.muted,fontSize:12}}>—</span>}
                  </div>
                </td>
                <td style={{padding:"10px 12px"}}><Btn small variant="danger" onClick={()=>remove(m.id)}>✕</Btn></td>
              </tr>)}</tbody>
            </table>
          )}
        </Card>
      </>}
      {!entityId&&<EmptyState icon="📋" title="Select an entity" subtitle="Choose an entity to view and record its board meetings."/>}

      {showForm&&<Modal title="Record Meeting" onClose={()=>setShowForm(false)} width={520}>
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          <Select label="Type of Meeting" required options={MEETING_TYPES.map(t=>({label:t==="BM"?"Board Meeting":t==="AGM"?"Annual General Meeting (AGM)":t==="EGM"?"Extraordinary General Meeting (EGM)":"Others",value:t}))} value={form.meeting_type} onChange={v=>setForm(p=>({...p,meeting_type:v}))}/>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
            <Input label="Notice Date" type="date" value={form.notice_date} onChange={v=>{setForm(p=>({...p,notice_date:v}));setMeetingError("");}} helpText="BM: 7 days notice · AGM: 21 days"/>
            <Input label="Meeting Date" type="date" required value={form.meeting_date} onChange={v=>{setForm(p=>({...p,meeting_date:v}));setMeetingError("");}}/>
          </div>
          <Input label="Brief Description" placeholder="e.g. Quarterly accounts review, dividend declaration…" value={form.description} onChange={v=>setForm(p=>({...p,description:v}))}/>
          {meetingError && <div style={{background:"#fee2e2",color:C.red,padding:"10px 14px",borderRadius:8,fontSize:13,fontWeight:500}}>⚠️ {meetingError}</div>}

          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
            <div>
              <label style={{fontSize:13,fontWeight:600,color:C.text,display:"block",marginBottom:6}}>Attach Notice</label>
              <input ref={noticeRef} type="file" onChange={e=>handleFile(e,"notice")} accept=".pdf,.doc,.docx,.jpg,.png" style={{width:"100%",padding:"6px",border:`1px solid ${C.border}`,borderRadius:8,fontSize:12}}/>
              {noticeFile&&<div style={{fontSize:11,color:C.green,marginTop:3}}>✓ {noticeFile.name}</div>}
            </div>
            <div>
              <label style={{fontSize:13,fontWeight:600,color:C.text,display:"block",marginBottom:6}}>Attach Minutes</label>
              <input ref={minutesRef} type="file" onChange={e=>handleFile(e,"minutes")} accept=".pdf,.doc,.docx,.jpg,.png" style={{width:"100%",padding:"6px",border:`1px solid ${C.border}`,borderRadius:8,fontSize:12}}/>
              {minutesFile&&<div style={{fontSize:11,color:C.green,marginTop:3}}>✓ {minutesFile.name}</div>}
            </div>
          </div>
        </div>
        <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
          <Btn variant="secondary" onClick={()=>setShowForm(false)}>Cancel</Btn>
          <Btn onClick={save} disabled={!form.meeting_date}>Save Meeting</Btn>
        </div>
      </Modal>}
      {toast&&<Toast msg={toast.msg} type={toast.type} onClose={()=>setToast(null)}/>}
    </div>
  );
};

// ── Password Vault Page ───────────────────────────────────────────────────────
const PasswordVaultPage = ({user}) => {
  const [entries,setEntities]=useState([]);
  const [category,setCategory]=useState("professional");
  const [locked,setLocked]=useState(true);
  const [pinInput,setPinInput]=useState("");
  const [pinError,setPinError]=useState("");
  const [showForm,setShowForm]=useState(false);
  const [editEntry,setEditEntry]=useState(null);
  const [revealed,setRevealed]=useState({});
  const [toast,setToast]=useState(null);
  const [entities,setEntitiesData]=useState([]);
  const [directors,setDirectors]=useState([]);
  const [form,setForm]=useState({category:"professional",portal_name:"",portal_url:"",description:"",username:"",password:"",entity_id:"",director_id:""});
  const PIN_KEY="rcp_vault_pin";

  useEffect(()=>{GET("/api/entities").then(r=>{if(r.ok)setEntitiesData(r.entities);});},[]);

  const [selectedVaultEntity,setSelectedVaultEntity]=useState("");
  const loadEntries=()=>{
    let url=`/api/vault?category=${category}`;
    if(category==="entity"&&selectedVaultEntity) url+=`&entity_id=${selectedVaultEntity}`;
    GET(url).then(r=>{if(r.ok)setEntities(r.entries);});
  };
  useEffect(()=>{if(!locked)loadEntries();},[locked,category,selectedVaultEntity]);

  useEffect(()=>{
    if(form.entity_id){GET(`/api/entities/${form.entity_id}/directors`).then(r=>{if(r.ok)setDirectors(r.directors);});}
    else setDirectors([]);
  },[form.entity_id]);

  const unlock=()=>{
    const saved=localStorage.getItem(PIN_KEY);
    if(!saved){if(pinInput.length<4){setPinError("PIN must be at least 4 digits.");return;}localStorage.setItem(PIN_KEY,pinInput);}
    else{if(pinInput!==saved){setPinError("Incorrect PIN.");return;}}
    setLocked(false);setPinInput("");setPinError("");
  };

  const revealPw=async id=>{const r=await POST(`/api/vault/${id}/reveal`,{});if(r.ok)setRevealed(p=>({...p,[id]:r.password}));};
  const hidePw=id=>setRevealed(p=>{const n={...p};delete n[id];return n;});
  const copyPw=async id=>{const r=await POST(`/api/vault/${id}/reveal`,{});if(r.ok){navigator.clipboard.writeText(r.password);setToast({msg:"Password copied",type:"success"});}};

  const save=async()=>{
    if(!form.portal_name)return;
    const payload={...form,entity_id:form.entity_id?parseInt(form.entity_id):null,director_id:form.director_id?parseInt(form.director_id):null};
    if(editEntry)await PUT(`/api/vault/${editEntry.id}`,payload);else await POST("/api/vault",payload);
    setShowForm(false);setEditEntry(null);setForm({category:"professional",portal_name:"",portal_url:"",description:"",username:"",password:"",entity_id:"",director_id:""});
    loadEntries();setToast({msg:editEntry?"Updated":"Added",type:"success"});
  };
  const del=async id=>{await DEL(`/api/vault/${id}`);loadEntries();setToast({msg:"Entry deleted",type:"success"});};

  const CATEGORIES=[{value:"professional",label:"Professional Users",icon:"🧑‍💼",desc:"CA/CS firm login IDs used for MCA filings"},{value:"entity",label:"Entity Logins",icon:"🏢",desc:"Company & LLP portal credentials"},{value:"director",label:"Directors & Partners",icon:"👤",desc:"Individual director/partner login IDs"}];

  if(locked) return (
    <div style={{padding:32,maxWidth:480,margin:"0 auto"}}>
      <div style={{textAlign:"center",marginBottom:32}}>
        <div style={{fontSize:48,marginBottom:12}}>🔐</div>
        <h1 style={{fontSize:22,fontWeight:800,color:C.navy}}>Password Vault</h1>
        <p style={{color:C.muted,marginTop:6}}>Securely store portal credentials. All passwords encrypted with AES-256-GCM.</p>
      </div>
      <Card>
        <div style={{background:C.navy,borderRadius:10,padding:"14px 18px",marginBottom:20}}>
          <div style={{color:"#fff",fontWeight:700}}>🔒 AES-256-GCM Encrypted</div>
          <div style={{color:"#94c5f7",fontSize:12,marginTop:3}}>Passwords are encrypted before storage. Never stored in plain text. All data saved in server database.</div>
        </div>
        {pinError&&<div style={{background:"#fee2e2",color:C.red,padding:"8px 12px",borderRadius:8,marginBottom:14,fontSize:13}}>{pinError}</div>}
        <Input label={localStorage.getItem(PIN_KEY)?"Enter Vault PIN":"Set Vault PIN (first time)"} type="password" value={pinInput} onChange={setPinInput} placeholder="Enter your PIN"/>
        <Btn onClick={unlock} style={{width:"100%",justifyContent:"center",marginTop:14}}>🔓 Unlock Vault</Btn>
        {!localStorage.getItem(PIN_KEY)&&<p style={{fontSize:12,color:C.muted,marginTop:12,textAlign:"center"}}>First time? Set a PIN to protect your vault.</p>}
      </Card>
    </div>
  );

  return (
    <div style={{padding:28}}>
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:24}}>
        <div>
          <h1 style={{fontSize:22,fontWeight:800,color:C.navy}}>Password Vault</h1>
          <p style={{color:C.muted,marginTop:4}}>AES-256-GCM encrypted · All data stored in server database</p>
        </div>
        <div style={{display:"flex",gap:10}}>
          <Btn small variant="secondary" onClick={()=>setLocked(true)}>🔒 Lock</Btn>
          <Btn small onClick={()=>{setEditEntry(null);setForm({category,portal_name:"",portal_url:"",description:"",username:"",password:"",entity_id:"",director_id:"",dsc_expiry:""});setShowForm(true);}}>+ Add Entry</Btn>
        </div>
      </div>

      {/* Category tabs */}
      <div style={{display:"flex",gap:12,marginBottom:24,flexWrap:"wrap"}}>
        {CATEGORIES.map(c=>(
          <div key={c.value} onClick={()=>setCategory(c.value)} style={{flex:1,minWidth:180,padding:"14px 18px",borderRadius:12,border:`2px solid ${category===c.value?C.blue:C.border}`,background:category===c.value?`${C.blue}08`:"#fff",cursor:"pointer",transition:"all .15s"}}>
            <div style={{fontSize:24,marginBottom:6}}>{c.icon}</div>
            <div style={{fontWeight:700,fontSize:14,color:category===c.value?C.blue:C.text}}>{c.label}</div>
            <div style={{fontSize:12,color:C.muted,marginTop:2}}>{c.desc}</div>
          </div>
        ))}
      </div>

      {/* Entity selector for entity category */}
      {category==="entity" && (
        <Card style={{padding:"14px 16px",marginBottom:20}}>
          <div style={{display:"flex",gap:14,alignItems:"flex-end"}}>
            <Select label="Select Entity to view passwords" options={entities.map(e=>({label:e.name,value:String(e.id)}))} value={selectedVaultEntity} onChange={setSelectedVaultEntity} style={{minWidth:280}}/>
            {selectedVaultEntity && <Btn small variant="secondary" onClick={()=>setSelectedVaultEntity("")}>Show All</Btn>}
          </div>
        </Card>
      )}

      {entries.length===0?<EmptyState icon="🔑" title={`No ${CATEGORIES.find(c=>c.value===category)?.label||"entries"}`} subtitle="Add portal credentials to store them securely." action={<Btn onClick={()=>{setForm({category,portal_name:"",portal_url:"",description:"",username:"",password:"",entity_id:"",director_id:""});setShowForm(true);}}>Add Entry</Btn>}/>:(
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(340px,1fr))",gap:16}}>
          {entries.map(e=>(
            <Card key={e.id} style={{padding:20}}>
              <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",marginBottom:14}}>
                <div>
                  <div style={{fontWeight:700,fontSize:15,color:C.navy}}>{e.portal_name}</div>
                  {e.description&&<div style={{fontSize:12,color:C.muted,marginTop:2}}>{e.description}</div>}
                </div>
                <div style={{display:"flex",gap:6}}>
                  {e.portal_url&&<a href={e.portal_url} target="_blank" rel="noreferrer" style={{fontSize:12,color:C.blue,textDecoration:"none",fontWeight:600,padding:"4px 10px",border:`1px solid ${C.blue}`,borderRadius:6}}>Open ↗</a>}
                  <Btn small variant="secondary" onClick={()=>{setEditEntry(e);setForm({category:e.category,portal_name:e.portal_name,portal_url:e.portal_url||"",description:e.description||"",username:e.username||"",password:"",entity_id:e.entity_id?String(e.entity_id):"",director_id:e.director_id?String(e.director_id):"",dsc_expiry:e.dsc_expiry||""});setShowForm(true);}}>Edit</Btn>
                </div>
              </div>
              <div style={{display:"flex",flexDirection:"column",gap:10}}>
                <div>
                  <label style={{fontSize:11,fontWeight:600,color:C.muted,textTransform:"uppercase",letterSpacing:.5}}>Username / ID</label>
                  <div style={{background:C.light,border:`1px solid ${C.border}`,borderRadius:8,padding:"8px 12px",fontSize:13,marginTop:4,fontFamily:"monospace"}}>{e.username||<span style={{color:C.muted}}>Not set</span>}</div>
                </div>
                <div>
                  <label style={{fontSize:11,fontWeight:600,color:C.muted,textTransform:"uppercase",letterSpacing:.5}}>Password</label>
                  <div style={{display:"flex",gap:8,marginTop:4}}>
                    <div style={{flex:1,background:C.light,border:`1px solid ${C.border}`,borderRadius:8,padding:"8px 12px",fontSize:13,fontFamily:"monospace"}}>{revealed[e.id]!==undefined?revealed[e.id]||<span style={{color:C.muted}}>Empty</span>:"••••••••••"}</div>
                    <button onClick={()=>revealed[e.id]!==undefined?hidePw(e.id):revealPw(e.id)} style={{background:"none",border:`1px solid ${C.border}`,borderRadius:8,padding:"6px 10px",cursor:"pointer",fontSize:14}}>{revealed[e.id]!==undefined?"🙈":"👁"}</button>
                    <button onClick={()=>copyPw(e.id)} style={{background:"none",border:`1px solid ${C.border}`,borderRadius:8,padding:"6px 10px",cursor:"pointer",fontSize:14}}>📋</button>
                  </div>
                </div>
              </div>
              {e.dsc_expiry && (()=>{
                const d=Math.ceil((new Date(e.dsc_expiry)-new Date())/864e5);
                const color=d<0?C.red:d<=7?C.red:d<=30?C.amber:C.green;
                return <div style={{marginTop:10,padding:"6px 12px",borderRadius:8,background:d<=30?"#fff7ed":"#f0fdf4",border:"1px solid "+(d<=30?"#fed7aa":"#bbf7d0"),fontSize:12,color}}>
                  🔑 DSC Expiry: {fmtDate(e.dsc_expiry)} {d<0?"(EXPIRED ⚠️)":d<=7?`(${d}d — urgent!)`:d<=30?`(${d}d remaining)`:""}
                </div>;
              })()}
              <div style={{marginTop:12,display:"flex",justifyContent:"flex-end"}}>
                <Btn small variant="danger" onClick={()=>del(e.id)}>Delete</Btn>
              </div>
            </Card>
          ))}
        </div>
      )}

      {showForm&&<Modal title={editEntry?"Edit Entry":"Add Vault Entry"} onClose={()=>setShowForm(false)} width={500}>
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          <Select label="Category" options={CATEGORIES.map(c=>({label:c.label,value:c.value}))} value={form.category} onChange={v=>setForm(p=>({...p,category:v}))}/>
          <Input label="Portal / System Name" required placeholder="e.g. MCA V3 Portal" value={form.portal_name} onChange={v=>setForm(p=>({...p,portal_name:v}))}/>
          <Input label="URL" placeholder="https://www.mca.gov.in" value={form.portal_url} onChange={v=>setForm(p=>({...p,portal_url:v}))}/>
          <Input label="Description" placeholder="e.g. Used for ROC annual filings" value={form.description} onChange={v=>setForm(p=>({...p,description:v}))}/>
          {form.category==="entity"&&<Select label="Linked Entity" options={entities.map(e=>({label:e.name,value:String(e.id)}))} value={form.entity_id} onChange={v=>setForm(p=>({...p,entity_id:v}))}/>}
          {form.category==="director"&&<>
            <Select label="Linked Entity" options={entities.map(e=>({label:e.name,value:String(e.id)}))} value={form.entity_id} onChange={v=>setForm(p=>({...p,entity_id:v,director_id:""}))}/>
            {directors.length>0&&<Select label="Linked Director" options={directors.map(d=>({label:`${d.name} — ${d.designation}`,value:String(d.id)}))} value={form.director_id} onChange={v=>setForm(p=>({...p,director_id:v}))}/>}
          </>}
          <Input label="Username / Login ID" placeholder="Your login ID or email" value={form.username} onChange={v=>setForm(p=>({...p,username:v}))}/>
          <Input label="Password" type="password" placeholder={editEntry?"Leave blank to keep current":"Enter password"} value={form.password} onChange={v=>setForm(p=>({...p,password:v}))}/>
          <Input label="DSC Expiry Date" type="date" value={form.dsc_expiry||""} onChange={v=>setForm(p=>({...p,dsc_expiry:v}))} helpText="Optional — get alerted 30 days before expiry"/>
        </div>
        <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
          <Btn variant="secondary" onClick={()=>setShowForm(false)}>Cancel</Btn>
          <Btn onClick={save}>{editEntry?"Save Changes":"Add Entry"}</Btn>
        </div>
      </Modal>}
      {toast&&<Toast msg={toast.msg} type={toast.type} onClose={()=>setToast(null)}/>}
    </div>
  );
};

// ── Audit Tracker Page ────────────────────────────────────────────────────────
const AuditTrackerPage = ({user}) => {
  const [entities,setEntities]=useState([]);
  const [appointments,setAppointments]=useState([]);
  const [showForm,setShowForm]=useState(false);
  const [editItem,setEditItem]=useState(null);
  const [form,setForm]=useState({entity_id:"",auditor_name:"",firm_reg_no:"",adt1_srn:"",appointment_date:"",start_fy:"",end_fy:"",reappointment_date:"",notes:""});
  const [attachment,setAttachment]=useState(null);
  const [toast,setToast]=useState(null);
  const fileRef=useRef();

  useEffect(()=>{
    GET("/api/entities").then(r=>{if(r.ok)setEntities(r.entities);});
    GET("/api/audit-appointments").then(r=>{if(r.ok)setAppointments(r.appointments);});
  },[]);

  const loadAll=()=>GET("/api/audit-appointments").then(r=>{if(r.ok)setAppointments(r.appointments);});

  const save=async()=>{
    if(!form.entity_id||!form.auditor_name)return;
    const payload={...form,entity_id:parseInt(form.entity_id),attachment_name:attachment?.name||(editItem?.attachment_name||""),attachment_data:attachment?.data||""};
    if(editItem)await PUT(`/api/audit-appointments/${editItem.id}`,payload);
    else await POST("/api/audit-appointments",payload);
    setShowForm(false);setEditItem(null);setAttachment(null);
    setForm({entity_id:"",auditor_name:"",firm_reg_no:"",adt1_srn:"",appointment_date:"",start_fy:"",end_fy:"",reappointment_date:"",notes:""});
    loadAll();setToast({msg:editItem?"Updated":"Added",type:"success"});
  };

  const del=async id=>{await DEL(`/api/audit-appointments/${id}`);loadAll();setToast({msg:"Deleted",type:"success"});};
  const downloadAdt=async id=>{const r=await GET(`/api/audit-appointments/${id}/attachment`);if(r.ok&&r.data)downloadFile(r.data,r.filename,"application/octet-stream");};

  const F=k=>({value:form[k],onChange:v=>setForm(p=>({...p,[k]:v}))});

  // Compute tenure expiry
  // ADT-1 due = 15 days after AGM of ending FY — computed from meetings data
  // We'll fetch it from the API when building the appointments list
  const tenureEnd=(appt)=>{
    // Returns computed ADT-1 due date from agm lookup — stored in appt.adt1_due if available
    return appt.adt1_due || null;
  };

  return (
    <div style={{padding:28}}>
      <h1 style={{fontSize:22,fontWeight:800,color:C.navy,marginBottom:6}}>Audit Appointment Tracker</h1>
      <p style={{color:C.muted,marginBottom:24}}>Track statutory auditor appointments, ADT-1 SRNs, tenure and rotation schedules</p>
      <div style={{display:"flex",justifyContent:"flex-end",marginBottom:20}}>
        <Btn onClick={()=>{setEditItem(null);setForm({entity_id:"",auditor_name:"",firm_reg_no:"",adt1_srn:"",appointment_date:"",start_fy:"",end_fy:"",reappointment_date:"",notes:""});setAttachment(null);setShowForm(true);}}>+ Add Appointment</Btn>
      </div>
      <Card style={{padding:0}}>
        {appointments.length===0?<EmptyState icon="📜" title="No audit appointments" subtitle="Track your statutory auditor appointments, tenure, and rotation here."/>:(
          <table style={{width:"100%",borderCollapse:"collapse",fontSize:13}}>
            <thead><tr style={{background:C.light}}>{["Entity","Auditor / Firm","Firm Reg No.","ADT-1 SRN","Appointed","Start FY","End FY","ADT-1 Due","Reappointment","ADT-1",""].map(h=><th key={h} style={{padding:"10px 12px",textAlign:"left",fontSize:11,fontWeight:700,color:C.slate,borderBottom:`1px solid ${C.border}`,whiteSpace:"nowrap"}}>{h}</th>)}</tr></thead>
            <tbody>{appointments.map(a=>{
              const end=tenureEnd(a);
              const daysLeft=daysUntil(end);
              const expiringSoon=daysLeft!==null&&daysLeft<=180&&daysLeft>0;
              const expired=daysLeft!==null&&daysLeft<=0;
              return(
                <tr key={a.id} style={{borderBottom:`1px solid ${C.border}`}}>
                  <td style={{padding:"10px 12px",fontWeight:600}}>{a.entity_name}</td>
                  <td style={{padding:"10px 12px"}}>{a.auditor_name}</td>
                  <td style={{padding:"10px 12px",color:C.muted,fontFamily:"monospace",fontSize:12}}>{a.firm_reg_no||"—"}</td>
                  <td style={{padding:"10px 12px",color:C.muted,fontFamily:"monospace",fontSize:12}}>{a.adt1_srn||"—"}</td>
                  <td style={{padding:"10px 12px",whiteSpace:"nowrap"}}>{fmtDate(a.appointment_date)}</td>
                  <td style={{padding:"10px 12px",color:C.muted}}>{a.start_fy||"—"}</td>
                  <td style={{padding:"10px 12px",color:C.muted}}>{a.end_fy||"—"}</td>
                  <td style={{padding:"10px 12px",whiteSpace:"nowrap"}}>
                    {end?<span style={{color:expired?C.red:expiringSoon?C.amber:C.green,fontWeight:expired||expiringSoon?700:400}}>
                      {fmtDate(end)}{expired&&" ⚠️"}{expiringSoon&&" ⏰"}
                    </span>:<span style={{color:C.muted,fontSize:12}}>No AGM recorded</span>}
                  </td>
                  <td style={{padding:"10px 12px",whiteSpace:"nowrap"}}>{fmtDate(a.reappointment_date)}</td>
                  <td style={{padding:"10px 12px"}}>
                    {a.attachment_name?<button onClick={()=>downloadAdt(a.id)} style={{background:"none",border:`1px solid ${C.border}`,borderRadius:6,padding:"3px 8px",cursor:"pointer",fontSize:11,color:C.blue}}>📎 ADT-1</button>:<span style={{color:C.muted,fontSize:12}}>—</span>}
                  </td>
                  <td style={{padding:"10px 12px",display:"flex",gap:6}}>
                    <Btn small variant="secondary" onClick={()=>{setEditItem(a);setForm({entity_id:String(a.entity_id),auditor_name:a.auditor_name,firm_reg_no:a.firm_reg_no||"",adt1_srn:a.adt1_srn||"",appointment_date:a.appointment_date||"",start_fy:a.start_fy||"",end_fy:a.end_fy||"",reappointment_date:a.reappointment_date||"",notes:a.notes||""});setShowForm(true);}}>Edit</Btn>
                    <Btn small variant="danger" onClick={()=>del(a.id)}>✕</Btn>
                  </td>
                </tr>
              );
            })}</tbody>
          </table>
        )}
      </Card>

      {showForm&&<Modal title={editItem?"Edit Audit Appointment":"Add Audit Appointment"} onClose={()=>setShowForm(false)} width={600}>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16}}>
          <Select label="Entity" required options={entities.map(e=>({label:e.name,value:String(e.id)}))} {...F("entity_id")} style={{gridColumn:"1/-1"}}/>
          <Input label="Auditor / Firm Name" required placeholder="M/s. ABC & Associates" {...F("auditor_name")} style={{gridColumn:"1/-1"}}/>
          <Input label="Firm Registration No." placeholder="e.g. 123456W" {...F("firm_reg_no")}/>
          <Input label="ADT-1 SRN" placeholder="e.g. F12345678" {...F("adt1_srn")}/>
          <Input label="Date of Appointment" type="date" {...F("appointment_date")}/>
          <Input label="Starting Financial Year" placeholder="e.g. 2024-25" helpText="FY from which audit tenure starts" {...F("start_fy")}/>
          <Input label="Ending Financial Year" placeholder="e.g. 2028-29" helpText="FY in which this audit tenure ends (ADT-1 due 15 days after that year's AGM)" {...F("end_fy")}/>
          <Input label="Reappointment Date (if any)" type="date" {...F("reappointment_date")}/>
          <Input label="Notes" placeholder="Any additional notes" {...F("notes")}/>
        </div>
        <div style={{marginTop:16}}>
          <label style={{fontSize:13,fontWeight:600,color:C.text,display:"block",marginBottom:6}}>Attach ADT-1 Form</label>
          <input ref={fileRef} type="file" accept=".pdf,.jpg,.png,.doc,.docx" onChange={async e=>{const file=e.target.files[0];if(file){const r=await readFileAsBase64(file);setAttachment(r);}}} style={{width:"100%",padding:"6px",border:`1px solid ${C.border}`,borderRadius:8,fontSize:13}}/>
          {(attachment||editItem?.attachment_name)&&<div style={{fontSize:12,color:C.green,marginTop:4}}>✓ {attachment?.name||editItem?.attachment_name}</div>}
        </div>
        <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
          <Btn variant="secondary" onClick={()=>setShowForm(false)}>Cancel</Btn>
          <Btn onClick={save} disabled={!form.entity_id||!form.auditor_name}>{editItem?"Save Changes":"Add Appointment"}</Btn>
        </div>
      </Modal>}
      {toast&&<Toast msg={toast.msg} type={toast.type} onClose={()=>setToast(null)}/>}
    </div>
  );
};

// ── Admin Page ────────────────────────────────────────────────────────────────
const AdminPage = ({user}) => {
  const [tab,setTab]=useState("reminders");
  const [reminderEmails,setReminderEmails]=useState([]);
  const [settings,setSettings]=useState({});
  const [smtp,setSmtp]=useState({zohoHost:"smtp.zoho.in",zohoPort:"587",zohoUser:"",zohoPw:"",zohoFrom:"",zohoFromName:"Compliance Pro"});
  const [toast,setToast]=useState(null);
  const [adminPw,setAdminPw]=useState({newPw:"",confirm:""});
  const [newEmail,setNewEmail]=useState({email:"",name:""});
  const [smtpTestResult,setSmtpTestResult]=useState(null);
  const [testing,setTesting]=useState(false);
  const [triggering,setTriggering]=useState(false);

  useEffect(()=>{
    GET("/api/reminder-emails").then(r=>{if(r.ok)setReminderEmails(r.emails);});
    GET("/api/settings").then(r=>{if(r.ok){setSettings(r.settings);if(r.settings.aif_smtp)setSmtp(r.settings.aif_smtp);}});
  },[]);

  const saveSmtp=async()=>{await POST("/api/settings",{key:"aif_smtp",value:smtp});setToast({msg:"Email settings saved",type:"success"});};

  const testSmtp=async()=>{
    setTesting(true);setSmtpTestResult(null);
    const r=await POST("/api/test-smtp",{});setTesting(false);
    setSmtpTestResult(r);setToast({msg:r.ok?r.message:r.error,type:r.ok?"success":"error"});
  };

  const triggerJob=async()=>{
    setTriggering(true);
    const r=await POST("/api/trigger-job",{});setTriggering(false);
    setToast({msg:r.ok?"Reminder emails sent successfully!":r.error||"Job failed",type:r.ok?"success":"error"});
  };

  const saveAdminPw=async()=>{
    if(adminPw.newPw!==adminPw.confirm){setToast({msg:"Passwords don't match",type:"error"});return;}
    if(adminPw.newPw.length<6){setToast({msg:"Password must be at least 6 characters",type:"error"});return;}
    await POST("/api/settings",{key:"admin_password",value:adminPw.newPw});
    setAdminPw({newPw:"",confirm:""});setToast({msg:"Password updated",type:"success"});
  };

  const addEmail=async()=>{
    if(!newEmail.email)return;
    const r=await POST("/api/reminder-emails",newEmail);
    if(r.ok){setNewEmail({email:"",name:""});GET("/api/reminder-emails").then(r=>{if(r.ok)setReminderEmails(r.emails);});setToast({msg:"Email added",type:"success"});}
    else setToast({msg:r.error||"Failed",type:"error"});
  };

  const removeEmail=async id=>{await DEL(`/api/reminder-emails/${id}`);GET("/api/reminder-emails").then(r=>{if(r.ok)setReminderEmails(r.emails);});};
  const toggleEmail=async(id,active)=>{const e=reminderEmails.find(r=>r.id===id);if(e)await PUT(`/api/reminder-emails/${id}`,{...e,active:active?1:0});GET("/api/reminder-emails").then(r=>{if(r.ok)setReminderEmails(r.emails);});};

  const TabBtn=({id,label})=><button onClick={()=>setTab(id)} style={{padding:"9px 20px",border:"none",borderBottom:tab===id?`2px solid ${C.blue}`:"2px solid transparent",background:"none",cursor:"pointer",fontWeight:tab===id?700:500,color:tab===id?C.blue:C.muted,fontSize:14}}>{label}</button>;

  return (
    <div style={{padding:28}}>
      <h1 style={{fontSize:22,fontWeight:800,color:C.navy,marginBottom:24}}>Admin Panel</h1>
      <div style={{display:"flex",borderBottom:`1px solid ${C.border}`,marginBottom:28}}>
        <TabBtn id="reminders" label="Reminder Emails"/>
        <TabBtn id="smtp"      label="Email Settings"/>
        <TabBtn id="system"    label="System"/>
      </div>

      {/* ── Reminder Emails ── */}
      {tab==="reminders"&&(
        <div style={{maxWidth:680}}>
          <Card style={{marginBottom:24}}>
            <h3 style={{fontSize:15,fontWeight:700,color:C.navy,marginBottom:6}}>Compliance Reminder Recipients</h3>
            <p style={{fontSize:13,color:C.muted,marginBottom:20}}>All email addresses listed here will receive the daily consolidated compliance digest covering all entities. Add your team members, compliance officers, and partners.</p>
            <div style={{display:"flex",gap:12,marginBottom:20}}>
              <Input placeholder="Email address" value={newEmail.email} onChange={v=>setNewEmail(p=>({...p,email:v}))} style={{flex:1}}/>
              <Input placeholder="Name (optional)" value={newEmail.name} onChange={v=>setNewEmail(p=>({...p,name:v}))} style={{width:180}}/>
              <Btn onClick={addEmail} disabled={!newEmail.email}>Add</Btn>
            </div>
            {reminderEmails.length===0?<div style={{textAlign:"center",padding:24,color:C.muted,fontSize:14}}>No reminder emails configured yet. Add your first recipient above.</div>:(
              <div style={{display:"flex",flexDirection:"column",gap:10}}>
                {reminderEmails.map(re=>(
                  <div key={re.id} style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",background:re.active?C.light:"#f8fafc",borderRadius:10,border:`1px solid ${C.border}`,opacity:re.active?1:.7}}>
                    <div style={{display:"flex",alignItems:"center",gap:12}}>
                      <div style={{width:36,height:36,borderRadius:"50%",background:re.active?`${C.blue}20`:C.border,display:"flex",alignItems:"center",justifyContent:"center",fontSize:16}}>📧</div>
                      <div>
                        <div style={{fontWeight:600,fontSize:14}}>{re.name||re.email}</div>
                        {re.name&&<div style={{fontSize:12,color:C.muted}}>{re.email}</div>}
                      </div>
                    </div>
                    <div style={{display:"flex",gap:10,alignItems:"center"}}>
                      <Toggle label="" checked={!!re.active} onChange={v=>toggleEmail(re.id,v)}/>
                      <Btn small variant="danger" onClick={()=>removeEmail(re.id)}>Remove</Btn>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </Card>
          <div style={{background:"#f0fdf4",border:"1px solid #bbf7d0",borderRadius:12,padding:"14px 18px",fontSize:13,color:"#166534"}}>
            <strong>📧 How reminders work:</strong> Every day at 8:00 AM IST, the system sends a consolidated email to all active recipients above. The email shows all overdue filings and items due within 30 days across all entities.
          </div>
        </div>
      )}

      {/* ── SMTP Settings ── */}
      {tab==="smtp"&&(
        <div style={{maxWidth:540}}>
          <Card style={{marginBottom:24}}>
            <h3 style={{fontSize:15,fontWeight:700,color:C.navy,marginBottom:6}}>Zoho SMTP Configuration</h3>
            <p style={{fontSize:13,color:C.muted,marginBottom:20}}>Configure your Zoho email to send compliance reminders. Use an App Password, not your main account password.</p>
            <div style={{display:"flex",flexDirection:"column",gap:14}}>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
                <Input label="SMTP Host" value={smtp.zohoHost} onChange={v=>setSmtp(p=>({...p,zohoHost:v}))} placeholder="smtp.zoho.in"/>
                <Input label="SMTP Port" value={smtp.zohoPort} onChange={v=>setSmtp(p=>({...p,zohoPort:v}))} placeholder="587"/>
              </div>
              <Input label="Zoho Email (Username)" type="email" value={smtp.zohoUser} onChange={v=>setSmtp(p=>({...p,zohoUser:v}))} placeholder="contact@yourdomain.com"/>
              <Input label="Zoho App Password" type="password" value={smtp.zohoPw} onChange={v=>setSmtp(p=>({...p,zohoPw:v}))} placeholder="App password from Zoho security settings" helpText="Go to mail.zoho.in → Settings → Security → App Passwords → Generate"/>
              <Input label="From Email" type="email" value={smtp.zohoFrom} onChange={v=>setSmtp(p=>({...p,zohoFrom:v}))} placeholder="contact@yourdomain.com"/>
              <Input label="From Name" value={smtp.zohoFromName} onChange={v=>setSmtp(p=>({...p,zohoFromName:v}))} placeholder="Compliance Pro"/>
              <div style={{display:"flex",gap:12}}>
                <Btn onClick={saveSmtp} style={{flex:1,justifyContent:"center"}}>💾 Save Settings</Btn>
                <Btn variant="secondary" onClick={testSmtp} disabled={testing}>{testing?"Testing…":"📧 Test Email"}</Btn>
              </div>
              {smtpTestResult&&(
                <div style={{background:smtpTestResult.ok?"#dcfce7":"#fee2e2",color:smtpTestResult.ok?C.green:C.red,padding:"10px 14px",borderRadius:8,fontSize:13,fontWeight:500}}>
                  {smtpTestResult.ok?`✓ ${smtpTestResult.message}`:`✕ ${smtpTestResult.error}`}
                </div>
              )}
            </div>
            <div style={{marginTop:20,background:"#fffbeb",border:"1px solid #fde68a",borderRadius:10,padding:"12px 16px",fontSize:12,color:"#92400e"}}>
              <strong>⚠️ Important:</strong> Always save settings first, then test. The App Password is different from your Zoho login password. Generate it at: mail.zoho.in → Settings → Security → App Passwords.
            </div>
          </Card>
          <Card>
            <h3 style={{fontSize:15,fontWeight:700,color:C.navy,marginBottom:16}}>Change Admin Password</h3>
            <div style={{display:"flex",flexDirection:"column",gap:14}}>
              <Input label="New Password" type="password" value={adminPw.newPw} onChange={v=>setAdminPw(p=>({...p,newPw:v}))} placeholder="Minimum 6 characters"/>
              <Input label="Confirm New Password" type="password" value={adminPw.confirm} onChange={v=>setAdminPw(p=>({...p,confirm:v}))} placeholder="Retype new password"/>
              <Btn onClick={saveAdminPw}>Update Password</Btn>
            </div>
          </Card>
        </div>
      )}

      {/* ── System ── */}
      {tab==="system"&&(
        <div style={{maxWidth:540}}>
          <Card style={{marginBottom:20}}>
            <h3 style={{fontSize:15,fontWeight:700,color:C.navy,marginBottom:16}}>Compliance Reminder System</h3>
            <p style={{color:C.muted,fontSize:13,marginBottom:20}}>Reminder emails run daily at 8:00 AM IST. They send a consolidated digest to all active reminder recipients showing overdue filings and items due in the next 30 days across all entities.</p>
            <Btn onClick={triggerJob} disabled={triggering} style={{width:"100%",justifyContent:"center"}}>{triggering?"Sending reminders…":"▶ Trigger Reminder Emails Now"}</Btn>
          </Card>
          <Card>
            <h3 style={{fontSize:15,fontWeight:700,color:C.navy,marginBottom:16}}>System Information</h3>
            {[
              ["App","Compliance Pro v3.0"],
              ["Data Storage","SQLite database on server — nothing in browser"],
              ["Encryption","AES-256-GCM for vault passwords · bcrypt for login passwords"],
              ["Schedule","Daily reminder: 8:00 AM IST (2:30 AM UTC)"],
              ["Coverage","Companies Act 2013 + LLP Act 2008"],
              ["Attachments","Stored in database as base64 — up to 50MB per request"],
            ].map(([k,v])=>(
              <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"8px 0",borderBottom:`1px solid ${C.border}`,fontSize:13}}>
                <span style={{color:C.muted,fontWeight:500}}>{k}</span>
                <span style={{fontWeight:600,color:C.text,maxWidth:320,textAlign:"right"}}>{v}</span>
              </div>
            ))}
          </Card>
        </div>
      )}
      {toast&&<Toast msg={toast.msg} type={toast.type} onClose={()=>setToast(null)}/>}
    </div>
  );
};

// ── Notice Tracker Page ──────────────────────────────────────────────────────
const NOTICE_CATEGORIES = ["GST","Income Tax","MCA"];
const NOTICE_STATUS_OPTS = [{value:"pending",label:"Pending"},{value:"replied",label:"Replied"},{value:"closed",label:"Closed"}];

const noticeStatusColor = s => ({pending:C.amber,replied:C.blue,closed:C.green}[s]||C.muted);
const noticeStatusBg    = s => ({pending:"#fef9c3",replied:"#eff6ff",closed:"#dcfce7"}[s]||"#f1f5f9");

const NoticeTrackerPage = ({user}) => {
  const [notices,setNotices]     = useState([]);
  const [entities,setEntities]   = useState([]);
  const [category,setCategory]   = useState("all");
  const [showForm,setShowForm]   = useState(false);
  const [editItem,setEditItem]   = useState(null);
  const [toast,setToast]         = useState(null);
  const [form,setForm]           = useState({entity_id:"",category:"GST",notice_ref:"",notice_date:"",description:"",due_date:"",status:"pending",reply_date:"",remarks:""});
  const [noticeFile,setNoticeFile] = useState(null);
  const [replyFile,setReplyFile]   = useState(null);
  const noticeRef = useRef(), replyRef = useRef();

  const loadNotices = () => {
    const url = category==="all" ? "/api/notices" : `/api/notices?category=${encodeURIComponent(category)}`;
    GET(url).then(r => { if(r.ok) setNotices(r.notices); });
  };

  useEffect(() => {
    GET("/api/entities").then(r => { if(r.ok) setEntities(r.entities); });
  }, []);

  useEffect(() => { loadNotices(); }, [category]);

  const handleFile = async (e, type) => {
    const file = e.target.files[0]; if (!file) return;
    const result = await readFileAsBase64(file);
    if (type==="notice") setNoticeFile(result); else setReplyFile(result);
  };

  const openAdd = () => {
    setEditItem(null);
    setForm({entity_id:"",category:category==="all"?"GST":category,notice_ref:"",notice_date:"",description:"",due_date:"",status:"pending",reply_date:"",remarks:""});
    setNoticeFile(null); setReplyFile(null);
    setShowForm(true);
  };

  const openEdit = (n) => {
    setEditItem(n);
    setForm({entity_id:n.entity_id?String(n.entity_id):"",category:n.category,notice_ref:n.notice_ref||"" ,notice_date:n.notice_date||"",description:n.description||"",due_date:n.due_date,status:n.status,reply_date:n.reply_date||"",remarks:n.remarks||""});
    setNoticeFile(null); setReplyFile(null);
    setShowForm(true);
  };

  const save = async () => {
    if (!form.due_date) return;
    const payload = {
      ...form,
      entity_id: form.entity_id ? parseInt(form.entity_id) : null,
      notice_filename: noticeFile?.name || (editItem?.notice_filename||""),
      notice_data:     noticeFile?.data || "",
      reply_filename:  replyFile?.name  || (editItem?.reply_filename||""),
      reply_data:      replyFile?.data  || "",
    };
    if (editItem) await PUT(`/api/notices/${editItem.id}`, payload);
    else          await POST("/api/notices", payload);
    setShowForm(false);
    loadNotices();
    setToast({msg: editItem?"Notice updated":"Notice added", type:"success"});
  };

  const del = async id => {
    await DEL(`/api/notices/${id}`);
    loadNotices();
    setToast({msg:"Notice deleted", type:"success"});
  };

  const downloadAtt = async (id, type) => {
    const r = await GET(`/api/notices/${id}/attachment/${type}`);
    if (r.ok && r.data) downloadFile(r.data, r.filename, "application/octet-stream");
  };

  const F = k => ({value:form[k], onChange:v=>setForm(p=>({...p,[k]:v}))});

  // Summary counts
  const counts = notices.reduce((a,n) => { a[n.status]=(a[n.status]||0)+1; a.total=(a.total||0)+1; return a; }, {});
  const overdueNotices = notices.filter(n => n.status==="pending" && n.due_date < new Date().toISOString().split("T")[0]);

  return (
    <div style={{padding:28}}>
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:24}}>
        <div>
          <h1 style={{fontSize:22,fontWeight:800,color:C.navy}}>Notice Tracker</h1>
          <p style={{color:C.muted,marginTop:4}}>Track GST, Income Tax and MCA notices with due dates and reply status</p>
        </div>
        <Btn onClick={openAdd}>+ Add Notice</Btn>
      </div>

      {/* Summary cards */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(150px,1fr))",gap:16,marginBottom:24}}>
        <StatCard label="Total Notices"   value={counts.total||0}   icon="📬" color={C.navy}/>
        <StatCard label="Pending"         value={counts.pending||0} icon="⏳" color={C.amber}/>
        <StatCard label="Overdue"         value={overdueNotices.length} icon="⚠️" color={C.red} sub="Reply date passed"/>
        <StatCard label="Replied"         value={counts.replied||0} icon="✉️" color={C.blue}/>
        <StatCard label="Closed"          value={counts.closed||0}  icon="✅" color={C.green}/>
      </div>

      {/* Category filter tabs */}
      <div style={{display:"flex",gap:8,marginBottom:20,flexWrap:"wrap",alignItems:"center"}}>
        {["all",...NOTICE_CATEGORIES].map(cat => (
          <button key={cat} onClick={()=>setCategory(cat)} style={{padding:"6px 18px",borderRadius:20,border:category===cat?'2px solid '+C.blue:'2px solid transparent',background:category===cat?C.blue+'12':C.light,color:category===cat?C.blue:C.slate,fontWeight:700,fontSize:13,cursor:"pointer"}}>
            {cat==="all"?"All Categories":cat}
          </button>
        ))}
      </div>

      {/* Notices table */}
      <Card style={{padding:0,overflow:"hidden"}}>
        {notices.length===0 ? (
          <EmptyState icon="📬" title="No notices" subtitle="Add GST, Income Tax or MCA notices to track them here." action={<Btn onClick={openAdd}>Add Notice</Btn>}/>
        ) : (
          <div style={{overflowX:"auto"}}>
            <table style={{width:"100%",borderCollapse:"collapse",fontSize:13}}>
              <thead><tr style={{background:C.light}}>
                {["Category","Entity","Ref. No.","Notice Date","Description","Reply Due","Status","Attachments",""].map(h => (
                  <th key={h} style={{padding:"10px 12px",textAlign:"left",fontSize:11,fontWeight:700,color:C.slate,borderBottom:"1px solid "+C.border,whiteSpace:"nowrap"}}>{h}</th>
                ))}
              </tr></thead>
              <tbody>
                {notices.map(n => {
                  const days = daysUntil(n.due_date);
                  const isOverdue = n.status==="pending" && days!==null && days < 0;
                  return (
                    <tr key={n.id} style={{borderBottom:"1px solid "+C.border,background:isOverdue?"#fff9f9":"#fff"}}>
                      <td style={{padding:"10px 12px"}}>
                        <span style={{display:"inline-block",padding:"3px 10px",borderRadius:20,fontWeight:700,fontSize:11,background:
                          n.category==="GST"?"#f0fdf4":n.category==="Income Tax"?"#eff6ff":"#faf5ff",
                          color:n.category==="GST"?C.green:n.category==="Income Tax"?C.blue:C.indigo
                        }}>{n.category}</span>
                      </td>
                      <td style={{padding:"10px 12px",color:C.text,fontWeight:500}}>{n.entity_name||"—"}</td>
                      <td style={{padding:"10px 12px",fontFamily:"monospace",fontSize:12,color:C.slate}}>{n.notice_ref||"—"}</td>
                      <td style={{padding:"10px 12px",color:C.muted,whiteSpace:"nowrap"}}>{fmtDate(n.notice_date)}</td>
                      <td style={{padding:"10px 12px",maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}} title={n.description}>{n.description||"—"}</td>
                      <td style={{padding:"10px 12px",whiteSpace:"nowrap"}}>
                        <span style={{color:isOverdue?C.red:days!==null&&days<=7?C.amber:C.text,fontWeight:isOverdue||days<=7?700:400}}>
                          {fmtDate(n.due_date)}
                        </span>
                        {isOverdue && <div style={{fontSize:10,color:C.red,fontWeight:700}}>OVERDUE</div>}
                        {!isOverdue && days!==null && days<=7 && days>=0 && <div style={{fontSize:10,color:C.amber,fontWeight:700}}>{days}d left</div>}
                      </td>
                      <td style={{padding:"10px 12px"}}>
                        <Badge label={n.status} color={noticeStatusColor(n.status)} bg={noticeStatusBg(n.status)} small/>
                        {n.reply_date && <div style={{fontSize:10,color:C.muted,marginTop:2}}>Replied: {fmtDate(n.reply_date)}</div>}
                      </td>
                      <td style={{padding:"10px 12px"}}>
                        <div style={{display:"flex",gap:4,flexDirection:"column"}}>
                          {n.notice_filename && <button onClick={()=>downloadAtt(n.id,"notice")} style={{background:"none",border:"1px solid "+C.border,borderRadius:6,padding:"2px 8px",cursor:"pointer",fontSize:11,color:C.blue,whiteSpace:"nowrap"}}>📎 Notice</button>}
                          {n.reply_filename  && <button onClick={()=>downloadAtt(n.id,"reply")}  style={{background:"none",border:"1px solid "+C.border,borderRadius:6,padding:"2px 8px",cursor:"pointer",fontSize:11,color:C.green,whiteSpace:"nowrap"}}>📎 Reply</button>}
                          {!n.notice_filename && !n.reply_filename && <span style={{color:C.muted,fontSize:12}}>—</span>}
                        </div>
                      </td>
                      <td style={{padding:"10px 12px"}}>
                        <div style={{display:"flex",gap:6}}>
                          <Btn small variant="secondary" onClick={()=>openEdit(n)}>Edit</Btn>
                          <Btn small variant="danger" onClick={()=>del(n.id)}>✕</Btn>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      {/* Add / Edit Modal */}
      {showForm && (
        <Modal title={editItem?"Edit Notice":"Add Notice"} onClose={()=>setShowForm(false)} width={580}>
          <div style={{display:"flex",flexDirection:"column",gap:14}}>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
              <Select label="Category" required options={NOTICE_CATEGORIES.map(c=>({label:c,value:c}))} {...F("category")}/>
              <Select label="Entity (optional)" options={entities.map(e=>({label:e.name,value:String(e.id)}))} {...F("entity_id")}/>
            </div>
            <Input label="Notice Reference Number" placeholder="e.g. GSTIN/2024/25/001" {...F("notice_ref")}/>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
              <Input label="Notice Date" type="date" {...F("notice_date")}/>
              <Input label="Reply Due Date" type="date" required helpText="Deadline to respond to this notice" {...F("due_date")}/>
            </div>
            <Input label="Description" placeholder="Brief description of the notice" {...F("description")}/>
            <Select label="Status" options={NOTICE_STATUS_OPTS} {...F("status")}/>
            {(form.status==="replied"||form.status==="closed") && (
              <>
                <Input label="Date of Reply" type="date" {...F("reply_date")}/>
                <Input label="Remarks" placeholder="Reply summary or outcome notes" {...F("remarks")}/>
              </>
            )}
            {/* Attachments */}
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
              <div>
                <label style={{fontSize:13,fontWeight:600,color:C.text,display:"block",marginBottom:6}}>Attach Notice Document</label>
                <input ref={noticeRef} type="file" onChange={e=>handleFile(e,"notice")} accept=".pdf,.doc,.docx,.jpg,.png" style={{width:"100%",padding:"6px",border:"1px solid "+C.border,borderRadius:8,fontSize:12}}/>
                {(noticeFile||editItem?.notice_filename) && <div style={{fontSize:11,color:C.green,marginTop:3}}>✓ {noticeFile?.name||editItem?.notice_filename}</div>}
              </div>
              <div>
                <label style={{fontSize:13,fontWeight:600,color:C.text,display:"block",marginBottom:6}}>Attach Reply Document</label>
                <input ref={replyRef} type="file" onChange={e=>handleFile(e,"reply")} accept=".pdf,.doc,.docx,.jpg,.png" style={{width:"100%",padding:"6px",border:"1px solid "+C.border,borderRadius:8,fontSize:12}}/>
                {(replyFile||editItem?.reply_filename) && <div style={{fontSize:11,color:C.green,marginTop:3}}>✓ {replyFile?.name||editItem?.reply_filename}</div>}
              </div>
            </div>
          </div>
          <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
            <Btn variant="secondary" onClick={()=>setShowForm(false)}>Cancel</Btn>
            <Btn onClick={save} disabled={!form.due_date}>{editItem?"Save Changes":"Add Notice"}</Btn>
          </div>
        </Modal>
      )}

      {toast && <Toast msg={toast.msg} type={toast.type} onClose={()=>setToast(null)}/>}
    </div>
  );
};

// ── Library Page ─────────────────────────────────────────────────────────────
const LibraryPage = () => {
  const [books,setBooks]       = useState([]);
  const [search,setSearch]     = useState("");
  const [showForm,setShowForm] = useState(false);
  const [editItem,setEditItem] = useState(null);
  const [form,setForm]         = useState({book_name:"",author:"",location:"",comments:""});
  const [photo,setPhoto]       = useState(null);
  const [toast,setToast]       = useState(null);
  const [viewPhoto,setViewPhoto] = useState(null);
  const photoRef = useRef();

  const load = () => GET("/api/library").then(r => { if(r.ok) setBooks(r.books); });
  useEffect(()=>{ load(); },[]);

  const openAdd  = () => { setEditItem(null); setForm({book_name:"",author:"",location:"",comments:""}); setPhoto(null); setShowForm(true); };
  const openEdit = b  => { setEditItem(b); setForm({book_name:b.book_name,author:b.author||"",location:b.location||"",comments:b.comments||""}); setPhoto(null); setShowForm(true); };

  const save = async () => {
    if (!form.book_name) return;
    const payload = {...form, photo_name:photo?.name||(editItem?.photo_name||""), photo_data:photo?.data||""};
    if (editItem) await PUT(`/api/library/${editItem.id}`, payload);
    else          await POST("/api/library", payload);
    setShowForm(false); load();
    setToast({msg:editItem?"Book updated":"Book added", type:"success"});
  };

  const del = async id => { await DEL(`/api/library/${id}`); load(); setToast({msg:"Book deleted",type:"success"}); };

  const viewPic = async id => {
    const r = await GET(`/api/library/${id}/photo`);
    if (r.ok && r.data) setViewPhoto({data:r.data,name:r.filename});
  };

  const filtered = books.filter(b => !search ||
    b.book_name.toLowerCase().includes(search.toLowerCase()) ||
    (b.author||"").toLowerCase().includes(search.toLowerCase()) ||
    (b.location||"").toLowerCase().includes(search.toLowerCase())
  );

  const F = k => ({value:form[k], onChange:v=>setForm(p=>({...p,[k]:v}))});

  return (
    <div style={{padding:28}}>
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:24}}>
        <div>
          <h1 style={{fontSize:22,fontWeight:800,color:C.navy}}>Library</h1>
          <p style={{color:C.muted,marginTop:4}}>Manage your book collection — {books.length} book{books.length!==1?"s":""} catalogued</p>
        </div>
        <Btn onClick={openAdd}>+ Add Book</Btn>
      </div>

      <Card style={{marginBottom:20,padding:"12px 16px"}}>
        <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search by book name, author or location…"
          style={{width:"100%",padding:"9px 12px",border:"1px solid "+C.border,borderRadius:8,fontSize:14,outline:"none"}}/>
      </Card>

      {filtered.length===0 ? (
        <EmptyState icon="📚" title="No books" subtitle="Start cataloguing your library collection." action={<Btn onClick={openAdd}>Add Book</Btn>}/>
      ) : (
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(280px,1fr))",gap:16}}>
          {filtered.map(b=>(
            <Card key={b.id} style={{padding:20,display:"flex",flexDirection:"column",gap:10}}>
              {b.photo_name && (
                <div style={{height:120,borderRadius:8,overflow:"hidden",background:C.light,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}} onClick={()=>viewPic(b.id)}>
                  <span style={{fontSize:36}}>📷</span>
                  <span style={{fontSize:12,color:C.muted,marginLeft:8}}>{b.photo_name}</span>
                </div>
              )}
              <div>
                <div style={{fontWeight:700,fontSize:16,color:C.navy}}>{b.book_name}</div>
                {b.author&&<div style={{fontSize:13,color:C.slate,marginTop:2}}>by {b.author}</div>}
              </div>
              {b.location&&(
                <div style={{display:"flex",alignItems:"center",gap:6,fontSize:13,color:C.muted}}>
                  <span>📍</span><span>{b.location}</span>
                </div>
              )}
              {b.comments&&<div style={{fontSize:12,color:C.muted,fontStyle:"italic"}}>{b.comments}</div>}
              <div style={{display:"flex",gap:8,marginTop:"auto",paddingTop:8,borderTop:"1px solid "+C.border}}>
                <Btn small variant="secondary" onClick={()=>openEdit(b)}>✏️ Edit</Btn>
                <Btn small variant="danger" onClick={()=>del(b.id)}>🗑 Delete</Btn>
              </div>
            </Card>
          ))}
        </div>
      )}

      {showForm&&(
        <Modal title={editItem?"Edit Book":"Add Book"} onClose={()=>setShowForm(false)} width={480}>
          <div style={{display:"flex",flexDirection:"column",gap:14}}>
            <Input label="Book Name" required placeholder="e.g. Companies Act 2013 Commentary" {...F("book_name")}/>
            <Input label="Author" placeholder="e.g. Dr. K.R. Chandratre" {...F("author")}/>
            <Input label="Location" placeholder="e.g. Shelf A2, Row 3" {...F("location")}/>
            <Textarea label="Comments" placeholder="Optional notes about the book" rows={2} {...F("comments")}/>
            <div>
              <label style={{fontSize:13,fontWeight:600,color:C.text,display:"block",marginBottom:6}}>Photo (optional)</label>
              <input ref={photoRef} type="file" accept=".jpg,.jpeg,.png,.webp" onChange={async e=>{const f=e.target.files[0];if(f){const r=await readFileAsBase64(f);setPhoto(r);}}} style={{width:"100%",padding:"6px",border:"1px solid "+C.border,borderRadius:8,fontSize:12}}/>
              {(photo||editItem?.photo_name)&&<div style={{fontSize:11,color:C.green,marginTop:3}}>✓ {photo?.name||editItem?.photo_name}</div>}
            </div>
          </div>
          <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
            <Btn variant="secondary" onClick={()=>setShowForm(false)}>Cancel</Btn>
            <Btn onClick={save} disabled={!form.book_name}>{editItem?"Save Changes":"Add Book"}</Btn>
          </div>
        </Modal>
      )}

      {viewPhoto&&(
        <Modal title="Book Photo" onClose={()=>setViewPhoto(null)} width={500}>
          <img src={"data:image/jpeg;base64,"+viewPhoto.data} alt={viewPhoto.name} style={{width:"100%",borderRadius:8}}/>
        </Modal>
      )}

      {toast&&<Toast msg={toast.msg} type={toast.type} onClose={()=>setToast(null)}/>}
    </div>
  );
};

// ── File Management Page ──────────────────────────────────────────────────────
const FileMgmtPage = () => {
  const [files,setFiles]       = useState([]);
  const [search,setSearch]     = useState("");
  const [showForm,setShowForm] = useState(false);
  const [editItem,setEditItem] = useState(null);
  const [form,setForm]         = useState({file_number:"",entity_name:"",location:"",description:""});
  const [toast,setToast]       = useState(null);
  const [numError,setNumError] = useState("");

  const load = (q) => {
    const url = q ? `/api/office-files?search=${encodeURIComponent(q)}` : "/api/office-files";
    GET(url).then(r => { if(r.ok) setFiles(r.files); });
  };
  useEffect(()=>{ load(); },[]);
  useEffect(()=>{ const t=setTimeout(()=>load(search),300); return()=>clearTimeout(t); },[search]);

  const openAdd  = () => { setEditItem(null); setForm({file_number:"",entity_name:"",location:"",description:""}); setNumError(""); setShowForm(true); };
  const openEdit = f  => { setEditItem(f); setForm({file_number:f.file_number,entity_name:f.entity_name,location:f.location||"",description:f.description||""}); setNumError(""); setShowForm(true); };

  const save = async () => {
    if (!form.file_number||!form.entity_name){setNumError("File number and name are required.");return;}
    if (!/^\d{3}$/.test(form.file_number.trim())&&!editItem){setNumError("File number must be exactly 3 digits (e.g. 001, 042, 100).");return;}
    setNumError("");
    const res = editItem ? await PUT(`/api/office-files/${editItem.id}`,form) : await POST("/api/office-files",form);
    if (res.ok) { setShowForm(false); load(search); setToast({msg:editItem?"File updated":"File added",type:"success"}); }
    else setNumError(res.error||"Failed.");
  };

  const del = async id => { await DEL(`/api/office-files/${id}`); load(search); setToast({msg:"File deleted",type:"success"}); };

  const F = k => ({value:form[k], onChange:v=>setForm(p=>({...p,[k]:v}))});

  return (
    <div style={{padding:28}}>
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:24}}>
        <div>
          <h1 style={{fontSize:22,fontWeight:800,color:C.navy}}>File Management</h1>
          <p style={{color:C.muted,marginTop:4}}>Track physical office files with unique 3-digit numbers — {files.length} file{files.length!==1?"s":""} registered</p>
        </div>
        <Btn onClick={openAdd}>+ Register File</Btn>
      </div>

      <Card style={{marginBottom:20,padding:"12px 16px"}}>
        <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search by file number, company name or location…"
          style={{width:"100%",padding:"9px 12px",border:"1px solid "+C.border,borderRadius:8,fontSize:14,outline:"none"}}/>
      </Card>

      {files.length===0 ? (
        <EmptyState icon="🗂️" title="No files registered" subtitle="Register your physical office files with unique 3-digit numbers." action={<Btn onClick={openAdd}>Register File</Btn>}/>
      ) : (
        <Card style={{padding:0,overflow:"hidden"}}>
          <table style={{width:"100%",borderCollapse:"collapse",fontSize:13}}>
            <thead><tr style={{background:C.light}}>
              {["File No.","Company / Individual","Location","Description","Registered On",""].map(h=>(
                <th key={h} style={{padding:"10px 14px",textAlign:"left",fontSize:11,fontWeight:700,color:C.slate,borderBottom:"1px solid "+C.border,whiteSpace:"nowrap"}}>{h}</th>
              ))}
            </tr></thead>
            <tbody>
              {files.map(f=>(
                <tr key={f.id} style={{borderBottom:"1px solid "+C.border}}>
                  <td style={{padding:"12px 14px"}}>
                    <span style={{display:"inline-block",background:C.navy,color:"#fff",borderRadius:8,padding:"4px 12px",fontFamily:"monospace",fontWeight:800,fontSize:15}}>{f.file_number}</span>
                  </td>
                  <td style={{padding:"12px 14px",fontWeight:600,color:C.text}}>{f.entity_name}</td>
                  <td style={{padding:"12px 14px"}}>
                    {f.location?<span style={{display:"inline-flex",alignItems:"center",gap:4,color:C.slate,fontSize:13}}><span>📍</span>{f.location}</span>:<span style={{color:C.muted}}>—</span>}
                  </td>
                  <td style={{padding:"12px 14px",color:C.muted,maxWidth:200}}>{f.description||"—"}</td>
                  <td style={{padding:"12px 14px",color:C.muted,whiteSpace:"nowrap"}}>{fmtDate(f.created_at)}</td>
                  <td style={{padding:"12px 14px"}}>
                    <div style={{display:"flex",gap:6}}>
                      <Btn small variant="secondary" onClick={()=>openEdit(f)}>✏️</Btn>
                      <Btn small variant="danger" onClick={()=>del(f.id)}>✕</Btn>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {showForm&&(
        <Modal title={editItem?"Edit File":"Register New File"} onClose={()=>setShowForm(false)} width={480}>
          {numError&&<div style={{background:"#fee2e2",color:C.red,padding:"10px 14px",borderRadius:8,marginBottom:16,fontSize:13}}>{numError}</div>}
          <div style={{display:"flex",flexDirection:"column",gap:14}}>
            <Input label="File Number (3 digits)" required placeholder="e.g. 001" helpText="Unique 3-digit number assigned to this physical file" {...F("file_number")} disabled={!!editItem}/>
            <Input label="Company / Individual Name" required placeholder="e.g. ABC Private Limited" {...F("entity_name")}/>
            <Input label="Location" placeholder="e.g. Shelf B3, Cabinet 2, Room 101" {...F("location")}/>
            <Input label="Description" placeholder="Brief description of file contents" {...F("description")}/>
          </div>
          <div style={{display:"flex",gap:12,justifyContent:"flex-end",marginTop:24}}>
            <Btn variant="secondary" onClick={()=>setShowForm(false)}>Cancel</Btn>
            <Btn onClick={save}>{editItem?"Save Changes":"Register File"}</Btn>
          </div>
        </Modal>
      )}

      {toast&&<Toast msg={toast.msg} type={toast.type} onClose={()=>setToast(null)}/>}
    </div>
  );
};

// ── Root App ──────────────────────────────────────────────────────────────────
const App = () => {
  const [user,setUser]=useState(()=>{try{return JSON.parse(localStorage.getItem("rcp_user"));}catch{return null;}});
  const [page,setPage]=useState("dashboard");
  const [navEntityId,setNavEntityId]=useState(null);
  const [collapsed,setCollapsed]=useState(false);

  const handleLogin=u=>{setUser(u);setPage("dashboard");};
  const handleLogout=()=>{localStorage.removeItem("rcp_user");setUser(null);};
  const navigate=(p,entityId=null)=>{setPage(p);setNavEntityId(entityId);};

  if (!user) return <LoginScreen onLogin={handleLogin}/>;

  const renderPage=()=>{
    switch(page){
      case "dashboard":  return <Dashboard user={user} onNavigate={navigate}/>;
      case "entities":   return <EntitiesPage user={user} selectedId={navEntityId}/>;
      case "calendar":   return <ComplianceCalendarPage user={user} selectedEntityId={navEntityId}/>;
      case "meetings":   return <BoardMeetingsPage user={user}/>;
      case "vault":      return <PasswordVaultPage user={user}/>;
      case "audit":      return <AuditTrackerPage user={user}/>;
      case "notices":    return <NoticeTrackerPage user={user}/>;
      case "library":    return <LibraryPage/>;
      case "files":      return <FileMgmtPage/>;
      case "admin":      return user.role==="admin"?<AdminPage user={user}/>:<div style={{padding:40,color:C.red}}>Access denied.</div>;
      default:           return <Dashboard user={user} onNavigate={navigate}/>;
    }
  };

  return (
    <div style={{display:"flex",minHeight:"100vh",background:C.light}}>
      <Sidebar page={page} setPage={p=>{setNavEntityId(null);setPage(p);}} user={user} onLogout={handleLogout} collapsed={collapsed} setCollapsed={setCollapsed}/>
      <div style={{flex:1,overflowY:"auto"}}>{renderPage()}</div>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
