/* FinFlow Screens — Settings (profile, security, team, policies, integrations, billing, notifications) */

const SettingsShell = ({ active, setActive, children }) => {
  const tabs = [
    { id:"profile",      label:"Profile",      icon:"user" },
    { id:"security",     label:"Security",     icon:"shield-check" },
    { id:"team",         label:"Team & roles", icon:"users-three" },
    { id:"policies",     label:"Policies",     icon:"scales" },
    { id:"integrations", label:"Integrations", icon:"plugs" },
    { id:"billing",      label:"Billing",      icon:"credit-card" },
    { id:"notif-prefs",  label:"Notifications",icon:"bell" }
  ];
  return (
    <>
      <PageHead eyebrow="Settings" title="Workspace settings" sub="Manage your Reyonal workspace"/>
      <div className="ff-grid" style={{gridTemplateColumns:'220px 1fr', gap:24, alignItems:'flex-start'}}>
        <div className="ff-stack" style={{'--ff-stack-gap':'2px'}}>
          {tabs.filter(t => ffCanAccess('settings-' + t.id)).map(t => (
            <a key={t.id} href="#" onClick={e=>{e.preventDefault();setActive(t.id);}}
               className="ff-nav-item" aria-current={active === t.id ? "page" : undefined}>
              <Icon name={t.icon} size={16}/>{t.label}
            </a>
          ))}
        </div>
        <div>{children}</div>
      </div>
    </>
  );
};

const SettingsProfile = () => {
  const role=ffRole(), person=FF_DATA.me[role];
  FF_SESSION.profiles ||= {};
  const [saved, setSaved] = React.useState(false);
  const [values,setValues] = React.useState(FF_SESSION.profiles[role] || {name:person.name,preferred:person.name.split(' ')[0],title:person.title,department:role==='finance'?'Finance':role==='manager'?'Sales':'Marketing',email:person.email,timezone:'America/Los_Angeles'});
  const [errors,setErrors] = React.useState({});
  const update=(key,value)=>{setValues({...values,[key]:value});setSaved(false);};
  const save=()=>{const next={}; if(!values.name.trim()) next.name='Enter your full name.'; if(!values.title.trim()) next.title='Enter your title.'; if(!values.department.trim()) next.department='Enter your department.'; if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email.trim())) next.email='Enter a valid work email.'; setErrors(next); if(!Object.keys(next).length){FF_SESSION.profiles[role]={...values};setSaved(true);}};
  const field=(key,label,type='text')=><div className="ff-field"><label className="ff-label">{label}{['name','title','department','email'].includes(key)&&<span aria-hidden="true" style={{color:'var(--ff-rejected)'}}> *</span>}</label><input aria-label={label} className="ff-input" type={type} value={values[key]} onChange={e=>update(key,e.target.value)} onBlur={()=>{const bad=key==='email'?!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values[key].trim()):key!=='preferred'&&!values[key].trim();setErrors({...errors,[key]:bad?(key==='email'?'Enter a valid work email.':`Enter your ${label.toLowerCase()}.`):''});}}/><FieldError error={errors[key]}/></div>;
  return <Card title="Profile">
    <div className="ff-row" style={{gap:18, marginBottom:20}}>
      <Avatar initials={person.initials} name={values.name} size="xl"/>
      <div>
        <div style={{fontSize:18, fontWeight:600}}>{values.name}</div>
        <div style={{fontSize:13, color:'var(--ff-fg-muted)'}}>{values.title} · Joined Mar 2023</div>
        <div className="ff-row" style={{marginTop:10, gap:8}}>
          <button className="ff-btn ff-btn--sm" disabled title="Profile photo upload is not available in this prototype.">Upload photo</button>
          <button className="ff-btn ff-btn--sm ff-btn--ghost" disabled title="Profile photo removal is not available in this prototype.">Remove</button>
        </div>
      </div>
    </div>
    <FormSummary errors={errors} title="Check your profile"/><div className="ff-grid ff-grid--2" style={{gap:'14px 18px'}}>
      {field('name','Full name')}{field('preferred','Preferred name')}{field('title','Title')}{field('department','Department')}{field('email','Work email','email')}<div className="ff-field"><label className="ff-label">Time zone</label><select aria-label="Time zone" className="ff-select" value={values.timezone} onChange={e=>update('timezone',e.target.value)}><option>America/Los_Angeles</option><option>America/New_York</option><option>UTC</option></select></div>
    </div>
    <div className="ff-row" style={{marginTop:20, justifyContent:'flex-end', gap:8}}>
      <button className="ff-btn" disabled title="Resetting profile fields is not available in this prototype.">Cancel</button>
      <button className="ff-btn ff-btn--primary" onMouseDown={e=>e.preventDefault()} onClick={save}>Save</button>
    </div>
    <ActionFeedback message={saved ? 'Profile saved' : ''}/>
  </Card>;
};

const SettingsSecurity = () => {
  FF_SESSION.sessions ||= {};
  const [sessions, setSessions] = React.useState(FF_SESSION.sessions[ffRole()] || [
    ['iPhone 15 · FinFlow iOS','San Francisco, CA','2h ago'],
    ['Windows · Edge 128','Austin, TX (VPN)','3d ago']
  ]);
  React.useEffect(()=>{FF_SESSION.sessions[ffRole()]=sessions;},[sessions]);
  const [confirming,setConfirming] = React.useState(null);
  const [message,setMessage] = React.useState('');
  return <div className="ff-stack" style={{'--ff-stack-gap':'16px'}}>
    <Card title="Two-factor authentication">
      <div className="ff-row" style={{justifyContent:'space-between'}}>
        <div>
          <div style={{fontWeight:500}}>Authenticator app · enabled</div>
          <div style={{fontSize:12, color:'var(--ff-fg-muted)'}}>Last used May 22, 9:04 AM</div>
        </div>
        <button className="ff-btn" disabled title="Security reconfiguration is not available in this prototype.">Reconfigure</button>
      </div>
      <hr className="ff-divider"/>
      <div className="ff-row" style={{justifyContent:'space-between'}}>
        <div>
          <div style={{fontWeight:500}}>Hardware key (YubiKey)</div>
          <div style={{fontSize:12, color:'var(--ff-fg-muted)'}}>Not configured</div>
        </div>
        <button className="ff-btn ff-btn--primary" disabled title="Hardware key setup is not available in this prototype.">Add key</button>
      </div>
    </Card>
    <div>
      <div className="ff-row" style={{padding:'0 0 10px'}}><span style={{fontSize:15, fontWeight:600}}>Active sessions</span></div>
      <table className="ff-table">
        <thead><tr><th>Device</th><th>Location</th><th>Last active</th><th></th></tr></thead>
        <tbody>
          <tr><td><Icon name="laptop" size={14}/> MacBook Pro · Chrome 128</td><td>San Francisco, CA</td><td className="ff-tnum">Now</td><td><StatusBadge status="active"/></td></tr>
          {sessions.map(([device, location, active]) => <tr key={device}><td><Icon name={device.startsWith('iPhone') ? 'device-mobile' : 'laptop'} size={14}/> {device}</td><td>{location}</td><td className="ff-tnum">{active}</td><td><button className="ff-btn ff-btn--ghost ff-btn--sm" onClick={()=>setConfirming({device,location})}>Revoke</button></td></tr>)}
        </tbody>
      </table>
    </div>
    <Card title="API keys" action={<button className="ff-btn ff-btn--sm" disabled title="API key creation is not available in this prototype.">+ New key</button>}>
      <div className="ff-row" style={{justifyContent:'space-between', fontSize:13}}>
        <div><div style={{fontWeight:500}} className="ff-mono">ff_live_••••91kx</div><div style={{fontSize:11, color:'var(--ff-fg-muted)'}}>QuickBooks sync · created Apr 2</div></div>
        <button className="ff-btn ff-btn--sm ff-btn--ghost" disabled title="API key rotation is not available in this prototype.">Rotate</button>
      </div>
    </Card>
    <ActionFeedback message={message}/>{confirming && <ConfirmDialog title="Revoke session?" body={`This will sign out ${confirming.device} in ${confirming.location}.`} onCancel={()=>setConfirming(null)} onConfirm={()=>{setSessions(current=>current.filter(row=>row[0] !== confirming.device));setConfirming(null);setMessage('Session revoked.');}}/>}
  </div>;
};

const SettingsTeam = () => (
  <div>
    <div className="ff-row" style={{padding:'0 0 10px'}}><span style={{fontSize:15, fontWeight:600}}>Team & roles</span><div style={{flex:1}}/><button className="ff-btn ff-btn--sm ff-btn--primary" disabled title="Inviting members is not available in this prototype."><Icon name="user-plus" size={12}/> Invite</button></div>
    <table className="ff-table">
      <thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Last active</th><th></th></tr></thead>
      <tbody>
        {[
          ["Morgan Ellis","Finance Admin","morgan.ellis@reyonal.com","Now"],
          ["Taylor Brooks","Manager","taylor.brooks@reyonal.com","12 minutes ago"],
          ["Casey Parker","Employee","casey.parker@reyonal.com","2 hours ago"],
          ["Jordan Lee","Employee","jordan.lee@reyonal.com","4 hours ago"],
          ["Quinn Avery","Employee","quinn.avery@reyonal.com","Yesterday"],
          ["Alex Morgan","Employee","alex.morgan@reyonal.com","Yesterday"],
          ["Avery Quinn","Employee","avery.quinn@reyonal.com","2 days ago"],
          ["Devon Hayes","Auditor","devon.hayes@reyonal.com","1 week ago"],
          ["Riley Bennett","Employee","riley.bennett@reyonal.com","1 week ago"],
          ["Sam Foster","Employee","sam.foster@reyonal.com","3 days ago"]
        ].map(([n, role, em, la], i) => (
          <tr key={i}>
            <td><span className="ff-row" style={{gap:8}}><Avatar initials={n.split(' ').map(x=>x[0]).join('').slice(0,2)} name={n}/>{n}</span></td>
            <td style={{color:'var(--ff-fg-muted)'}}>{em}</td>
            <td><span className="ff-badge ff-badge--primary ff-badge--no-dot">{role}</span></td>
            <td className="ff-tnum" style={{color:'var(--ff-fg-muted)'}}>{la}</td>
            <td><button className="ff-btn ff-btn--ghost ff-btn--sm" disabled title="Member editing is not available in this prototype.">Edit</button></td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);

const SettingsPolicies = () => {
  const d = FF_DATA;
  return (
    <div>
      <div className="ff-row" style={{padding:'0 0 10px'}}><span style={{fontSize:15, fontWeight:600}}>Policies</span><div style={{flex:1}}/><button className="ff-btn ff-btn--sm ff-btn--primary" disabled title="Policy creation is not available in this prototype."><Icon name="plus" size={12}/> New policy</button></div>
      <table className="ff-table">
        <thead><tr><th>Policy</th><th>Limit / rule</th><th>Scope</th><th>Last edited</th><th></th></tr></thead>
        <tbody>
          {d.policies.map((p, i) => (
            <tr key={i}>
              <td><strong>{p.name}</strong></td>
              <td>{p.limit}</td>
              <td><span className="ff-badge ff-badge--neutral ff-badge--no-dot">{p.scope}</span></td>
              <td className="ff-tnum" style={{color:'var(--ff-fg-muted)'}}>{p.lastEdit}</td>
              <td><button className="ff-btn ff-btn--ghost ff-btn--sm" disabled title="Policy editing is not available in this prototype.">Edit</button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

const SettingsIntegrations = () => {
  const d = FF_DATA;
  const [message, setMessage] = React.useState("");
  const toggle = (integration) => {
    integration.status = integration.status === "connected" ? "available" : "connected";
    integration.lastSync = integration.status === "connected" ? "Just now" : "—";
    setMessage(`${integration.name} ${integration.status === "connected" ? "connected (demo)" : "disconnected"}.`);
  };
  return (
    <>
    {message && <div role="status" className="ff-alert ff-alert--info" style={{marginBottom:16}}>{message}</div>}
    <div className="ff-grid ff-grid--3">
      {d.integrations.map((i, k) => (
        <Card key={k}>
          <div className="ff-row" style={{justifyContent:'space-between', marginBottom:10}}>
            <div className="ff-row" style={{gap:10}}>
              <div style={{width:36, height:36, borderRadius:8, background:'var(--ff-card-2)', display:'grid', placeItems:'center', border:'1px solid var(--ff-border)'}}>
                {i.brand ? <BrandIcon name={i.brand} size={20}/> : <Icon name={i.icon} size={18}/>}
              </div>
              <div>
                <div style={{fontWeight:600}}>{i.name}</div>
                <div style={{fontSize:11, color:'var(--ff-fg-muted)'}}>Last sync · {i.lastSync}</div>
              </div>
            </div>
            <StatusBadge status={i.status}/>
          </div>
          <p style={{margin:'8px 0 14px', fontSize:13, color:'var(--ff-fg-muted)'}}>
            {{
              "QuickBooks":"Sync expenses, vendors, and reimbursements to QuickBooks Online.",
              "Wise":"Pull statements; fund reimbursements from operating account.",
              "Brex":"Import card transactions and statements automatically.",
              "Xero":"Sync to Xero GL for monthly close.",
              "Google Chat":"Approve and review expenses inline in Google Chat.",
              "Okta SSO":"Single sign-on with SCIM provisioning."
            }[i.name]}
          </p>
          <button className={`ff-btn ff-btn--sm ${i.status === "connected" ? "" : "ff-btn--primary"}`} style={{width:'100%'}} onClick={()=>toggle(i)}>
            {i.status === "connected" ? "Manage" : "Connect"}
          </button>
        </Card>
      ))}
    </div>
    </>
  );
};

const SettingsBilling = () => (
  <div className="ff-stack" style={{'--ff-stack-gap':'16px'}}>
    <Card title="Plan">
      <div className="ff-row" style={{justifyContent:'space-between', alignItems:'flex-start'}}>
        <div>
          <div style={{fontFamily:'var(--ff-font-sans)', fontWeight:600, fontSize:24, letterSpacing:'-0.025em'}}>FinFlow Scale</div>
          <div style={{color:'var(--ff-fg-muted)', fontSize:13, marginTop:4}}>$15 / user / month · billed annually</div>
          <div className="ff-row" style={{gap:6, marginTop:10}}>
            <StatusBadge status="active"/>
            <span className="ff-badge ff-badge--neutral">Renews Jan 14, 2027</span>
          </div>
        </div>
        <div>
          <button className="ff-btn" disabled title="Plan changes are not available in this prototype.">Compare plans</button>
          <button className="ff-btn ff-btn--primary" style={{marginLeft:8}} disabled title="Seat changes are not available in this prototype.">Add seats</button>
        </div>
      </div>
    </Card>
    <Card title="Payment method">
      <div className="ff-row" style={{justifyContent:'space-between', alignItems:'center'}}>
        <div className="ff-row" style={{gap:14, alignItems:'center'}}>
          <div style={{
            width:72, aspectRatio:'1.586 / 1', borderRadius:6, padding:'8px 9px',
            background:'linear-gradient(135deg, var(--ff-blue-700), var(--ff-blue-900))',
            display:'flex', flexDirection:'column', justifyContent:'space-between',
          }}>
            <div style={{width:14, height:10, borderRadius:2, background:'linear-gradient(135deg, #e8d48a, #c9a94f)'}}/>
            <BrandIcon name="visa" size={22} style={{filter:'brightness(0) invert(1)'}}/>
          </div>
          <div>
            <div style={{fontWeight:500}} className="ff-mono">•••• •••• •••• 4242</div>
            <div style={{fontSize:11, color:'var(--ff-fg-muted)'}}>Visa · expires 11/27</div>
          </div>
        </div>
        <button className="ff-btn" disabled title="Payment method updates are not available in this prototype.">Update</button>
      </div>
    </Card>
    <div>
      <div className="ff-row" style={{padding:'0 0 10px'}}><span style={{fontSize:15, fontWeight:600}}>Invoices</span></div>
      <table className="ff-table">
        <thead><tr><th>Invoice</th><th>Date</th><th className="ff-num">Amount</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {[["INV-2026-005","May 14",3720,"paid"],["INV-2026-004","Apr 14",3720,"paid"],["INV-2026-003","Mar 14",3525,"paid"]].map(([id, dt, a, s], i) => (
            <tr key={i}><td className="ff-mono" style={{fontSize:12}}>{id}</td><td>{dt}</td><td className="ff-num"><Money value={a}/></td><td><StatusBadge status={s}/></td><td><button className="ff-btn ff-btn--ghost ff-btn--sm" disabled title="Invoice downloads are not available in this prototype.">PDF</button></td></tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

const SettingsNotifPrefs = () => {
  const defaults = [['Expense submitted to me',true,true,false],['Policy flag on my expense',true,true,true],['Approval decision',true,false,true],['Reimbursement scheduled',true,true,false],['Weekly digest',true,false,false],['Card transaction over $250',true,true,true]];
  FF_SESSION.notificationPrefs ||= {};
  const [prefs,setPrefs]=React.useState(FF_SESSION.notificationPrefs[ffRole()] || defaults.map(([,a,b,c])=>[a,b,c])); const [message,setMessage]=React.useState('');
  React.useEffect(()=>{FF_SESSION.notificationPrefs[ffRole()]=prefs;},[prefs]);
  return <Card title="Notification preferences"><ActionFeedback message={message}/>
    {[
      ["Expense submitted to me", true, true, false],
      ["Policy flag on my expense", true, true, true],
      ["Approval decision", true, false, true],
      ["Reimbursement scheduled", true, true, false],
      ["Weekly digest", true, false, false],
      ["Card transaction over $250", true, true, true]
    ].map(([label], i, arr) => (
      <div key={i} className="ff-row" style={{padding:'12px 0', borderBottom: i < arr.length-1 ? '1px solid var(--ff-border)' : '0'}}>
        <div style={{flex:1}}>{label}</div>
        <label className="ff-row" style={{gap:6, fontSize:12, minWidth:80}}><input type="checkbox" checked={prefs[i][0]} onChange={e=>{const n=prefs.map((p,j)=>j===i?[e.target.checked,p[1],p[2]]:p);setPrefs(n);setMessage('Notification preference updated.');}}/> Email</label>
        <label className="ff-row" style={{gap:6, fontSize:12, minWidth:80}}><input type="checkbox" checked={prefs[i][1]} onChange={e=>{const n=prefs.map((p,j)=>j===i?[p[0],e.target.checked,p[2]]:p);setPrefs(n);setMessage('Notification preference updated.');}}/> Google Chat</label>
        <label className="ff-row" style={{gap:6, fontSize:12, minWidth:80}}><input type="checkbox" checked={prefs[i][2]} onChange={e=>{const n=prefs.map((p,j)=>j===i?[p[0],p[1],e.target.checked]:p);setPrefs(n);setMessage('Notification preference updated.');}}/> Push</label>
      </div>
    ))}
  </Card>;
};

Object.assign(window, { SettingsShell, SettingsProfile, SettingsSecurity, SettingsTeam, SettingsPolicies, SettingsIntegrations, SettingsBilling, SettingsNotifPrefs });
