// nvx-settings.jsx — Astrail Settings Module
// Sections: General · Members & Roles · Approval Policy · Wallets · Notifications · Security · Billing

// ─────────────────────────────────────────────────────────────────
// Shared layout primitives
// ─────────────────────────────────────────────────────────────────

const FormRow = ({ label, hint, children, noBorder = false }) =>
<div style={{
  display: 'grid', gridTemplateColumns: '196px 1fr', gap: 32,
  padding: '18px 0', alignItems: 'start',
  borderBottom: noBorder ? 'none' : '1px solid var(--col-border-s)'
}}>
    <div>
      <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--col-text)', lineHeight: 1.4 }}>{label}</div>
      {hint && <div style={{ fontSize: 12, color: 'var(--col-text-3)', marginTop: 4, lineHeight: 1.5 }}>{hint}</div>}
    </div>
    <div>{children}</div>
  </div>;


const SectionHead = ({ title, desc, action }) =>
<div style={{ marginBottom: 24 }}>
    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
      <div>
        <h2 style={{ fontSize: 18, fontWeight: 600, color: 'var(--col-text)', letterSpacing: '-0.015em', marginBottom: 4 }}>{title}</h2>
        {desc && <p style={{ fontSize: 14, color: 'var(--col-text-2)', lineHeight: 1.6, maxWidth: 500, margin: 0 }}>{desc}</p>}
      </div>
      {action && <div style={{ flexShrink: 0 }}>{action}</div>}
    </div>
  </div>;


const SInput = ({ value, onChange, placeholder, type = 'text', disabled, readOnly, style }) => {
  const [f, setF] = React.useState(false);
  return (
    <input type={type} value={value} readOnly={readOnly} disabled={disabled}
    onChange={onChange ? (e) => onChange(e.target.value) : undefined}
    placeholder={placeholder}
    onFocus={() => setF(true)} onBlur={() => setF(false)}
    style={{
      height: 40, width: '100%', padding: '0 12px',
      border: `1.5px solid ${f ? 'var(--col-accent)' : 'var(--col-border)'}`,
      borderRadius: 9, outline: 'none', fontFamily: 'inherit',
      fontSize: 14, color: disabled ? 'var(--col-text-dis)' : 'var(--col-text)',
      background: disabled || readOnly ? 'var(--col-surface-2)' : 'var(--col-surface)',
      transition: 'border-color 150ms ease', cursor: readOnly ? 'default' : 'text',
      ...style
    }} />);


};

const SSelect = ({ value, onChange, options, style }) => {
  const [f, setF] = React.useState(false);
  return (
    <select value={value} onChange={(e) => onChange(e.target.value)}
    onFocus={() => setF(true)} onBlur={() => setF(false)}
    style={{
      height: 40, width: '100%', padding: '0 32px 0 12px',
      border: `1.5px solid ${f ? 'var(--col-accent)' : 'var(--col-border)'}`,
      borderRadius: 9, outline: 'none', fontFamily: 'inherit',
      fontSize: 14, color: 'var(--col-text)', background: 'var(--col-surface)',
      appearance: 'none', cursor: 'pointer', transition: 'border-color 150ms ease',
      backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8' fill='none'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%238A8480' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")`,
      backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center',
      ...style
    }}>
      {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>);

};

const SToggle = ({ value, onChange, disabled }) =>
<div onClick={() => !disabled && onChange(!value)} style={{
  width: 40, height: 22, borderRadius: 999, position: 'relative',
  background: value ? 'var(--col-accent)' : 'var(--col-border-str)',
  cursor: disabled ? 'not-allowed' : 'pointer',
  opacity: disabled ? 0.4 : 1,
  transition: 'background 200ms ease', flexShrink: 0
}}>
    <div style={{
    position: 'absolute', top: 3, width: 16, height: 16, borderRadius: 50,
    left: value ? 21 : 3, background: 'white',
    boxShadow: '0 1px 4px rgba(0,0,0,0.20)',
    transition: 'left 180ms cubic-bezier(0.4,0,0.2,1)'
  }} />
  </div>;


const RoleMeta = {
  owner: { label: 'Owner', color: 'var(--col-accent)', bg: 'var(--col-accent-50)' },
  approver: { label: 'Approver', color: 'var(--col-processing)', bg: 'var(--col-processing-bg)' },
  accountant: { label: 'Accountant', color: 'var(--col-success)', bg: 'var(--col-success-bg)' },
  viewer: { label: 'Viewer', color: 'var(--col-draft)', bg: 'var(--col-draft-bg)' }
};

const RBadge = ({ role }) => {
  const m = RoleMeta[role] || RoleMeta.viewer;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', padding: '3px 9px', borderRadius: 999, fontSize: 12, fontWeight: 500, background: m.bg, color: m.color }}>
      {m.label}
    </span>);

};

// Inline icon helper (uses global Icon from nvx-icons.jsx)
const SI = ({ d, size = 15 }) => <Icon d={d} size={size} color="currentColor" strokeWidth={1.8} />;

// ─────────────────────────────────────────────────────────────────
// GENERAL
// ─────────────────────────────────────────────────────────────────
const GeneralSettings = ({ addToast }) => {
  const [name, setName] = React.useState('Acme Corp');
  const [currency, setCurrency] = React.useState('USDT');
  const [tz, setTz] = React.useState('Europe/Warsaw');
  const WS_ID = 'ws_k7m3n9p2q8f4';

  const save = () => addToast('Workspace settings saved', 'success');
  const copyId = () => {navigator.clipboard?.writeText(WS_ID);addToast('Workspace ID copied', 'success');};

  return (
    <div>
      <SectionHead title="General" desc="Basic workspace configuration visible to all members." />

      <div className="card card-pad" style={{ borderRadius: 16 }}>
        {/* Logo placeholder */}
        <FormRow label="Workspace logo" hint="Square image, at least 128 × 128 px.">
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 56, height: 56, borderRadius: 14, border: '1.5px dashed var(--col-border)', background: 'var(--col-surface-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--col-text-3)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="3" width="18" height="18" rx="4" />
                <circle cx="8.5" cy="8.5" r="1.5" fill="var(--col-text-3)" stroke="none" />
                <path d="M21 15l-5-5L5 21" />
              </svg>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <button className="btn btn-secondary btn-sm" onClick={() => addToast('File upload coming soon', 'success')}>
                <SI d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12" size={13} />
                Upload image
              </button>
              <span style={{ fontSize: 12, color: 'var(--col-text-3)' }}>PNG or SVG · max 2 MB</span>
            </div>
          </div>
        </FormRow>

        <FormRow label="Workspace name" hint="Shown to all members in the sidebar.">
          <SInput value={name} onChange={setName} placeholder="Your company name" />
        </FormRow>

        <FormRow label="Default currency" hint="Used as the default asset when creating payroll runs.">
          <SSelect value={currency} onChange={setCurrency} options={[
          { value: 'USDT', label: 'USDT — Tether' },
          { value: 'USDC', label: 'USDC — USD Coin' },
          { value: 'USDT_TRX', label: 'USDT on Tron' }]
          } />
        </FormRow>

        <FormRow label="Timezone" hint="Used for scheduled payroll runs and reporting periods.">
          <SSelect value={tz} onChange={setTz} options={[
          { value: 'Europe/Warsaw', label: 'Europe/Warsaw (UTC+2)' },
          { value: 'Europe/Kyiv', label: 'Europe/Kyiv (UTC+3)' },
          { value: 'Europe/Prague', label: 'Europe/Prague (UTC+2)' },
          { value: 'UTC', label: 'UTC' },
          { value: 'America/New_York', label: 'America/New_York (UTC-4)' }]
          } />
        </FormRow>

        <FormRow label="Workspace ID" hint="Reference this ID when contacting support." noBorder>
          <div style={{ display: 'flex', gap: 8 }}>
            <SInput value={WS_ID} readOnly style={{ fontFamily: "'SF Mono','Fira Code',monospace", fontSize: 12, color: 'var(--col-text-2)' }} />
            <button className="btn btn-secondary btn-sm" style={{ height: 40, flexShrink: 0 }} onClick={copyId}>Copy</button>
          </div>
        </FormRow>
      </div>

      <div style={{ marginTop: 14, display: 'flex', justifyContent: 'flex-end' }}>
        <button className="btn btn-primary btn-md" onClick={save}>Save changes</button>
      </div>

      <div style={{ marginTop: 40 }}>
        <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--col-text-3)', marginBottom: 12 }}>Danger zone</div>
        <div style={{ border: '1px solid var(--col-error-border)', borderRadius: 12, padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 16, justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--col-text)' }}>Delete workspace</div>
            <div style={{ fontSize: 13, color: 'var(--col-text-3)', marginTop: 2 }}>Permanently remove all data. This cannot be undone.</div>
          </div>
          <button className="btn btn-destructive btn-sm" style={{ flexShrink: 0 }} onClick={() => addToast('Contact support to delete your workspace.', 'error')}>Delete workspace</button>
        </div>
      </div>
    </div>);

};

// ─────────────────────────────────────────────────────────────────
// MEMBERS
// ─────────────────────────────────────────────────────────────────
const INIT_MEMBERS = [
{ id: 1, name: 'Alice Johnson', email: 'alice@acme.com', role: 'owner', status: 'active', joined: 'Jan 15, 2026', isYou: true },
{ id: 2, name: 'Boris Kovalev', email: 'boris@acme.com', role: 'approver', status: 'active', joined: 'Jan 15, 2026', isYou: false },
{ id: 3, name: 'Carol Dubois', email: 'carol@acme.com', role: 'accountant', status: 'active', joined: 'Feb 3, 2026', isYou: false },
{ id: 4, name: 'David Lee', email: 'david@acme.com', role: 'viewer', status: 'pending', joined: 'May 10, 2026', isYou: false }];


const MembersSettings = ({ addToast }) => {
  const [members, setMembers] = React.useState(INIT_MEMBERS);
  const [showInvite, setShowInvite] = React.useState(false);
  const [inviteEmail, setInviteEmail] = React.useState('');
  const [inviteRole, setInviteRole] = React.useState('viewer');
  const [removeTarget, setRemove] = React.useState(null);
  const [roleChangeTarget, setRoleChangeTarget] = React.useState(null);

  const changeRole = (id, role) => {
    setMembers((p) => p.map((m) => m.id === id ? { ...m, role } : m));
    addToast('Role updated', 'success');
  };
  const doRemove = (id) => {
    setMembers((p) => p.filter((m) => m.id !== id));
    setRemove(null);
    addToast('Member removed', 'success');
  };
  const sendInvite = () => {
    if (!inviteEmail.trim()) return;
    setMembers((p) => [...p, { id: Date.now(), name: inviteEmail.split('@')[0], email: inviteEmail, role: inviteRole, status: 'pending', joined: 'Today', isYou: false }]);
    setShowInvite(false);setInviteEmail('');
    addToast(`Invite sent to ${inviteEmail}`, 'success');
  };

  return (
    <div>
      <SectionHead
        title="Members & Roles"
        desc="Manage who has access to this workspace and their permissions."
        action={
        <button className="btn btn-primary btn-md" onClick={() => setShowInvite(true)}>
            <IcoPlus size={13} /> Invite member
          </button>
        } />
      

      {/* Role legend */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 8, marginBottom: 18 }}>
        {Object.entries(RoleMeta).map(([key, m]) =>
        <div key={key} style={{ padding: '10px 14px', borderRadius: 11, border: '1px solid var(--col-border-s)', background: 'var(--col-surface)', display: 'flex', flexDirection: 'column', gap: 4 }}>
            <RBadge role={key} />
            <div style={{ fontSize: 12, color: 'var(--col-text-3)', lineHeight: 1.4 }}>
              {{ owner: 'Full access — invite, approve, broadcast', approver: 'Sign and approve payroll runs', accountant: 'Draft runs, manage address book', viewer: 'Read-only access to all data' }[key]}
            </div>
          </div>
        )}
      </div>

      {/* Table */}
      <div className="card" style={{ overflow: 'hidden', borderRadius: 16 }}>
        <table className="data-table">
          <thead>
            <tr>
              <th>Member</th>
              <th style={{ width: 140 }}>Role</th>
              <th style={{ width: 110 }}>Status</th>
              <th style={{ width: 110 }}>Joined</th>
              <th style={{ width: 44 }}></th>
            </tr>
          </thead>
          <tbody>
            {members.map((m) =>
            <tr key={m.id} style={{ cursor: 'default' }}>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <Avatar name={m.name} size="sm" />
                    <div>
                      <div style={{ fontWeight: 500, fontSize: 14, color: 'var(--col-text)', display: 'flex', alignItems: 'center', gap: 6 }}>
                        {m.name}
                        {m.isYou && <span style={{ fontSize: 11, color: 'var(--col-accent)', fontWeight: 600 }}>You</span>}
                      </div>
                      <div style={{ fontSize: 12, color: 'var(--col-text-3)' }}>{m.email}</div>
                    </div>
                  </div>
                </td>
                <td>
                  {m.isYou ?
                <RBadge role={m.role} /> :

                <select value={m.role} onChange={(e) => setRoleChangeTarget({ member: m, newRole: e.target.value })}
                style={{ padding: '4px 8px', borderRadius: 7, border: '1px solid var(--col-border)', background: 'var(--col-surface)', color: 'var(--col-text)', fontSize: 13, fontFamily: 'inherit', cursor: 'pointer', outline: 'none' }}>
                        {Object.entries(RoleMeta).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
                      </select>

                }
                </td>
                <td>
                  <span style={{
                  display: 'inline-flex', alignItems: 'center', gap: 5, padding: '2px 9px', borderRadius: 999, fontSize: 12, fontWeight: 500,
                  background: m.status === 'active' ? 'var(--col-success-bg)' : 'var(--col-pending-bg)',
                  color: m.status === 'active' ? 'var(--col-success)' : 'var(--col-pending)'
                }}>
                    <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'currentColor', display: 'inline-block' }} />
                    {m.status === 'active' ? 'Active' : 'Pending'}
                  </span>
                </td>
                <td style={{ fontSize: 13, color: 'var(--col-text-3)' }}>{m.joined}</td>
                <td>
                  {!m.isYou &&
                <button className="btn btn-ghost btn-sm" style={{ padding: '0 6px', color: 'var(--col-text-3)' }} onClick={() => setRemove(m)}>
                      <IcoX size={14} />
                    </button>
                }
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Invite modal */}
      {showInvite &&
      <div className="modal-overlay" onClick={() => setShowInvite(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()} style={{ width: 480 }}>
            <div className="modal-header"><div className="modal-title">Invite a member</div></div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 20, marginBottom: 24 }}>
              <div>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, color: 'var(--col-text)', marginBottom: 7 }}>Email address</label>
                <SInput value={inviteEmail} onChange={setInviteEmail} type="email" placeholder="colleague@yourcompany.com" />
              </div>
              <div>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, color: 'var(--col-text)', marginBottom: 7 }}>Role</label>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {Object.entries(RoleMeta).map(([key, m]) =>
                <label key={key} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px', borderRadius: 10, cursor: 'pointer',
                  border: `1.5px solid ${inviteRole === key ? 'var(--col-accent)' : 'var(--col-border-s)'}`,
                  background: inviteRole === key ? 'var(--col-accent-50)' : 'var(--col-surface)',
                  transition: 'all 150ms'
                }}>
                      <input type="radio" name="inv-role" value={key} checked={inviteRole === key} onChange={() => setInviteRole(key)} style={{ accentColor: 'var(--col-accent)', marginTop: 1 }} />
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--col-text)' }}>{m.label}</div>
                        <div style={{ fontSize: 12, color: 'var(--col-text-3)' }}>{{ owner: 'Full access', approver: 'Sign and approve', accountant: 'Draft runs, manage recipients', viewer: 'Read-only' }[key]}</div>
                      </div>
                    </label>
                )}
                </div>
              </div>
            </div>
            <div className="modal-footer">
              <button className="btn btn-secondary btn-md" onClick={() => setShowInvite(false)}>Cancel</button>
              <button className="btn btn-primary btn-md" onClick={sendInvite} disabled={!inviteEmail.trim()}>Send invite</button>
            </div>
          </div>
        </div>
      }

      {removeTarget &&
      <ConfirmModal
        title={`Remove ${removeTarget.name}?`}
        body={`${removeTarget.name} will immediately lose access. Any approval flows they were required for may be affected.`}
        confirmLabel="Remove member" confirmClass="btn-destructive"
        onConfirm={() => doRemove(removeTarget.id)} onCancel={() => setRemove(null)} />
      }

      {roleChangeTarget &&
      <ConfirmModal
        title={`Change role for ${roleChangeTarget.member.name}?`}
        body={`This will change their role from ${RoleMeta[roleChangeTarget.member.role]?.label} to ${RoleMeta[roleChangeTarget.newRole]?.label}. Their access level updates immediately.`}
        confirmLabel="Change role" confirmClass="btn-primary"
        onConfirm={() => { changeRole(roleChangeTarget.member.id, roleChangeTarget.newRole); setRoleChangeTarget(null); }}
        onCancel={() => setRoleChangeTarget(null)} />
      }
    </div>);

};

// ─────────────────────────────────────────────────────────────────
// APPROVAL POLICY
// ─────────────────────────────────────────────────────────────────
const ApprovalPolicySettings = ({ addToast }) => {
  const signers = [
  { name: 'Alice Johnson', initials: 'AJ', role: 'owner' },
  { name: 'Boris Kovalev', initials: 'BK', role: 'approver' },
  { name: 'Carol Dubois', initials: 'CD', role: 'approver' }];

  const [required, setRequired] = React.useState(2);
  const total = signers.length;

  return (
    <div>
      <SectionHead title="Approval Policy" desc="Set how many signers must approve a payroll run before it is broadcast on-chain." />

      <div className="card card-pad" style={{ borderRadius: 16 }}>

        {/* Threshold stepper */}
        <FormRow label="Signature threshold" hint="The run broadcasts automatically once this many approvers have signed.">
          <div>
            {/* Stepper */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
              <span style={{ fontSize: 14, color: 'var(--col-text-2)' }}>Require</span>
              <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--col-border)', borderRadius: 10, overflow: 'hidden' }}>
                <button onClick={() => setRequired(Math.max(1, required - 1))} style={{ width: 36, height: 38, border: 'none', background: 'var(--col-surface-2)', cursor: 'pointer', color: 'var(--col-text-2)', fontSize: 18, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'background 120ms' }}
                onMouseOver={(e) => e.currentTarget.style.background = 'var(--col-border-s)'}
                onMouseOut={(e) => e.currentTarget.style.background = 'var(--col-surface-2)'}>−</button>
                <div style={{ width: 46, textAlign: 'center', fontSize: 20, fontWeight: 700, color: 'var(--col-text)', fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' }}>
                  {required}
                </div>
                <button onClick={() => setRequired(Math.min(total, required + 1))} style={{ width: 36, height: 38, border: 'none', background: 'var(--col-surface-2)', cursor: 'pointer', color: 'var(--col-text-2)', fontSize: 18, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'background 120ms' }}
                onMouseOver={(e) => e.currentTarget.style.background = 'var(--col-border-s)'}
                onMouseOut={(e) => e.currentTarget.style.background = 'var(--col-surface-2)'}>+</button>
              </div>
              <span style={{ fontSize: 14, color: 'var(--col-text-2)' }}>of {total} signers</span>
            </div>

            {/* Visual signer dots */}
            <div style={{ display: 'flex', gap: 20, marginBottom: 20 }}>
              {signers.map((s, i) => {
                const on = i < required;
                return (
                  <div key={s.name} onClick={() => setRequired(on ? i : i + 1)}
                  style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, cursor: 'pointer', userSelect: 'none' }}>
                    <div style={{ position: 'relative' }}>
                      <div style={{
                        width: 48, height: 48, borderRadius: '50%',
                        border: `2.5px solid ${on ? 'var(--col-accent)' : 'var(--col-border)'}`,
                        background: on ? 'var(--col-accent-50)' : 'var(--col-surface-2)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 14, fontWeight: 700, letterSpacing: '0.01em',
                        color: on ? 'var(--col-accent)' : 'var(--col-text-3)',
                        transition: 'all 200ms ease'
                      }}>
                        {s.initials}
                      </div>
                      {on &&
                      <div style={{
                        position: 'absolute', bottom: -1, right: -1,
                        width: 18, height: 18, borderRadius: '50%',
                        background: 'var(--col-accent)', border: '2px solid var(--col-surface)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center'
                      }}>
                          <IcoCheck size={9} color="white" />
                        </div>
                      }
                    </div>
                    <div style={{ fontSize: 12, fontWeight: on ? 600 : 400, color: on ? 'var(--col-text)' : 'var(--col-text-3)', transition: 'color 200ms' }}>
                      {s.name.split(' ')[0]}
                    </div>
                    <RBadge role={s.role} />
                  </div>);

              })}
            </div>

            {/* Policy summary pill */}
            <div style={{ padding: '11px 16px', borderRadius: 10, background: 'var(--col-accent-50)', border: '1px solid var(--col-accent-100)', fontSize: 13, color: 'var(--col-text-2)', lineHeight: 1.5 }}>
              <span style={{ fontWeight: 600, color: 'var(--col-accent)' }}>{required} of {total} signatures required.</span>{' '}
              {required === 1 && 'Any one approver can authorize a run.'}
              {required > 1 && required < total && `${required} approvers must sign independently before broadcast.`}
              {required === total && 'All approvers must sign — maximum security.'}
            </div>
          </div>
        </FormRow>

        {/* Per-amount tiers — post-MVP */}
        <FormRow label="Per-amount tiers" hint="Different thresholds based on run value." noBorder>
          <div style={{ padding: '12px 16px', borderRadius: 10, border: '1.5px dashed var(--col-border)', background: 'var(--col-surface-2)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 7px', borderRadius: 5, background: 'var(--col-accent-50)', color: 'var(--col-accent)', textTransform: 'uppercase', letterSpacing: '0.05em', flexShrink: 0 }}>Soon</span>
            <span style={{ fontSize: 13, color: 'var(--col-text-3)' }}>Require more signatures for runs above a custom threshold (e.g. over $50,000).</span>
          </div>
        </FormRow>
      </div>

      <div style={{ marginTop: 14, display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 12 }}>
        {required < 1 && <span style={{ fontSize: 13, color: 'var(--col-error)' }}>At least 1 signer required</span>}
        <button className="btn btn-primary btn-md" onClick={() => addToast('Approval policy updated', 'success')} disabled={required < 1}>Save policy</button>
      </div>
    </div>);

};

// ─────────────────────────────────────────────────────────────────
// WALLETS
// ─────────────────────────────────────────────────────────────────
const INIT_WALLETS = [
{ id: 1, name: 'Operations Safe', address: '0x1a2b3c4d5e6f7890abcdef1234567890ab12345678', chain: 'EVM', type: 'multisig', balance: '$882,000', since: 'Jan 15, 2026', primary: true },
{ id: 2, name: 'Tron Treasury', address: 'TRX9a4f2e8b1d3c7e5a2b4c6d8e1f3a5b7c9d0e2f', chain: 'Tron', type: 'multisig', balance: '$286,400', since: 'Jan 15, 2026', primary: false },
{ id: 3, name: 'Solana Ops', address: '7GWCfpxzQrPXSMt2qH1kQbsJ8V3nYdL9Fx4mGBYx4z', chain: 'Solana', type: 'eoa', balance: '$80,000', since: 'Feb 12, 2026', primary: false }];


const WalletsSettings = ({ addToast }) => {
  const [wallets, setWallets] = React.useState(INIT_WALLETS);
  const [disconnectTarget, setDT] = React.useState(null);
  const [showConnectModal, setShowConnectModal] = React.useState(false);
  const [connectName, setConnectName] = React.useState('');
  const [connectType, setConnectType] = React.useState('metamask');

  const WALLET_TYPES = [
    { id:'metamask',      label:'MetaMask',      hint:'EVM',  color:'#F6851B' },
    { id:'tronlink',      label:'TronLink',      hint:'Tron', color:'#E84142' },
    { id:'walletconnect', label:'WalletConnect',  hint:'EVM',  color:'#3B99FC' },
    { id:'ledger',        label:'Ledger',         hint:'HW',   color:'#333'    },
  ];

  const doConnect = () => {
    if (!connectName.trim()) return;
    setWallets(p => [...p, { id: Date.now(), name: connectName.trim(), address: '0x...', chain: connectType === 'tronlink' ? 'Tron' : 'EVM', type: 'eoa', balance: '$0', since: 'Today', primary: false }]);
    setShowConnectModal(false); setConnectName(''); setConnectType('metamask');
    addToast(`${connectName} connected`, 'success');
  };

  const doDisconnect = (id) => {
    setWallets((p) => p.filter((w) => w.id !== id));
    setDT(null);
    addToast('Wallet disconnected', 'success');
  };

  return (
    <div>
      <SectionHead
        title="Connected Wallets"
        desc="Wallets linked to this workspace for treasury data and transaction signing."
        action={<button className="btn btn-secondary btn-md" onClick={() => setShowConnectModal(true)}><IcoPlus size={13} /> Connect wallet</button>} />
      

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 20 }}>
        {wallets.map((w) =>
        <div key={w.id} className="card" style={{ borderRadius: 14, padding: '16px 20px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 46, height: 46, borderRadius: 13, background: 'var(--col-surface-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <IcoWallet size={20} color="var(--col-text-3)" />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--col-text)' }}>{w.name}</span>
                  <ChainBadge chain={w.chain} size="xs" />
                  <span style={{ fontSize: 11, fontWeight: 600, padding: '1px 6px', borderRadius: 4, textTransform: 'uppercase', letterSpacing: '0.05em', background: w.type === 'multisig' ? 'var(--col-accent-50)' : 'var(--col-surface-2)', color: w.type === 'multisig' ? 'var(--col-accent)' : 'var(--col-text-3)' }}>
                    {w.type}
                  </span>
                  {w.primary && <span style={{ fontSize: 11, fontWeight: 600, padding: '1px 6px', borderRadius: 4, textTransform: 'uppercase', letterSpacing: '0.05em', background: 'var(--col-success-bg)', color: 'var(--col-success)' }}>Primary</span>}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
                  <span style={{ fontFamily: "'SF Mono','Fira Code',monospace", fontSize: 12, color: 'var(--col-text-3)' }}>{w.address.slice(0, 10)}…{w.address.slice(-6)}</span>
                  <span style={{ fontSize: 12, color: 'var(--col-text-3)' }}>Balance: <span style={{ fontWeight: 500, color: 'var(--col-text-2)' }}>{w.balance}</span></span>
                  <span style={{ fontSize: 12, color: 'var(--col-text-3)' }}>Since {w.since}</span>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                <button className="btn btn-ghost btn-sm" onClick={() => {navigator.clipboard?.writeText(w.address);addToast('Address copied', 'success');}}>
                  <IcoLink size={12} /> Copy
                </button>
                <button className="btn btn-ghost btn-sm" style={{ color: 'var(--col-error)' }} onClick={() => setDT(w)}>
                  Disconnect
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Supported chains */}
      <div style={{ padding: '16px 18px', borderRadius: 12, border: '1px solid var(--col-border-s)', background: 'var(--col-surface)' }}>
        <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--col-text-3)', marginBottom: 10 }}>Supported chains</div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems:'center' }}>
          {['EVM', 'Tron', 'Solana', 'BTC', 'TON'].map((c) => {
            const unsupported = ['BTC','TON'].includes(c);
            return (
              <span key={c} title={unsupported ? 'Coming in Phase 2' : ''}
                style={{ opacity: unsupported ? 0.38 : 1, filter: unsupported ? 'grayscale(0.5)' : 'none',
                  position:'relative', display:'inline-flex', alignItems:'center', gap:4 }}>
                <ChainBadge chain={c} />
                {unsupported && <span style={{ fontSize:9, fontWeight:700, color:'var(--col-text-3)', letterSpacing:'0.04em' }}>SOON</span>}
              </span>
            );
          })}
        </div>
        <div style={{ marginTop: 10, fontSize: 12, color: 'var(--col-text-3)' }}>BTC and TON support launching in Phase 2.</div>
      </div>

      {showConnectModal &&
      <div className="modal-overlay" onClick={() => setShowConnectModal(false)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 440 }}>
            <div className="modal-header"><div className="modal-title">Connect a wallet</div></div>
            <div style={{ display:'flex', flexDirection:'column', gap:16, marginBottom:24 }}>
              <div>
                <label style={{ display:'block', fontSize:13, fontWeight:500, color:'var(--col-text)', marginBottom:7 }}>Wallet name</label>
                <input className="form-input" style={{ height:40, width:'100%', padding:'0 12px', border:'1.5px solid var(--col-border)', borderRadius:9, fontFamily:'inherit', fontSize:14, color:'var(--col-text)', background:'var(--col-surface)', outline:'none' }}
                  value={connectName} onChange={e => setConnectName(e.target.value)}
                  placeholder="e.g. Operations Safe" autoFocus />
              </div>
              <div>
                <label style={{ display:'block', fontSize:13, fontWeight:500, color:'var(--col-text)', marginBottom:7 }}>Wallet type</label>
                <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                  {WALLET_TYPES.map(wt => (
                    <label key={wt.id} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 14px', borderRadius:10, cursor:'pointer',
                      border:`1.5px solid ${connectType===wt.id?'var(--col-accent)':'var(--col-border-s)'}`,
                      background:connectType===wt.id?'var(--col-accent-50)':'var(--col-surface)', transition:'all 150ms' }}>
                      <input type="radio" name="wtype" value={wt.id} checked={connectType===wt.id} onChange={()=>setConnectType(wt.id)} style={{ accentColor:'var(--col-accent)' }} />
                      <div style={{ width:8,height:8,borderRadius:'50%',background:wt.color,flexShrink:0 }} />
                      <span style={{ fontSize:13,fontWeight:500,color:'var(--col-text)' }}>{wt.label}</span>
                      <span style={{ fontSize:12,color:'var(--col-text-3)',marginLeft:'auto' }}>{wt.hint}</span>
                    </label>
                  ))}
                </div>
              </div>
            </div>
            <div className="modal-footer">
              <button className="btn btn-secondary btn-md" onClick={() => setShowConnectModal(false)}>Cancel</button>
              <button className="btn btn-primary btn-md" onClick={doConnect} disabled={!connectName.trim()}>Connect</button>
            </div>
          </div>
        </div>
      }

      {disconnectTarget &&
      <ConfirmModal
        title={`Disconnect ${disconnectTarget.name}?`}
        body="This wallet will stop appearing in your treasury dashboard. Existing payroll history is preserved. You can reconnect it at any time."
        confirmLabel="Disconnect" confirmClass="btn-destructive"
        onConfirm={() => doDisconnect(disconnectTarget.id)} onCancel={() => setDT(null)} />

      }
    </div>);

};

// ─────────────────────────────────────────────────────────────────
// NOTIFICATIONS
// ─────────────────────────────────────────────────────────────────
const NOTIF_ITEMS = [
{ key: 'payroll_drafted', label: 'Payroll run drafted', desc: 'When an accountant creates a new run' },
{ key: 'approval_requested', label: 'Your approval requested', desc: 'When your signature is needed on a pending run' },
{ key: 'run_broadcast', label: 'Run approved and broadcast', desc: 'When threshold is met and transactions are sent' },
{ key: 'tx_failed', label: 'Transaction failed', desc: 'When a broadcast fails on-chain' },
{ key: 'member_joined', label: 'New member joined', desc: 'When an invite is accepted' },
{ key: 'role_changed', label: 'Role changed', desc: 'When a member\'s permissions are updated' },
{ key: 'low_balance', label: 'Low balance alert', desc: 'When a wallet balance falls below your threshold' }];


const NotificationsSettings = ({ addToast }) => {
  const init = () => Object.fromEntries(NOTIF_ITEMS.map((r) => [r.key, { email: true, inapp: true }]));
  const [prefs, setPrefs] = React.useState(init);
  const toggle = (key, ch) => setPrefs((p) => ({ ...p, [key]: { ...p[key], [ch]: !p[key][ch] } }));

  return (
    <div>
      <SectionHead title="Notifications" desc="Choose which events notify you by email and inside the app." />
      <div className="card" style={{ overflow: 'hidden', borderRadius: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 80px 80px', padding: '10px 20px', borderBottom: '1px solid var(--col-border-s)', background: 'var(--col-surface-2)' }}>
          <span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--col-text-3)' }}>Event</span>
          <span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--col-text-3)', textAlign: 'center' }}>Email</span>
          <span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--col-text-3)', textAlign: 'center' }}>In-app</span>
        </div>
        {NOTIF_ITEMS.map((item, i) =>
        <div key={item.key} style={{ display: 'grid', gridTemplateColumns: '1fr 80px 80px', padding: '14px 20px', alignItems: 'center', borderBottom: i < NOTIF_ITEMS.length - 1 ? '1px solid var(--col-border-s)' : 'none' }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--col-text)' }}>{item.label}</div>
              <div style={{ fontSize: 12, color: 'var(--col-text-3)', marginTop: 1 }}>{item.desc}</div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'center' }}><SToggle value={prefs[item.key].email} onChange={() => toggle(item.key, 'email')} /></div>
            <div style={{ display: 'flex', justifyContent: 'center' }}><SToggle value={prefs[item.key].inapp} onChange={() => toggle(item.key, 'inapp')} /></div>
          </div>
        )}
      </div>
      <div style={{ marginTop: 14, display: 'flex', justifyContent: 'flex-end' }}>
        <button className="btn btn-primary btn-md" onClick={() => addToast('Notification preferences saved', 'success')}>Save preferences</button>
      </div>
    </div>);

};

// ─────────────────────────────────────────────────────────────────
// SECURITY
// ─────────────────────────────────────────────────────────────────
const INIT_SESSIONS = [
{ id: 1, device: 'Chrome on macOS', ip: '91.148.22.14', location: 'Warsaw, PL', last: 'Now', current: true },
{ id: 2, device: 'Safari on iPhone', ip: '91.148.22.15', location: 'Warsaw, PL', last: '2h ago', current: false },
{ id: 3, device: 'Chrome on Windows', ip: '178.43.91.22', location: 'Prague, CZ', last: '3d ago', current: false }];


const SecuritySettings = ({ addToast }) => {
  const [twoFa, setTwoFa] = React.useState(true);
  const [emailMfa, setEmailMfa] = React.useState(false);
  const [passkeys, setPasskeys] = React.useState([
    { id:1, name:'Chrome on macOS', createdAt:'May 15, 2026' }
  ]);
  const [sessions, setSessions] = React.useState(INIT_SESSIONS);

  const revokeSession = (id) => {setSessions((p) => p.filter((s) => s.id !== id));addToast('Session revoked', 'success');};
  const revokeAll = () => {setSessions((p) => p.filter((s) => s.current));addToast('All other sessions revoked', 'success');};

  return (
    <div>
      <SectionHead title="Security" desc="Manage two-factor authentication and active login sessions." />

      {/* 2FA card */}
      <div className="card card-pad" style={{ borderRadius: 16, marginBottom: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--col-text)', marginBottom: 3 }}>Two-factor authentication (TOTP)</div>
            <div style={{ fontSize: 13, color: 'var(--col-text-3)', lineHeight: 1.5 }}>Require an authenticator code in addition to your password at each login.</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
            <span style={{ fontSize: 12, fontWeight: 600, padding: '3px 10px', borderRadius: 999, background: twoFa ? 'var(--col-success-bg)' : 'var(--col-error-bg)', color: twoFa ? 'var(--col-success)' : 'var(--col-error)' }}>
              {twoFa ? '● Enabled' : '○ Disabled'}
            </span>
            <button className={`btn btn-sm ${twoFa ? 'btn-secondary' : 'btn-primary'}`} onClick={() => {setTwoFa((v) => !v);addToast(`2FA ${!twoFa ? 'enabled' : 'disabled'}`, 'success');}}>
              {twoFa ? 'Disable' : 'Enable 2FA'}
            </button>
          </div>
        </div>
      </div>

      {/* Email magic link 2FA */}
      <div className="card card-pad" style={{ borderRadius: 16, marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--col-text)', marginBottom: 3 }}>Email magic link</div>
            <div style={{ fontSize: 13, color: 'var(--col-text-3)', lineHeight: 1.5 }}>Send a one-time expirable link to your email to confirm sensitive actions (e.g. approvals, 2FA changes).</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
            <SToggle value={emailMfa} onChange={(v) => { setEmailMfa(v); addToast(`Email magic link ${v ? 'enabled' : 'disabled'}`, 'success'); }} />
          </div>
        </div>
        {emailMfa &&
          <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--col-border-s)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ fontSize: 13, color: 'var(--col-text-2)' }}>Links sent to <strong>alice@acme.com</strong> · expires in 15 min</div>
            <button className="btn btn-secondary btn-sm" onClick={() => addToast('Test link sent to alice@acme.com', 'success')}>Send test link</button>
          </div>
        }
      </div>

      {/* Passkeys */}
      <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--col-text)', marginBottom: 12 }}>Passkeys</div>
      <div className="card card-pad" style={{ borderRadius: 16, marginBottom: 16 }}>
        <div style={{ fontSize: 13, color: 'var(--col-text-3)', marginBottom: 14, lineHeight: 1.5 }}>
          Sign in with Face ID, Touch ID, or a hardware key — no password needed. Passkeys replace passwords and are phishing-resistant.
        </div>
        {passkeys.map(pk => (
          <div key={pk.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', borderRadius: 10, border: '1px solid var(--col-border-s)', background: 'var(--col-surface)', marginBottom: 8 }}>
            <div style={{ width: 34, height: 34, borderRadius: 9, background: 'var(--col-accent-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--col-accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--col-text)' }}>{pk.name}</div>
              <div style={{ fontSize: 11, color: 'var(--col-text-3)', marginTop: 1 }}>Registered {pk.createdAt}</div>
            </div>
            <button className="btn btn-ghost btn-sm" style={{ color: 'var(--col-error)' }} onClick={() => { setPasskeys(p => p.filter(k => k.id !== pk.id)); addToast('Passkey removed', 'success'); }}>Remove</button>
          </div>
        ))}
        <button className="btn btn-secondary btn-sm" style={{ gap: 5, marginTop: 4 }}
          onClick={() => { setPasskeys(p => [...p, { id: Date.now(), name: 'New passkey', createdAt: 'Today' }]); addToast('Passkey registered', 'success'); }}>
          <IcoPlus size={13} /> Register passkey
        </button>
      </div>

      {/* Sessions */}
      <div style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--col-text)' }}>Active sessions</div>
          {sessions.length > 1 &&
          <button className="btn btn-ghost btn-sm" style={{ color: 'var(--col-error)', fontSize: 13 }} onClick={revokeAll}>Revoke all others</button>
          }
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {sessions.map((s) =>
          <div key={s.id} className="card" style={{ borderRadius: 12, padding: '13px 18px', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 36, height: 36, borderRadius: 9, background: 'var(--col-surface-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <IcoUser size={16} color="var(--col-text-3)" />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--col-text)' }}>{s.device}</span>
                  {s.current && <span style={{ fontSize: 11, fontWeight: 600, padding: '1px 6px', borderRadius: 4, background: 'var(--col-accent-50)', color: 'var(--col-accent)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Current</span>}
                </div>
                <div style={{ fontSize: 12, color: 'var(--col-text-3)', marginTop: 2 }}>{s.ip} · {s.location} · Last active {s.last}</div>
              </div>
              {!s.current &&
            <button className="btn btn-ghost btn-sm" style={{ color: 'var(--col-text-3)', flexShrink: 0 }} onClick={() => revokeSession(s.id)}>Revoke</button>
            }
            </div>
          )}
        </div>
      </div>

      {/* Change password */}
      <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--col-text)', marginBottom: 12 }}>Change password</div>
      <div className="card card-pad" style={{ borderRadius: 16 }}>
        <FormRow label="Current password"><SInput type="password" placeholder="••••••••" /></FormRow>
        <FormRow label="New password" hint="Minimum 10 characters."><SInput type="password" placeholder="••••••••" /></FormRow>
        <FormRow label="Confirm new password" noBorder><SInput type="password" placeholder="••••••••" /></FormRow>
      </div>
      <div style={{ marginTop: 14, display: 'flex', justifyContent: 'flex-end' }}>
        <button className="btn btn-primary btn-md" onClick={() => addToast('Password updated', 'success')}>Update password</button>
      </div>
    </div>);

};

// ─────────────────────────────────────────────────────────────────
// BILLING
// ─────────────────────────────────────────────────────────────────
const BillingSettings = ({ addToast }) =>
<div>
    <SectionHead title="Subscription" desc="Your current plan, usage, and payment details." />

    {/* Plan hero */}
    <div style={{ borderRadius: 18, border: '1px solid var(--col-accent-100)', background: 'var(--col-accent-50)', padding: 24, marginBottom: 16, position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: -30, right: -30, width: 140, height: 140, borderRadius: '50%', background: 'var(--col-accent-100)', opacity: 0.5 }} />
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', position: 'relative' }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--col-accent)', marginBottom: 6 }}>Current plan</div>
          <div style={{ fontSize: 30, fontWeight: 700, color: 'var(--col-text)', letterSpacing: '-0.025em', lineHeight: 1.1 }}>Growth</div>
          <div style={{ fontSize: 14, color: 'var(--col-text-2)', marginTop: 5 }}>$499 / month, flat · Next billing <strong>June 1, 2026</strong></div>
        </div>
        <button className="btn btn-secondary btn-md" style={{ background: 'rgba(255,255,255,0.7)', flexShrink: 0 }} onClick={() => addToast('Opening billing portal…', 'success')}>Manage billing</button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, marginTop: 20, position: 'relative' }}>
        {[{ label: 'Active members', value: '4', limit: 'unlimited' }, { label: 'Connected wallets', value: '3', limit: 'unlimited' }, { label: 'Runs this month', value: '2', limit: 'unlimited' }].map((item) =>
      <div key={item.label} style={{ background: 'rgba(255,255,255,0.65)', borderRadius: 10, padding: '12px 14px', backdropFilter: 'blur(6px)' }}>
            <div style={{ fontSize: 11, color: 'var(--col-text-3)', fontWeight: 500, marginBottom: 4 }}>{item.label}</div>
            <div style={{ fontSize: 20, fontWeight: 700, color: 'var(--col-text)', letterSpacing: '-0.01em', lineHeight: 1 }}>
              {item.value}<span style={{ fontSize: 12, fontWeight: 400, color: 'var(--col-text-3)', marginLeft: 4 }}>{item.limit}</span>
            </div>
          </div>
      )}
      </div>
    </div>

    {/* Payment method */}
    <div className="card card-pad" style={{ borderRadius: 16, marginBottom: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--col-text-3)', marginBottom: 10 }}>Payment method</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 40, height: 26, borderRadius: 5, border: '1px solid var(--col-border)', background: 'var(--col-surface-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, fontWeight: 800, color: 'var(--col-text-3)', letterSpacing: '0.06em' }}>VISA</div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--col-text)' }}>Visa ending 4242</div>
              <div style={{ fontSize: 12, color: 'var(--col-text-3)' }}>Expires 09 / 2028</div>
            </div>
          </div>
        </div>
        <button className="btn btn-secondary btn-sm" onClick={() => addToast('Update card in billing portal', 'success')}>Update</button>
      </div>
    </div>

    {/* Invoice history */}
    <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--col-text)', marginBottom: 12 }}>Invoice history</div>
    <div className="card" style={{ overflow: 'hidden', borderRadius: 16 }}>
      <table className="data-table">
        <thead><tr><th>Period</th><th>Amount</th><th>Status</th><th style={{ width: 80 }}></th></tr></thead>
        <tbody>
          {[{ p: 'May 2026', amount: '$149.00' }, { p: 'Apr 2026', amount: '$149.00' }, { p: 'Mar 2026', amount: '$149.00' }].map((inv) =>
        <tr key={inv.p} style={{ cursor: 'default' }}>
              <td className="cell-primary">{inv.p}</td>
              <td className="cell-mono">{inv.amount}</td>
              <td><span className="badge badge-dot badge-confirmed">Paid</span></td>
              <td className="right"><button className="btn btn-ghost btn-sm" onClick={() => addToast(`Downloading ${inv.p} invoice…`, 'success')}><IcoDownload size={12} /> PDF</button></td>
            </tr>
        )}
        </tbody>
      </table>
    </div>
  </div>;


// ─────────────────────────────────────────────────────────────────
// NAV ICONS (inline, uses global Icon)
// ─────────────────────────────────────────────────────────────────
const SNIcon = ({ type, size = 15 }) => {
  const paths = {
    general: ["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z", "M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"],
    members: ["M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2", "M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z", "M23 21v-2a4 4 0 0 0-3-3.87", "M16 3.13a4 4 0 0 1 0 7.75"],
    approval: ["M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z", "M9 12l2 2 4-4"],
    wallets: ["M20 7H4a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z", "M16 3H8L4 7h16l-4-4z", "M16 14a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"],
    notifications: ["M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9", "M13.73 21a2 2 0 0 1-3.46 0"],
    security: ["M19 11H5a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2z", "M7 11V7a5 5 0 0 1 10 0v4", "M12 16a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"],
    billing: ["M21 4H3a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z", "M1 10h22"],
    appearance: ["M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z", "M12 2v20", "M2 12h20", "M4.93 4.93l14.14 14.14", "M19.07 4.93L4.93 19.07"]
  };
  return <Icon d={paths[type] || paths.general} size={size} color="currentColor" strokeWidth={1.7} />;
};

// ─────────────────────────────────────────────────────────────────
// SETTINGS SHELL
// ─────────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────
// APPEARANCE
// ─────────────────────────────────────────────────────────────────
const PALETTE_OPTIONS = [
{ id: 'stone', label: 'Astrail', accent: '#4571F2', bg: '#F3F4F7', darkBg: '#0A0B0F' },
{ id: 'aurora', label: 'Aurora', accent: '#009B8A', bg: '#EEF9F7', darkBg: '#080E14' },
{ id: 'onyx', label: 'Onyx & Champagne', accent: '#8B6B30', bg: '#FAF8F4', darkBg: '#0A0908' },
{ id: 'dusk', label: 'Dusk', accent: '#5A5AF0', bg: '#F6F5FF', darkBg: '#100F1C' }];


const AppearanceSettings = ({ addToast }) => {
  // Read live tweaks from the App (exposed via window.__nvxTweaks)
  const getTweaks = () => window.__nvxTweaks || { palette: 'stone', theme: 'light', density: 'comfortable', glass: false, paletteGradient: false, animatedGlass: false };
  const [localT, setLocalT] = React.useState(getTweaks);

  // Re-sync when this section mounts
  React.useEffect(() => {setLocalT(getTweaks());}, []);

  const apply = (key, val) => {
    setLocalT((p) => ({ ...p, [key]: val }));
    if (window.__nvxSetTweak) window.__nvxSetTweak(key, val);else
    addToast('Applied', 'success');
  };

  const isDark = localT.theme === 'dark';

  return (
    <div>
      <SectionHead title="Appearance" desc="Customise the look and feel of your workspace. Changes apply instantly and are saved per-session." />

      {/* Palette */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--col-text-3)', marginBottom: 12 }}>Colour palette</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10 }}>
          {PALETTE_OPTIONS.map((p) => {
            const selected = localT.palette === p.id;
            return (
              <div key={p.id} onClick={() => apply('palette', p.id)} style={{ borderRadius: 14, border: `2px solid ${selected ? p.accent : 'var(--col-border-s)'}`, cursor: 'pointer', overflow: 'hidden', transition: 'border-color 150ms, box-shadow 150ms', boxShadow: selected ? `0 0 0 3px ${p.accent}22` : 'none' }}>
                {/* Mini preview */}
                <div style={{ height: 64, background: isDark ? p.darkBg : p.bg, display: 'flex', alignItems: 'flex-end', padding: 10, gap: 6, position: 'relative' }}>
                  {/* Fake sidebar */}
                  <div style={{ width: 28, height: 48, borderRadius: 6, background: isDark ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.7)', position: 'absolute', left: 8, top: 8, display: 'flex', flexDirection: 'column', gap: 3, padding: 4 }}>
                    {[1, 0.5, 0.5].map((o, i) => <div key={i} style={{ height: 4, borderRadius: 2, background: p.accent, opacity: o }} />)}
                  </div>
                  {/* Fake cards */}
                  <div style={{ position: 'absolute', right: 8, top: 8, display: 'flex', gap: 4 }}>
                    {[1, 0.6].map((o, i) => <div key={i} style={{ width: 28, height: 18, borderRadius: 4, background: isDark ? `rgba(255,255,255,${0.08 * o})` : `rgba(255,255,255,${0.8 * o})`, border: `1px solid ${isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)'}` }} />)}
                  </div>
                  {/* Accent dot */}
                  <div style={{ position: 'absolute', bottom: 8, right: 8, width: 18, height: 18, borderRadius: 999, background: p.accent, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    {selected && <IcoCheck size={9} color="white" />}
                  </div>
                </div>
                <div style={{ padding: '8px 12px', background: 'var(--col-surface)', display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ width: 10, height: 10, borderRadius: 2, background: p.accent, flexShrink: 0 }} />
                  <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--col-text)' }}>{p.label}</span>
                </div>
              </div>);

          })}
        </div>
      </div>

      {/* Theme */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--col-text-3)', marginBottom: 12 }}>Theme</div>
        <div style={{ display: 'flex', gap: 10 }}>
          {[['light', '☀️ Light'], ['dark', '🌙 Dark']].map(([v, l]) =>
          <button key={v} onClick={() => apply('theme', v)} style={{ flex: 1, padding: '12px 16px', borderRadius: 12, border: `2px solid ${localT.theme === v ? 'var(--col-accent)' : 'var(--col-border-s)'}`, background: localT.theme === v ? 'var(--col-accent-50)' : 'var(--col-surface)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 14, fontWeight: 500, color: localT.theme === v ? 'var(--col-accent)' : 'var(--col-text-2)', transition: 'all 150ms', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
              {l}
            </button>
          )}
        </div>
      </div>

      {/* Density */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--col-text-3)', marginBottom: 12 }}>Layout density</div>
        <div style={{ display: 'flex', gap: 10 }}>
          {[['comfortable', 'Comfortable — more breathing room'], ['compact', 'Compact — more data on screen']].map(([v, l]) =>
          <button key={v} onClick={() => apply('density', v)} style={{ flex: 1, padding: '12px 16px', borderRadius: 12, border: `2px solid ${localT.density === v ? 'var(--col-accent)' : 'var(--col-border-s)'}`, background: localT.density === v ? 'var(--col-accent-50)' : 'var(--col-surface)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 500, color: localT.density === v ? 'var(--col-accent)' : 'var(--col-text-2)', transition: 'all 150ms', textAlign: 'left' }}>
              {l}
            </button>
          )}
        </div>
      </div>

      {/* Effects */}
      <div>
        <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--col-text-3)', marginBottom: 12 }}>Visual effects</div>
        <div className="card" style={{ borderRadius: 14, overflow: 'hidden' }}>
          {[
          { key: 'glass', label: 'Glass mode', desc: 'Frosted-glass effect over a gradient background', always: true },
          { key: 'paletteGradient', label: 'Palette gradient', desc: 'Match the glass gradient to your colour palette', depends: 'glass' },
          { key: 'animatedGlass', label: 'Animated gradient', desc: 'Slowly animate the background gradient', depends: 'glass' }].
          map((item, i, arr) => {
            const disabled = item.depends && !localT[item.depends];
            const value = localT[item.key];
            return (
              <div key={item.key} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 18px', borderBottom: i < arr.length - 1 ? '1px solid var(--col-border-s)' : 'none', opacity: disabled ? 0.45 : 1 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--col-text)' }}>{item.label}</div>
                  <div style={{ fontSize: 12, color: 'var(--col-text-3)', marginTop: 1 }}>{item.desc}</div>
                </div>
                <SToggle value={!!value} onChange={(v) => apply(item.key, v)} disabled={disabled} />
              </div>);

          })}
        </div>
      </div>
    </div>);

};

const SETTINGS_SECTIONS = [
{ group: 'Workspace', items: [
  { id: 'general', label: 'General', icon: 'general' },
  { id: 'members', label: 'Members & Roles', icon: 'members' },
  { id: 'approval', label: 'Approval Policy', icon: 'approval' },
  { id: 'wallets', label: 'Wallets', icon: 'wallets' }]
},
{ group: 'Compliance & accounting', items: [
  { id: 'compliance', label: 'AML & Sanctions', icon: 'approval' },
  { id: 'accounting', label: 'Accounting & Export', icon: 'billing' }]
},
{ group: 'Account', items: [
  { id: 'notifications', label: 'Notifications', icon: 'notifications' },
  { id: 'security', label: 'Security', icon: 'security' },
  { id: 'appearance', label: 'Appearance', icon: 'appearance' }]
},
{ group: 'Billing', items: [
  { id: 'billing', label: 'Subscription', icon: 'billing' }]
}];


const SettingsScreen = ({ onNavigate, addToast, activeSection, onSectionChange }) => {
  const [_localActive, _setLocalActive] = React.useState('general');
  const active = activeSection !== undefined ? activeSection : _localActive;
  const setActive = onSectionChange || _setLocalActive;

  const renderSection = () => {
    switch (active) {
      case 'general':return <GeneralSettings addToast={addToast} />;
      case 'members':return <MembersSettings addToast={addToast} />;
      case 'approval':return <ApprovalPolicySettings addToast={addToast} />;
      case 'wallets':return <WalletsSettings addToast={addToast} />;
      case 'notifications':return <NotificationsSettings addToast={addToast} />;
      case 'security':return <SecuritySettings addToast={addToast} />;
      case 'appearance':return <AppearanceSettings addToast={addToast} />;
      case 'billing':return <BillingSettings addToast={addToast} />;
      case 'compliance':return <ComplianceSettings addToast={addToast} />;
      case 'accounting':return <AccountingSettings addToast={addToast} />;
      default:return null;
    }
  };

  return (
    <>
      {/* Header */}
      <div className="content-header">
        <div className="content-header-left">
          <div className="breadcrumb">
            <span className="breadcrumb-link" onClick={() => onNavigate('dashboard')}>Dashboard</span>
            <span className="breadcrumb-sep">›</span>
            <span className="breadcrumb-current">Settings</span>
          </div>
        </div>
      </div>

      {/* Body: full-width content */}
      <div style={{ flex: 1, overflow: 'hidden' }}>
        <div style={{ height: '100%', overflowY: 'auto', padding: '32px 40px', background: 'var(--col-bg)' }}>
          <div style={{ maxWidth: 720 }}>
            {renderSection()}
          </div>
        </div>
      </div>
    </>);

};

Object.assign(window, { SettingsScreen, SNIcon, SETTINGS_SECTIONS });