// Organizations, Users, Billing, Support, System, Audit, Settings, Org Detail

function Table({ columns, rows, dark, onRowClick }) {
  const fgMuted = dark?'#9A9A9A':'#707070';
  const border = dark?'#2B2B2B':'#F0F0F0';
  return (
    <div style={{overflow:'auto'}}>
      <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
        <thead>
          <tr style={{background:dark?'#1A1A1A':'#FAFAFA'}}>
            {columns.map(c=>(
              <th key={c.key} style={{
                padding:'12px 18px', textAlign:c.align||'left', fontWeight:600,
                fontSize:11, letterSpacing:'.1em', textTransform:'uppercase',
                color:fgMuted, borderBottom:`1px solid ${border}`, whiteSpace:'nowrap',
              }}>{c.label}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((r,i)=>(
            <tr key={i} onClick={()=>onRowClick && onRowClick(r)}
              style={{borderBottom:`1px solid ${border}`, cursor:onRowClick?'pointer':'default', transition:'background 80ms'}}
              onMouseEnter={e=>{ if(onRowClick) e.currentTarget.style.background=dark?'#222':'#FAFAFA'; }}
              onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
              {columns.map(c=>(
                <td key={c.key} style={{padding:'13px 18px', color:dark?'#E5E5E5':'#1A1A1A', verticalAlign:'middle', textAlign:c.align||'left'}}>
                  {c.render ? c.render(r) : r[c.key]}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function FilterBar({ dark, filters, children }) {
  return (
    <div style={{display:'flex', gap:10, marginBottom:16, alignItems:'center', flexWrap:'wrap'}}>
      <div style={{position:'relative', flex:1, minWidth:240, maxWidth:360}}>
        <div style={{position:'absolute', left:12, top:'50%', transform:'translateY(-50%)', color:dark?'#9A9A9A':'#9A9A9A'}}>
          <Icon name="search" size={14}/>
        </div>
        <input placeholder="Iskanje…" style={{
          width:'100%', padding:'9px 12px 9px 34px', fontSize:13,
          background: dark?'#1A1A1A':'#fff', color:dark?'#fff':'#1A1A1A',
          border:`1px solid ${dark?'#2B2B2B':'#E5E5E5'}`, borderRadius:10,
          fontFamily:'inherit', outline:'none',
        }}/>
      </div>
      {filters && filters.map((f,i)=>(
        <select key={i} style={{
          padding:'9px 12px', fontSize:13,
          background:dark?'#1A1A1A':'#fff', color:dark?'#fff':'#1A1A1A',
          border:`1px solid ${dark?'#2B2B2B':'#E5E5E5'}`, borderRadius:10, fontFamily:'inherit', cursor:'pointer',
        }}>
          {f.map(o=><option key={o}>{o}</option>)}
        </select>
      ))}
      <Btn variant="ghost" dark={dark} size="sm" icon="filter">Več filtrov</Btn>
      <div style={{marginLeft:'auto', display:'flex', gap:8}}>{children}</div>
    </div>
  );
}

// ═════ ORGANIZATIONS ═════
function OrganizationsPage({ dark, onOpenOrg, onNav }) {
  const planTone = {Enterprise:'purple', Pro:'blue', Starter:'neutral'};
  const statusMap = {active:['success','Aktivna'], trial:['cyan','Poskusna'], past_due:['orange','Zapadlo'], suspended:['danger','Suspendirana']};

  return (
    <>
      <PageHeader
        dark={dark}
        title="Organizacije"
        subtitle={`${ORGS.length} organizacij · ${ORGS.reduce((s,o)=>s+o.rooms,0)} sob · ${ORGS.filter(o=>o.status==='active').length} aktivnih`}
        actions={<>
          <Btn variant="ghost" dark={dark} icon="download">Izvozi CSV</Btn>
          <Btn variant="primary" icon="plus">Nova organizacija</Btn>
        </>}
      />
      <FilterBar dark={dark} filters={[
        ['Vsi paketi','Starter','Pro','Enterprise'],
        ['Vsi statusi','Aktivne','Poskusne','Zapadle','Suspendirane'],
        ['Vse regije','Osrednja SI','Primorska','Štajerska','Gorenjska'],
      ]}/>
      <Card dark={dark} padding={0} style={{overflow:'hidden'}}>
        <Table dark={dark} onRowClick={onOpenOrg}
          columns={[
            {key:'name', label:'Organizacija', render:r=>(
              <div style={{display:'flex', alignItems:'center', gap:12}}>
                <div style={{width:34, height:34, borderRadius:8, background:'linear-gradient(135deg,#00BCD4,#2196F3)',
                  color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:12}}>
                  {r.name.split(' ').slice(0,2).map(w=>w[0]).join('')}
                </div>
                <div>
                  <div style={{fontWeight:600}}>{r.name}</div>
                  <div style={{fontSize:11, color:dark?'#9A9A9A':'#707070'}}>{r.city} · {r.owner}</div>
                </div>
              </div>
            )},
            {key:'plan', label:'Paket', render:r=><Badge tone={planTone[r.plan]}>{r.plan}</Badge>},
            {key:'rooms', label:'Sobe', align:'right', render:r=><span>{r.rooms}</span>},
            {key:'properties', label:'Lokacije', align:'right', render:r=><span>{r.properties}</span>},
            {key:'occupancy', label:'Zasedenost', render:r=>(
              <div style={{display:'flex', alignItems:'center', gap:8}}>
                <div style={{width:60, height:6, background:dark?'#2B2B2B':'#F0F0F0', borderRadius:999, overflow:'hidden'}}>
                  <div style={{width:`${r.occupancy}%`, height:'100%', background:r.occupancy>80?'#2DD164':r.occupancy>50?'#2196F3':'#FF9800'}}/>
                </div>
                <span style={{fontSize:12, fontWeight:600, minWidth:32}}>{r.occupancy}%</span>
              </div>
            )},
            {key:'mrr', label:'MRR', align:'right', render:r=><span style={{fontWeight:600}}>€{r.mrr}</span>},
            {key:'status', label:'Status', render:r=><Badge tone={statusMap[r.status][0]}>{statusMap[r.status][1]}</Badge>},
            {key:'lastActive', label:'Zadnja aktivnost', render:r=><span style={{fontSize:12, color:dark?'#9A9A9A':'#707070'}}>{r.lastActive}</span>},
          ]}
          rows={ORGS}/>
      </Card>
    </>
  );
}

function OrgDetailPage({ org, dark, onBack }) {
  const fgMuted = dark?'#9A9A9A':'#707070';
  const orgUsers = USERS.filter(u=>u.org===org.name);
  const orgTickets = TICKETS.filter(t=>t.org===org.name);
  const orgInvoices = INVOICES.filter(i=>i.org===org.name);
  return (
    <>
      <PageHeader
        dark={dark}
        breadcrumbs={['Organizacije', org.name]}
        title={org.name}
        subtitle={`${org.city} · Lastnik: ${org.owner} · ${org.plan} · Registrirana ${org.signup}`}
        actions={<>
          <Btn variant="ghost" dark={dark} onClick={onBack}>← Nazaj</Btn>
          <Btn variant="ghost" dark={dark} icon="ext">Impersoniraj</Btn>
          <Btn variant="danger">Suspendiraj</Btn>
        </>}
      />
      <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:16}}>
        <StatCard dark={dark} tone="blue"   label="Sobe"       value={org.rooms}/>
        <StatCard dark={dark} tone="cyan"   label="Zasedenost" value={`${org.occupancy}%`}/>
        <StatCard dark={dark} tone="green"  label="MRR"        value={`€${org.mrr}`}/>
        <StatCard dark={dark} tone="orange" label="Uporabniki" value={orgUsers.length}/>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:16}}>
        <Card dark={dark}>
          <div style={{fontSize:14, fontWeight:600, marginBottom:14, color:dark?'#fff':'#1A1A1A'}}>Uporabniki organizacije</div>
          {orgUsers.length===0 && <div style={{fontSize:13, color:fgMuted}}>Ni uporabnikov.</div>}
          {orgUsers.map((u,i)=>(
            <div key={u.id} style={{display:'flex', alignItems:'center', gap:12, padding:'10px 0', borderTop:i>0?`1px solid ${dark?'#2B2B2B':'#F5F5F5'}`:'none'}}>
              <div style={{width:32, height:32, borderRadius:'50%', background:'#E3F2FD', color:'#2196F3',
                display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:11}}>
                {u.name.split(' ').map(w=>w[0]).join('')}
              </div>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontSize:13, fontWeight:600, color:dark?'#fff':'#1A1A1A'}}>{u.name}</div>
                <div style={{fontSize:11, color:fgMuted}}>{u.email} · {u.role}</div>
              </div>
              <Badge tone={u.status==='active'?'success':u.status==='invited'?'cyan':'danger'}>{u.status}</Badge>
            </div>
          ))}
        </Card>

        <Card dark={dark}>
          <div style={{fontSize:14, fontWeight:600, marginBottom:14, color:dark?'#fff':'#1A1A1A'}}>Odprte prijave</div>
          {orgTickets.length===0 && <div style={{fontSize:13, color:fgMuted}}>Nobene odprte prijave.</div>}
          {orgTickets.map((t,i)=>(
            <div key={t.id} style={{padding:'10px 0', borderTop:i>0?`1px solid ${dark?'#2B2B2B':'#F5F5F5'}`:'none'}}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:4}}>
                <div style={{fontSize:12, fontWeight:600, color:'#2196F3'}}>{t.id}</div>
                <Badge tone={t.priority==='urgent'?'danger':t.priority==='high'?'orange':'neutral'}>{t.priority}</Badge>
              </div>
              <div style={{fontSize:13, color:dark?'#E5E5E5':'#1A1A1A'}}>{t.subject}</div>
              <div style={{fontSize:11, color:fgMuted, marginTop:4}}>{t.opened} · {t.messages} sporočil</div>
            </div>
          ))}
        </Card>
      </div>

      <Card dark={dark}>
        <div style={{fontSize:14, fontWeight:600, marginBottom:14, color:dark?'#fff':'#1A1A1A'}}>Računi in naročnine</div>
        <Table dark={dark}
          columns={[
            {key:'id', label:'Račun', render:r=><span style={{fontWeight:600, color:'#2196F3'}}>{r.id}</span>},
            {key:'amount', label:'Znesek', align:'right', render:r=><span style={{fontWeight:600}}>€{r.amount}</span>},
            {key:'due', label:'Rok plačila'},
            {key:'paid', label:'Plačano', render:r=>r.paid || <span style={{color:fgMuted}}>—</span>},
            {key:'status', label:'Status', render:r=>{
              const m = {paid:['success','Plačano'], past_due:['danger','Zapadlo'], trial:['cyan','Poskus'], void:['neutral','Stornirano']};
              return <Badge tone={m[r.status][0]}>{m[r.status][1]}</Badge>;
            }},
          ]}
          rows={orgInvoices}/>
      </Card>
    </>
  );
}

// ═════ USERS ═════
function UsersPage({ dark }) {
  const statusMap = {active:['success','Aktiven'], invited:['cyan','Povabljen'], suspended:['danger','Suspendiran']};
  const roleColor = { 'Superadmin':'purple','Hotel Admin':'blue','Front Desk Mgr':'cyan','Receptionist':'neutral','Housekeeping':'orange','Support Agent':'cyan' };
  return (
    <>
      <PageHeader dark={dark} title="Uporabniki" subtitle={`${USERS.length} uporabnikov na platformi · ${USERS.filter(u=>u.twofa).length} z 2FA`}
        actions={<>
          <Btn variant="ghost" dark={dark} icon="download">Izvozi CSV</Btn>
          <Btn variant="primary" icon="plus">Povabi uporabnika</Btn>
        </>}/>
      <FilterBar dark={dark} filters={[['Vse vloge','Superadmin','Hotel Admin','Receptionist','Housekeeping','Support Agent'],['Vsi statusi','Aktivni','Povabljeni','Suspendirani'],['Vse organizacije']]}/>
      <Card dark={dark} padding={0} style={{overflow:'hidden'}}>
        <Table dark={dark}
          columns={[
            {key:'name', label:'Uporabnik', render:r=>(
              <div style={{display:'flex', alignItems:'center', gap:12}}>
                <div style={{width:34, height:34, borderRadius:'50%', background:'linear-gradient(135deg,#64B5F6,#2196F3)',
                  color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:12}}>
                  {r.name.split(' ').map(w=>w[0]).join('')}
                </div>
                <div><div style={{fontWeight:600}}>{r.name}</div><div style={{fontSize:11, color:dark?'#9A9A9A':'#707070'}}>{r.email}</div></div>
              </div>
            )},
            {key:'role', label:'Vloga', render:r=><Badge tone={roleColor[r.role]||'neutral'}>{r.role}</Badge>},
            {key:'org', label:'Organizacija'},
            {key:'twofa', label:'2FA', render:r=>r.twofa
              ? <Badge tone="success">Omogočeno</Badge>
              : <Badge tone="neutral">Brez</Badge>},
            {key:'last', label:'Zadnja prijava', render:r=><span style={{fontSize:12, color:dark?'#9A9A9A':'#707070'}}>{r.last}</span>},
            {key:'status', label:'Status', render:r=><Badge tone={statusMap[r.status][0]}>{statusMap[r.status][1]}</Badge>},
          ]} rows={USERS}/>
      </Card>
    </>
  );
}

// ═════ BILLING ═════
function BillingPage({ dark }) {
  const total = INVOICES.reduce((s,i)=>i.status==='paid'?s+i.amount:s,0);
  const pastDue = INVOICES.filter(i=>i.status==='past_due').reduce((s,i)=>s+i.amount,0);
  const statusMap = {paid:['success','Plačano'], past_due:['danger','Zapadlo'], trial:['cyan','Poskus'], void:['neutral','Stornirano']};
  return (
    <>
      <PageHeader dark={dark} title="Naročnine in plačila" subtitle="Pregled prihodkov, naročnin in izdanih računov v tekočem mesecu"
        actions={<>
          <Btn variant="ghost" dark={dark} icon="download">Izvozi za računovodstvo</Btn>
          <Btn variant="primary" icon="plus">Ročni račun</Btn>
        </>}/>
      <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:20}}>
        <StatCard dark={dark} tone="cyan"   label="MRR"                  value={`€${ORGS.reduce((s,o)=>s+o.mrr,0).toLocaleString('sl-SI')}`} delta="+5,6 %"/>
        <StatCard dark={dark} tone="green"  label="Plačano ta mesec"     value={`€${total.toLocaleString('sl-SI')}`} delta="+8,2 %"/>
        <StatCard dark={dark} tone="orange" label="Zapadlo"              value={`€${pastDue}`} delta="+€149"/>
        <StatCard dark={dark} tone="blue"   label="ARPU"                 value="€574" delta="+2,1 %"/>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:16, marginBottom:20}}>
        <Card dark={dark}>
          <div style={{fontSize:14, fontWeight:600, marginBottom:14, color:dark?'#fff':'#1A1A1A'}}>Razporeditev po paketih</div>
          {['Enterprise','Pro','Starter'].map(p=>{
            const count = ORGS.filter(o=>o.plan===p).length;
            const mrr = ORGS.filter(o=>o.plan===p).reduce((s,o)=>s+o.mrr,0);
            const maxMrr = ORGS.reduce((s,o)=>s+o.mrr,0);
            const color = p==='Enterprise'?'#9C27B0':p==='Pro'?'#2196F3':'#9A9A9A';
            return (
              <div key={p} style={{marginBottom:14}}>
                <div style={{display:'flex', justifyContent:'space-between', fontSize:13, marginBottom:6}}>
                  <span style={{color:dark?'#E5E5E5':'#1A1A1A', fontWeight:600}}>{p} <span style={{color:dark?'#9A9A9A':'#707070', fontWeight:400, marginLeft:6}}>{count} org.</span></span>
                  <span style={{fontWeight:700, color:dark?'#fff':'#1A1A1A'}}>€{mrr.toLocaleString('sl-SI')}</span>
                </div>
                <div style={{height:10, background:dark?'#2B2B2B':'#F5F5F5', borderRadius:999, overflow:'hidden'}}>
                  <div style={{width:`${(mrr/maxMrr)*100}%`, height:'100%', background:color}}/>
                </div>
              </div>
            );
          })}
        </Card>
        <Card dark={dark}>
          <div style={{fontSize:14, fontWeight:600, marginBottom:14, color:dark?'#fff':'#1A1A1A'}}>Plačilne metode</div>
          {[['SEPA direktna bremenitev',8,'#2196F3'],['Kreditna kartica (Stripe)',3,'#00BCD4'],['Bančno nakazilo',1,'#FF9800']].map(([m,c,col])=>(
            <div key={m} style={{display:'flex', alignItems:'center', gap:12, marginBottom:12}}>
              <div style={{width:8, height:8, borderRadius:'50%', background:col}}/>
              <div style={{flex:1, fontSize:13, color:dark?'#E5E5E5':'#1A1A1A'}}>{m}</div>
              <div style={{fontSize:13, fontWeight:600}}>{c}</div>
            </div>
          ))}
        </Card>
      </div>

      <Card dark={dark} padding={0} style={{overflow:'hidden'}}>
        <div style={{padding:'18px 20px', borderBottom:`1px solid ${dark?'#2B2B2B':'#F0F0F0'}`, display:'flex', justifyContent:'space-between', alignItems:'center'}}>
          <div style={{fontSize:14, fontWeight:600, color:dark?'#fff':'#1A1A1A'}}>Izdani računi — april 2026</div>
          <Badge tone="orange">1 zapadel</Badge>
        </div>
        <Table dark={dark}
          columns={[
            {key:'id', label:'Račun', render:r=><span style={{fontWeight:600, color:'#2196F3'}}>{r.id}</span>},
            {key:'org', label:'Organizacija'},
            {key:'amount', label:'Znesek', align:'right', render:r=><span style={{fontWeight:600}}>€{r.amount}</span>},
            {key:'due', label:'Rok'},
            {key:'paid', label:'Plačano', render:r=>r.paid || <span style={{color:dark?'#9A9A9A':'#707070'}}>—</span>},
            {key:'status', label:'Status', render:r=><Badge tone={statusMap[r.status][0]}>{statusMap[r.status][1]}</Badge>},
          ]} rows={INVOICES}/>
      </Card>
    </>
  );
}

// ═════ SUPPORT ═════
function SupportPage({ dark }) {
  const pMap = {urgent:['danger','Nujno'], high:['orange','Visoko'], med:['cyan','Srednje'], low:['neutral','Nizko']};
  const sMap = {open:['orange','Odprto'], in_progress:['blue','V obdelavi'], waiting:['neutral','Čaka'], resolved:['success','Zaključeno']};
  return (
    <>
      <PageHeader dark={dark} title="Podpora" subtitle={`${TICKETS.filter(t=>t.status!=='resolved').length} odprtih prijav · povprečni čas odziva 42 min`}
        actions={<><Btn variant="ghost" dark={dark} icon="book">Baza znanja</Btn><Btn variant="primary" icon="plus">Nova prijava</Btn></>}/>
      <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:20}}>
        <StatCard dark={dark} tone="orange" label="Odprto"       value={TICKETS.filter(t=>t.status==='open').length}/>
        <StatCard dark={dark} tone="blue"   label="V obdelavi"   value={TICKETS.filter(t=>t.status==='in_progress').length}/>
        <StatCard dark={dark} tone="cyan"   label="Čaka stranko" value={TICKETS.filter(t=>t.status==='waiting').length}/>
        <StatCard dark={dark} tone="green"  label="Zaključeno"   value={TICKETS.filter(t=>t.status==='resolved').length}/>
      </div>
      <FilterBar dark={dark} filters={[['Vse prioritete','Nujno','Visoko','Srednje','Nizko'],['Vsi statusi','Odprto','V obdelavi','Čaka','Zaključeno']]}/>
      <Card dark={dark} padding={0} style={{overflow:'hidden'}}>
        <Table dark={dark}
          columns={[
            {key:'id', label:'Št.', render:r=><span style={{fontWeight:600, color:'#2196F3'}}>{r.id}</span>},
            {key:'subject', label:'Zadeva', render:r=><div style={{maxWidth:340}}><div style={{fontWeight:500}}>{r.subject}</div><div style={{fontSize:11, color:dark?'#9A9A9A':'#707070', marginTop:2}}>{r.messages} sporočil</div></div>},
            {key:'org', label:'Organizacija'},
            {key:'priority', label:'Prioriteta', render:r=><Badge tone={pMap[r.priority][0]}>{pMap[r.priority][1]}</Badge>},
            {key:'status', label:'Status', render:r=><Badge tone={sMap[r.status][0]}>{sMap[r.status][1]}</Badge>},
            {key:'agent', label:'Agent', render:r=>r.agent || <span style={{color:dark?'#9A9A9A':'#707070', fontStyle:'italic'}}>nedodeljeno</span>},
            {key:'opened', label:'Odprto', render:r=><span style={{fontSize:12, color:dark?'#9A9A9A':'#707070'}}>{r.opened}</span>},
          ]} rows={TICKETS}/>
      </Card>
    </>
  );
}

// ═════ SYSTEM ═════
function SystemPage({ dark }) {
  const toneMap = {ok:'success', degraded:'orange', down:'danger'};
  const lbl = {ok:'Deluje', degraded:'Upočasnjeno', down:'Nedosegljivo'};
  return (
    <>
      <PageHeader dark={dark} title="Sistem in integracije" subtitle="Zdravje platforme in zunanjih povezav v realnem času"
        actions={<><Btn variant="ghost" dark={dark} icon="download">Poročilo uptime</Btn><Btn variant="primary" icon="zap">Ponovno poveži vse</Btn></>}/>

      <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:20}}>
        <StatCard dark={dark} tone="green"  label="Uptime 30 dni"      value="99,94 %"/>
        <StatCard dark={dark} tone="blue"   label="API p95"            value="184 ms"/>
        <StatCard dark={dark} tone="cyan"   label="Sinhronizacij/dan"  value="14.2k"/>
        <StatCard dark={dark} tone="orange" label="Napake 24 ur"       value="3"/>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:16}}>
        <Card dark={dark}>
          <div style={{fontSize:14, fontWeight:600, marginBottom:14, color:dark?'#fff':'#1A1A1A'}}>Integracije</div>
          {INTEGRATIONS.map((it,i)=>(
            <div key={it.name} style={{display:'flex', alignItems:'center', gap:14, padding:'14px 0', borderTop:i>0?`1px solid ${dark?'#2B2B2B':'#F5F5F5'}`:'none'}}>
              <div style={{width:40, height:40, borderRadius:10, background:dark?'#2B2B2B':'#F5F5F5',
                display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, color:dark?'#C8C8C8':'#4D4D4D'}}>{it.icon}</div>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontSize:14, fontWeight:600, color:dark?'#fff':'#1A1A1A'}}>{it.name}</div>
                <div style={{fontSize:12, color:dark?'#9A9A9A':'#707070', marginTop:2}}>Zadnja sinhronizacija: {it.lastSync} · Latenca: {it.latency} ms</div>
              </div>
              <div style={{textAlign:'right'}}>
                <Badge tone={toneMap[it.status]}>{lbl[it.status]}</Badge>
                <div style={{fontSize:11, color:dark?'#9A9A9A':'#707070', marginTop:4}}>{it.uptime}% uptime</div>
              </div>
              <Btn variant="ghost" dark={dark} size="sm">Nastavi</Btn>
            </div>
          ))}
        </Card>
        <Card dark={dark}>
          <div style={{fontSize:14, fontWeight:600, marginBottom:14, color:dark?'#fff':'#1A1A1A'}}>Podatkovni centri</div>
          {[['EU-Fra-1 (Frankfurt)','primary','ok',12],['EU-Hel-1 (Helsinki)','replica','ok',48],['Backup (Ljubljana)','backup','ok',null]].map(([n,role,st,lag])=>(
            <div key={n} style={{padding:'14px 0', borderBottom:`1px solid ${dark?'#2B2B2B':'#F5F5F5'}`}}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6}}>
                <div style={{fontSize:13, fontWeight:600, color:dark?'#fff':'#1A1A1A'}}>{n}</div>
                <Badge tone="success">Online</Badge>
              </div>
              <div style={{fontSize:11, color:dark?'#9A9A9A':'#707070'}}>{role}{lag!==null && ` · zamik ${lag} ms`}</div>
            </div>
          ))}
          <div style={{fontSize:12, color:dark?'#9A9A9A':'#707070', marginTop:12, lineHeight:1.5}}>
            Podatki so shranjeni znotraj EU v skladu z GDPR in Zakonom o varstvu osebnih podatkov (ZVOP-2).
          </div>
        </Card>
      </div>
    </>
  );
}

// ═════ AUDIT ═════
function AuditPage({ dark }) {
  const levelMap = {info:'blue', warn:'orange', error:'danger'};
  return (
    <>
      <PageHeader dark={dark} title="Dnevnik dogodkov" subtitle="Varnostni in administrativni dogodki zadnjih 30 dni"
        actions={<><Btn variant="ghost" dark={dark} icon="download">Izvozi dnevnik</Btn><Btn variant="primary" icon="filter">Napredno iskanje</Btn></>}/>
      <FilterBar dark={dark} filters={[['Vsi akterji','Superadmin','Sistem','Hotel Admin'],['Vse stopnje','Info','Opozorilo','Napaka'],['Zadnjih 24 ur','7 dni','30 dni']]}/>
      <Card dark={dark} padding={0} style={{overflow:'hidden'}}>
        <Table dark={dark}
          columns={[
            {key:'ts', label:'Čas', render:r=><span style={{fontFamily:'var(--font-mono)', fontSize:12, color:dark?'#C8C8C8':'#4D4D4D'}}>23.04 · {r.ts}</span>},
            {key:'level', label:'Stopnja', render:r=><Badge tone={levelMap[r.level]}>{r.level.toUpperCase()}</Badge>},
            {key:'actor', label:'Akter', render:r=><span style={{fontWeight:600}}>{r.actor}</span>},
            {key:'action', label:'Dogodek', render:r=><span style={{fontFamily:'var(--font-mono)', fontSize:12, color:'#2196F3'}}>{r.action}</span>},
            {key:'target', label:'Cilj', render:r=><span style={{color:dark?'#C8C8C8':'#4D4D4D'}}>{r.target}</span>},
            {key:'ip', label:'IP', render:r=><span style={{fontFamily:'var(--font-mono)', fontSize:12, color:dark?'#9A9A9A':'#707070'}}>{r.ip}</span>},
          ]} rows={AUDIT}/>
      </Card>
    </>
  );
}

// ═════ SETTINGS ═════
function SettingsPage({ dark }) {
  const [tab, setTab] = React.useState('plans');
  const tabs = [['plans','Paketi in cene'],['features','Funkcionalnosti'],['branding','Blagovna znamka'],['regions','Regije'],['security','Varnost']];
  const fgMuted = dark?'#9A9A9A':'#707070';
  return (
    <>
      <PageHeader dark={dark} title="Nastavitve platforme" subtitle="Globalna konfiguracija, paketi, funkcionalnosti in varnostne politike"/>
      <div style={{display:'flex', gap:4, marginBottom:20, borderBottom:`1px solid ${dark?'#2B2B2B':'#E5E5E5'}`, overflowX:'auto'}}>
        {tabs.map(([k,l])=>(
          <button key={k} onClick={()=>setTab(k)} style={{
            padding:'10px 16px', border:'none', background:'transparent',
            fontSize:14, fontFamily:'inherit', cursor:'pointer',
            color: tab===k ? '#2196F3' : fgMuted,
            fontWeight: tab===k ? 600 : 500,
            borderBottom: tab===k ? '2px solid #2196F3' : '2px solid transparent',
            marginBottom:-1, whiteSpace:'nowrap',
          }}>{l}</button>
        ))}
      </div>

      {tab==='plans' && (
        <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:16}}>
          {[
            {name:'Starter', price:149, rooms:'do 25', props:1, features:['Rezervacije in check-in','Osnovni kanali (Booking.com)','E-mail podpora','FURS davčna blagajna'], color:'#9A9A9A'},
            {name:'Pro', price:389, rooms:'do 100', props:3, features:['Vse iz Starter','Vsi kanali + channel manager','Guest self-checkin','Poročila in analitika','24/7 telefonska podpora'], color:'#2196F3', featured:true},
            {name:'Enterprise', price:1890, rooms:'neomejeno', props:'neomejeno', features:['Vse iz Pro','Kioski in POS','Multi-property',+'Custom integracije','Dedicated account manager','SLA 99,99 %'], color:'#9C27B0'},
          ].map(p=>(
            <Card key={p.name} dark={dark} padding={0} style={{overflow:'hidden', borderColor: p.featured ? '#2196F3':undefined, borderWidth: p.featured?2:1, borderStyle:'solid'}}>
              {p.featured && <div style={{background:'linear-gradient(90deg,#00BCD4,#2196F3)', color:'#fff', fontSize:11, fontWeight:700, textAlign:'center', padding:'6px', letterSpacing:'.1em', textTransform:'uppercase'}}>Najbolj priljubljen</div>}
              <div style={{padding:24}}>
                <div style={{fontSize:12, fontWeight:700, letterSpacing:'.12em', textTransform:'uppercase', color:p.color}}>{p.name}</div>
                <div style={{display:'flex', alignItems:'baseline', gap:4, marginTop:10}}>
                  <div style={{fontFamily:'var(--font-display)', fontSize:42, fontWeight:800, color:dark?'#fff':'#1A1A1A', lineHeight:1}}>€{p.price}</div>
                  <div style={{fontSize:13, color:fgMuted}}>/ mesec</div>
                </div>
                <div style={{fontSize:12, color:fgMuted, marginTop:8}}>{p.rooms} sob · {p.props} lokacij</div>
                <div style={{height:1, background:dark?'#2B2B2B':'#F0F0F0', margin:'18px 0'}}/>
                {p.features.map(f=>(
                  <div key={f} style={{display:'flex', gap:10, padding:'6px 0', fontSize:13, color:dark?'#E5E5E5':'#1A1A1A'}}>
                    <Icon name="check" size={16} color="#2DD164"/>{f}
                  </div>
                ))}
                <Btn variant={p.featured?'primary':'ghost'} dark={dark} style={{marginTop:18, width:'100%', justifyContent:'center'}}>Uredi paket</Btn>
              </div>
            </Card>
          ))}
        </div>
      )}

      {tab==='features' && (
        <Card dark={dark}>
          {[
            ['Channel Manager','Sinhronizacija Booking.com, Expedia, Airbnb',true],
            ['Samopostrežni kiosk','Check-in brez recepcije',true],
            ['Digitalni ključi','Mobile key preko Bluetooth',true],
            ['AI Pricing','Dinamično oblikovanje cen glede na povpraševanje',false],
            ['WhatsApp integracija','Komunikacija z gosti preko WhatsApp',true],
            ['Loyalty program','Točke zvestobe in popusti',false],
            ['FURS davčna blagajna','Obvezno za slovensko tržišče',true],
            ['AJPES poročanje','Avtomatsko poročanje gostov',true],
          ].map(([n,d,on],i)=>(
            <div key={n} style={{display:'flex', alignItems:'center', gap:14, padding:'14px 0', borderTop:i>0?`1px solid ${dark?'#2B2B2B':'#F5F5F5'}`:'none'}}>
              <div style={{flex:1}}>
                <div style={{fontSize:14, fontWeight:600, color:dark?'#fff':'#1A1A1A'}}>{n}</div>
                <div style={{fontSize:12, color:fgMuted, marginTop:2}}>{d}</div>
              </div>
              <Toggle on={on} dark={dark}/>
            </div>
          ))}
        </Card>
      )}

      {tab==='branding' && <Card dark={dark}><div style={{fontSize:14, color:fgMuted}}>White-label konfiguracija — logotipi, barve, domene, e-mail predloge.</div></Card>}
      {tab==='regions' && <Card dark={dark}><div style={{fontSize:14, color:fgMuted}}>Aktivne regije: Slovenija (primarna), Hrvaška, Avstrija. Davčne stopnje in lokalizacija.</div></Card>}
      {tab==='security' && (
        <Card dark={dark}>
          <div style={{fontSize:14, fontWeight:600, marginBottom:16, color:dark?'#fff':'#1A1A1A'}}>Varnostne politike</div>
          {[['Obvezni 2FA za Superadmine',true],['Obvezni 2FA za Hotel Admine',true],['SSO (SAML 2.0)',false],['IP whitelist za admin konzolo',false],['Samodejna odjava po 30 min',true],['Zakasnitev po 5 neuspelih prijavah',true]].map(([l,on],i)=>(
            <div key={l} style={{display:'flex', alignItems:'center', gap:14, padding:'12px 0', borderTop:i>0?`1px solid ${dark?'#2B2B2B':'#F5F5F5'}`:'none'}}>
              <div style={{flex:1, fontSize:14, color:dark?'#E5E5E5':'#1A1A1A'}}>{l}</div>
              <Toggle on={on} dark={dark}/>
            </div>
          ))}
        </Card>
      )}
    </>
  );
}

function Toggle({ on, dark }) {
  const [v, setV] = React.useState(on);
  return (
    <button onClick={()=>setV(!v)} style={{
      width:44, height:24, borderRadius:999, border:'none',
      background: v?'#2196F3':(dark?'#333':'#E5E5E5'), cursor:'pointer', padding:0,
      position:'relative', transition:'background 120ms',
    }}>
      <span style={{position:'absolute', top:2, left: v?22:2, width:20, height:20, borderRadius:'50%', background:'#fff', transition:'left 120ms', boxShadow:'0 1px 3px rgba(0,0,0,.2)'}}/>
    </button>
  );
}

Object.assign(window, { OrganizationsPage, OrgDetailPage, UsersPage, BillingPage, SupportPage, SystemPage, AuditPage, SettingsPage });
