function BrandingPanel({ companyAddress, onUpdateAddress }) {
  const { Button, Input } = window.TheUpperDeckDesignSystem_4d3294;
  const { UploadBox } = window.UdUI;
  const [logo, setLogo] = React.useState(null);
  const [primary, setPrimary] = React.useState('#0E2247');
  const [accent, setAccent] = React.useState('#F49B52');
  const [address, setAddress] = React.useState(companyAddress || '');
  const [saved, setSaved] = React.useState(false);
  const [gcashQr, setGcashQr] = React.useState(null);
  const [bank, setBank] = React.useState({ bank: '', accountName: '', accountNumber: '' });
  React.useEffect(() => { window.fetchBrandingLive().then((b) => { setGcashQr(b.gcash_qr_url || null); setBank(b.bank_details && Object.keys(b.bank_details).length ? b.bank_details : { bank: '', accountName: '', accountNumber: '' }); }); }, []);
  async function save() {
    onUpdateAddress(address);
    let qrUrl = gcashQr;
    if (gcashQr && gcashQr.startsWith('data:')) {
      const blob = await (await fetch(gcashQr)).blob();
      await window.sb.storage.from('branding').upload('gcash-qr.jpg', blob, { upsert: true, contentType: blob.type });
      qrUrl = window.sb.storage.from('branding').getPublicUrl('gcash-qr.jpg').data.publicUrl;
    }
    await window.saveBrandingLive({ gcash_qr_url: qrUrl, bank_details: bank });
    setSaved(true); setTimeout(() => setSaved(false), 1800);
  }
  return (
    <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ fontWeight: 700 }}>Branding</div>
      <div style={{ display: 'grid', gridTemplateColumns: '160px 1fr', gap: 20 }}>
        <div style={{ height: 120 }}><UploadBox label="Logo" hint="Square, click to upload" value={logo} onChange={setLogo} /></div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <div style={{ fontSize: 'var(--text-sm)', fontWeight: 600, marginBottom: 6 }}>Primary color</div>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <input type="color" value={primary} onChange={(e) => setPrimary(e.target.value)} style={{ width: 40, height: 36, border: '1px solid var(--border-default)', borderRadius: 'var(--radius-sm)', cursor: 'pointer', padding: 0 }} />
              <input value={primary} onChange={(e) => setPrimary(e.target.value)} style={{ width: 110, padding: '9px 12px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)', fontFamily: 'var(--font-mono)', fontSize: 'var(--text-sm)' }} />
            </div>
          </div>
          <div>
            <div style={{ fontSize: 'var(--text-sm)', fontWeight: 600, marginBottom: 6 }}>Accent color</div>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <input type="color" value={accent} onChange={(e) => setAccent(e.target.value)} style={{ width: 40, height: 36, border: '1px solid var(--border-default)', borderRadius: 'var(--radius-sm)', cursor: 'pointer', padding: 0 }} />
              <input value={accent} onChange={(e) => setAccent(e.target.value)} style={{ width: 110, padding: '9px 12px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)', fontFamily: 'var(--font-mono)', fontSize: 'var(--text-sm)' }} />
            </div>
          </div>
        </div>
      </div>
      <Input label="Company address" value={address} onChange={setAddress} placeholder="Shown at the bottom of the admin sidebar" />
      <div style={{ borderTop: '1px solid var(--border-default)', paddingTop: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontWeight: 700 }}>Payment details shown at checkout</div>
        <div style={{ display: 'flex', gap: 16 }}>
          <div style={{ width: 120, height: 120, flexShrink: 0 }}><UploadBox label="GCash QR" hint="Upload QR" value={gcashQr} onChange={setGcashQr} /></div>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Input label="Bank name" value={bank.bank} onChange={(v) => setBank((b) => ({ ...b, bank: v }))} />
            <Input label="Account name" value={bank.accountName} onChange={(v) => setBank((b) => ({ ...b, accountName: v }))} />
            <Input label="Account number" value={bank.accountNumber} onChange={(v) => setBank((b) => ({ ...b, accountNumber: v }))} />
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <Button onClick={save}>Save branding</Button>
        {saved && <span style={{ fontSize: 'var(--text-sm)', color: 'var(--status-success)' }}>Saved</span>}
      </div>
    </div>
  );
}

function ListItemCard({ children, onRemove }) {
  return <div style={{ border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', padding: 14, display: 'flex', flexDirection: 'column', gap: 8, position: 'relative' }}>
    <button type="button" onClick={onRemove} style={{ position: 'absolute', top: 8, right: 8, border: 'none', background: 'none', color: 'var(--text-muted)', cursor: 'pointer', fontSize: 16 }}>×</button>
    {children}
  </div>;
}

function AboutContentPanel() {
  const { Input, Button, Switch } = window.TheUpperDeckDesignSystem_4d3294;
  const { UploadBox } = window.UdUI;
  const [content, setContent] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const [saved, setSaved] = React.useState(false);
  const [partnerInput, setPartnerInput] = React.useState('');
  const [newPartner, setNewPartner] = React.useState({ name: '', logo: null });

  React.useEffect(() => { window.fetchAboutContent().then(setContent); }, []);
  if (!content) return <div style={{ padding: 32, color: 'var(--text-muted)' }}>Loading…</div>;

  function updateFounder(i, k, v) { const arr = content.founders.slice(); arr[i] = { ...arr[i], [k]: v }; setContent({ ...content, founders: arr }); }
  function addFounder() { setContent({ ...content, founders: [...content.founders, { name: '', title: '', quote: '', photo: null }] }); }
  function removeFounder(i) { setContent({ ...content, founders: content.founders.filter((_, idx) => idx !== i) }); }

  function updateFacility(i, k, v) { const arr = content.facilities.slice(); arr[i] = { ...arr[i], [k]: v }; setContent({ ...content, facilities: arr }); }
  function addFacility() { setContent({ ...content, facilities: [...content.facilities, { title: '', desc: '', photo: null, tall: false }] }); }
  function removeFacility(i) { setContent({ ...content, facilities: content.facilities.filter((_, idx) => idx !== i) }); }

  function addPartner() { if (!newPartner.logo) return; setContent({ ...content, partners: [...content.partners, { name: newPartner.name.trim() || 'Partner', logo: newPartner.logo }] }); setNewPartner({ name: '', logo: null }); }
  function removePartner(i) { setContent({ ...content, partners: content.partners.filter((_, idx) => idx !== i) }); }

  async function save() {
    setSaving(true);
    await window.saveAboutContent(content);
    const fresh = await window.fetchAboutContent();
    setContent(fresh);
    setSaving(false); setSaved(true); setTimeout(() => setSaved(false), 1800);
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 24, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontWeight: 700 }}>Founders</div>
        {content.founders.map((f, i) => (
          <ListItemCard key={i} onRemove={() => removeFounder(i)}>
            <div style={{ display: 'flex', gap: 14 }}>
              <div style={{ width: 90, height: 90, flexShrink: 0 }}><UploadBox label="Photo" value={f.photo} onChange={(v) => updateFounder(i, 'photo', v)} /></div>
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                  <Input placeholder="Name" value={f.name} onChange={(v) => updateFounder(i, 'name', v)} />
                  <Input placeholder="Title" value={f.title} onChange={(v) => updateFounder(i, 'title', v)} />
                </div>
                <Input placeholder="Quote" value={f.quote} onChange={(v) => updateFounder(i, 'quote', v)} />
              </div>
            </div>
          </ListItemCard>
        ))}
        <Button variant="secondary" onClick={addFounder}>+ Add founder</Button>
      </div>

      <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 24, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontWeight: 700 }}>Facilities</div>
        {content.facilities.map((f, i) => (
          <ListItemCard key={i} onRemove={() => removeFacility(i)}>
            <div style={{ display: 'flex', gap: 14 }}>
              <div style={{ width: 90, height: 90, flexShrink: 0 }}><UploadBox label="Photo" value={f.photo} onChange={(v) => updateFacility(i, 'photo', v)} /></div>
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <Input placeholder="Title" value={f.title} onChange={(v) => updateFacility(i, 'title', v)} />
                <Input placeholder="Description" value={f.desc} onChange={(v) => updateFacility(i, 'desc', v)} />
                <Switch label="Tall card" checked={!!f.tall} onChange={(v) => updateFacility(i, 'tall', v)} />
              </div>
            </div>
          </ListItemCard>
        ))}
        <Button variant="secondary" onClick={addFacility}>+ Add facility</Button>
      </div>

      <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 24, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontWeight: 700 }}>Partners</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
          {content.partners.map((p, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', padding: '8px 10px' }}>
              {p.logo ? <img src={p.logo} alt={p.name} style={{ width: 32, height: 32, objectFit: 'contain' }} /> : <div style={{ width: 32, height: 32, borderRadius: 'var(--radius-sm)', background: 'var(--bg-sunken)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>?</div>}
              <span style={{ fontSize: 'var(--text-sm)' }}>{p.name}</span>
              <button type="button" onClick={() => removePartner(i)} style={{ border: 'none', background: 'none', color: 'var(--text-muted)', cursor: 'pointer' }}>×</button>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'flex-end' }}>
          <div style={{ width: 64, height: 64, flexShrink: 0 }}><UploadBox label="Logo" hint="Required" value={newPartner.logo} onChange={(v) => setNewPartner((p) => ({ ...p, logo: v }))} /></div>
          <Input placeholder="Partner name (alt text / fallback)" value={newPartner.name} onChange={(v) => setNewPartner((p) => ({ ...p, name: v }))} />
          <Button variant="secondary" onClick={addPartner} disabled={!newPartner.logo}>Add</Button>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <Button onClick={save} disabled={saving}>{saving ? 'Saving…' : 'Save About page'}</Button>
        {saved && <span style={{ fontSize: 'var(--text-sm)', color: 'var(--status-success)' }}>Saved</span>}
      </div>
    </div>
  );
}

function UsersPanel({ currentAdminId }) {
  const { Badge, Button, Input } = window.TheUpperDeckDesignSystem_4d3294;
  const { CustomSelect } = window.UdUI;
  const [admins, setAdmins] = React.useState(null);
  const [candidates, setCandidates] = React.useState([]);
  const [adding, setAdding] = React.useState(false);
  const [pick, setPick] = React.useState('');
  const [creating, setCreating] = React.useState(false);
  const [newAdmin, setNewAdmin] = React.useState({ firstName: '', lastName: '', email: '', password: '' });
  const [createBusy, setCreateBusy] = React.useState(false);
  const [createError, setCreateError] = React.useState('');

  function reload() {
    Promise.all([window.fetchAdminsLive(), window.fetchNonAdminUsersLive()]).then(([a, c]) => { setAdmins(a); setCandidates(c); });
  }
  React.useEffect(() => { reload(); }, []);

  async function remove(id) {
    if (!window.confirm('Remove this admin\u2019s access? They will no longer be able to log into the dashboard.')) return;
    await window.demoteAdminLive(id);
    reload();
  }
  async function addAdmin() {
    if (!pick) return;
    await window.promoteToAdminLive(pick);
    setAdding(false); setPick('');
    reload();
  }
  async function createAdmin() {
    if (!newAdmin.email || !newAdmin.password || !newAdmin.firstName) return;
    setCreateBusy(true); setCreateError('');
    const res = await window.createAdminAccountLive(newAdmin.email, newAdmin.password, newAdmin.firstName, newAdmin.lastName);
    setCreateBusy(false);
    if (res.error) { setCreateError(res.error); return; }
    setCreating(false); setNewAdmin({ firstName: '', lastName: '', email: '', password: '' });
    reload();
  }

  if (admins === null) return <div style={{ padding: 32, color: 'var(--text-muted)' }}>Loading…</div>;

  return (
    <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflow: 'hidden' }}>
      <div style={{ padding: '16px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid var(--border-default)', flexWrap: 'wrap', gap: 10 }}>
        <div style={{ fontWeight: 700 }}>Admins</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button size="sm" variant="secondary" onClick={() => { setCreating((c) => !c); setAdding(false); }}>+ Create new admin</Button>
          <Button size="sm" onClick={() => { setAdding((a) => !a); setCreating(false); }}>+ Promote existing user</Button>
        </div>
      </div>
      {creating && (
        <div style={{ padding: '14px 20px', display: 'flex', flexDirection: 'column', gap: 10, borderBottom: '1px solid var(--border-default)', background: 'var(--bg-sunken)' }}>
          {createError && <div style={{ fontSize: 'var(--text-sm)', color: 'var(--status-error)' }}>{createError}</div>}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <Input placeholder="First name" value={newAdmin.firstName} onChange={(v) => setNewAdmin((s) => ({ ...s, firstName: v }))} />
            <Input placeholder="Last name" value={newAdmin.lastName} onChange={(v) => setNewAdmin((s) => ({ ...s, lastName: v }))} />
          </div>
          <Input placeholder="Email" type="email" value={newAdmin.email} onChange={(v) => setNewAdmin((s) => ({ ...s, email: v }))} />
          <Input placeholder="Temporary password" type="password" value={newAdmin.password} onChange={(v) => setNewAdmin((s) => ({ ...s, password: v }))} />
          <Button size="sm" onClick={createAdmin} disabled={createBusy}>{createBusy ? 'Creating…' : 'Create admin account'}</Button>
        </div>
      )}
      {adding && (
        <div style={{ padding: '14px 20px', display: 'flex', gap: 10, alignItems: 'center', borderBottom: '1px solid var(--border-default)', background: 'var(--bg-sunken)' }}>
          <CustomSelect value={pick} onChange={setPick} placeholder="Select a user to promote" width={280} options={candidates.map((c) => ({ value: c.id, label: (c.first_name + ' ' + c.last_name).trim() + ' (' + c.email + ')' }))} />
          <Button size="sm" onClick={addAdmin} disabled={!pick}>Promote</Button>
          {candidates.length === 0 && <span style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>No other users yet.</span>}
        </div>
      )}
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 'var(--text-sm)' }}>
        <thead><tr style={{ textAlign: 'left', background: 'var(--bg-sunken)', color: 'var(--text-muted)', fontSize: 'var(--text-xs)', textTransform: 'uppercase' }}>
          <th style={{ padding: '10px 20px' }}>Name</th><th>Email</th><th>Admin since</th><th></th>
        </tr></thead>
        <tbody>
          {admins.map((u) => (
            <tr key={u.id} className="ud-row" style={{ borderTop: '1px solid var(--border-default)' }}>
              <td style={{ padding: '12px 20px', fontWeight: 600 }}>{u.first_name} {u.last_name}</td>
              <td style={{ color: 'var(--text-secondary)' }}>{u.email}</td>
              <td style={{ color: 'var(--text-muted)' }}>{new Date(u.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</td>
              <td style={{ textAlign: 'right', paddingRight: 20 }}>{u.id !== currentAdminId && <window.UdUI.Btn size="sm" variant="danger" onClick={() => remove(u.id)}>Remove</window.UdUI.Btn>}</td>
            </tr>
          ))}
          {admins.length === 0 && <tr><td colSpan={4} style={{ padding: 16, color: 'var(--text-muted)' }}>No admins found.</td></tr>}
        </tbody>
      </table>
    </div>
  );
}

function SystemSettingsScreen({ companyAddress, onUpdateAddress, adminId }) {
  const { Tabs } = window.TheUpperDeckDesignSystem_4d3294;
  const [tab, setTab] = React.useState('branding');
  return (
    <div>
      <div style={{ marginBottom: 20 }}><Tabs tabs={[{ value: 'branding', label: 'Branding' }, { value: 'about', label: 'About page' }, { value: 'users', label: 'Users & access' }]} active={tab} onChange={setTab} /></div>
      {tab === 'branding' && <BrandingPanel companyAddress={companyAddress} onUpdateAddress={onUpdateAddress} />}
      {tab === 'about' && <AboutContentPanel />}
      {tab === 'users' && <UsersPanel currentAdminId={adminId} />}
    </div>
  );
}
window.SystemSettingsScreen = SystemSettingsScreen;
