// Dashboard page — Superadmin platform overview

function Sparkline({ data, color='#2196F3', height=40, fill=true }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const w = 100;
  const pts = data.map((v,i)=>{
    const x = (i/(data.length-1))*w;
    const y = height - ((v-min)/range)*(height-4) - 2;
    return `${x},${y}`;
  }).join(' ');
  const areaPts = `0,${height} ${pts} ${w},${height}`;
  return (
    <svg width="100%" height={height} viewBox={`0 0 ${w} ${height}`} preserveAspectRatio="none" style={{display:'block'}}>
      {fill && <polygon points={areaPts} fill={color} opacity="0.12"/>}
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round"/>
    </svg>
  );
}

function StatCard({ label, value, delta, tone='blue', trend, dark }) {
  const tones = {
    cyan:'#00BCD4', blue:'#2196F3', orange:'#FF9800', green:'#2DD164', purple:'#9C27B0',
  };
  const color = tones[tone];
  const fgMuted = dark?'#9A9A9A':'#707070';
  const up = delta && !delta.startsWith('-');
  return (
    <Card dark={dark} padding={0} style={{overflow:'hidden'}}>
      <div style={{height:3, background:color}}/>
      <div style={{padding:'18px 20px'}}>
        <div style={{fontSize:11, fontWeight:700, letterSpacing:'.1em', textTransform:'uppercase', color:fgMuted}}>{label}</div>
        <div style={{display:'flex', alignItems:'flex-end', justifyContent:'space-between', marginTop:8, gap:12}}>
          <div>
            <div style={{fontFamily:'var(--font-display)', fontSize:30, fontWeight:700, letterSpacing:'-0.01em', color:dark?'#fff':'#1A1A1A', lineHeight:1}}>{value}</div>
            {delta && (
              <div style={{fontSize:12, marginTop:8, color: up?'#117A34':'#E53935', fontWeight:600, display:'inline-flex', alignItems:'center', gap:4}}>
                <Icon name={up?'arrow_up':'arrow_dn'} size={12}/> {delta}
              </div>
            )}
          </div>
          {trend && <div style={{width:90, opacity:.85}}><Sparkline data={trend} color={color}/></div>}
        </div>
      </div>
    </Card>
  );
}

function MRRChart({ dark }) {
  const max = Math.max(...MRR_TREND);
  const fgMuted = dark?'#9A9A9A':'#707070';
  const barBg = dark?'#2B2B2B':'#F5F5F5';
  return (
    <Card dark={dark}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18}}>
        <div>
          <div style={{fontSize:14, fontWeight:600, color:dark?'#fff':'#1A1A1A'}}>MRR rast (zadnjih 12 mesecev)</div>
          <div style={{fontSize:12, color:fgMuted, marginTop:2}}>Ponavljajoči mesečni prihodek · €</div>
        </div>
        <div style={{display:'flex', gap:16, alignItems:'center'}}>
          <div style={{display:'flex', alignItems:'center', gap:6, fontSize:12, color:fgMuted}}>
            <span style={{width:10, height:10, borderRadius:3, background:'linear-gradient(180deg,#00BCD4,#2196F3)'}}/>
            MRR
          </div>
          <Btn variant="ghost" size="sm" dark={dark} icon="download">Izvozi</Btn>
        </div>
      </div>
      <div style={{display:'flex', alignItems:'flex-end', gap:10, height:180, padding:'0 4px'}}>
        {MRR_TREND.map((v,i)=>{
          const h = (v/max)*100;
          const isCurrent = i===MRR_TREND.length-1;
          return (
            <div key={i} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:8, height:'100%', justifyContent:'flex-end'}}>
              <div style={{fontSize:10, fontWeight:600, color:isCurrent?'#2196F3':fgMuted}}>€{(v/1000).toFixed(1)}k</div>
              <div style={{width:'100%', height:`${h}%`, borderRadius:'8px 8px 0 0',
                background: isCurrent
                  ? 'linear-gradient(180deg,#00BCD4 0%, #2196F3 100%)'
                  : (dark?'#333':'#E3F2FD'),
                minHeight:8,
                boxShadow: isCurrent?'0 4px 12px rgba(33,150,243,.35)':'none',
                transition:'all 300ms',
              }}/>
              <div style={{fontSize:11, color:fgMuted}}>{MRR_MONTHS[i]}</div>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

function ActivityFeed({ dark }) {
  const fgMuted = dark?'#9A9A9A':'#707070';
  const items = AUDIT.slice(0,6).map(a=>{
    const iconMap = { logged_in:['zap','#2196F3'], impersonated:['shield','#FF9800'], subscription_failed:['alert','#E53935'], exported_guest_data:['download','#FF9800'], resolved_ticket:['check','#2DD164'], backup_completed:['check','#2DD164'], suspended_org:['alert','#FF9800'], integration_error:['alert','#E53935'], changed_pricing:['credit','#2196F3'], new_signup:['plus','#00BCD4'] };
    return {...a, ...(iconMap[a.action] ? {_i:iconMap[a.action][0], _c:iconMap[a.action][1]} : {_i:'dot', _c:'#9A9A9A'})};
  });
  const verb = { logged_in:'se je prijavil', impersonated:'impersoniral', subscription_failed:'neuspešno plačilo naročnine', exported_guest_data:'izvozil podatke gostov', resolved_ticket:'zaključil prijavo', backup_completed:'varnostna kopija zaključena', suspended_org:'suspendiral organizacijo', integration_error:'napaka integracije', changed_pricing:'spremenil cene', new_signup:'nova registracija' };
  return (
    <Card dark={dark}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
        <div style={{fontSize:14, fontWeight:600, color:dark?'#fff':'#1A1A1A'}}>Nedavna dejavnost</div>
        <div style={{fontSize:12, color:'#2196F3', cursor:'pointer', fontWeight:500}}>Prikaži vse →</div>
      </div>
      <div style={{display:'flex', flexDirection:'column'}}>
        {items.map((it,i)=>(
          <div key={i} style={{display:'flex', gap:12, padding:'10px 0',
            borderTop: i>0 ? `1px solid ${dark?'#2B2B2B':'#F5F5F5'}` : 'none'}}>
            <div style={{width:32, height:32, borderRadius:'50%', background:`${it._c}22`, color:it._c,
              display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
              <Icon name={it._i} size={15}/>
            </div>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontSize:13, color:dark?'#E5E5E5':'#1A1A1A', lineHeight:1.45}}>
                <span style={{fontWeight:600}}>{it.actor}</span> {verb[it.action]} <span style={{color:fgMuted}}>— {it.target}</span>
              </div>
              <div style={{fontSize:11, color:fgMuted, marginTop:2}}>{it.ts} · IP {it.ip}</div>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function TopOrgs({ dark }) {
  const sorted = [...ORGS].sort((a,b)=>b.mrr-a.mrr).slice(0,6);
  const maxMrr = sorted[0].mrr;
  const fgMuted = dark?'#9A9A9A':'#707070';
  return (
    <Card dark={dark}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
        <div style={{fontSize:14, fontWeight:600, color:dark?'#fff':'#1A1A1A'}}>Najbolj aktivne organizacije</div>
        <div style={{fontSize:12, color:fgMuted}}>Po mesečnem prihodku</div>
      </div>
      {sorted.map((o,i)=>(
        <div key={o.id} style={{padding:'10px 0', borderTop: i>0?`1px solid ${dark?'#2B2B2B':'#F5F5F5'}`:'none'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6}}>
            <div style={{display:'flex', alignItems:'center', gap:10, minWidth:0, flex:1}}>
              <div style={{width:28, height:28, borderRadius:8, background:'linear-gradient(135deg,#00BCD4,#2196F3)',
                color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:11, flexShrink:0}}>
                {o.name.split(' ').slice(0,2).map(w=>w[0]).join('')}
              </div>
              <div style={{minWidth:0}}>
                <div style={{fontSize:13, fontWeight:600, color:dark?'#fff':'#1A1A1A', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{o.name}</div>
                <div style={{fontSize:11, color:fgMuted}}>{o.city} · {o.rooms} sob · {o.plan}</div>
              </div>
            </div>
            <div style={{fontSize:13, fontWeight:700, color:dark?'#fff':'#1A1A1A'}}>€{o.mrr}</div>
          </div>
          <div style={{height:4, background:dark?'#2B2B2B':'#F5F5F5', borderRadius:999, overflow:'hidden'}}>
            <div style={{height:'100%', width:`${(o.mrr/maxMrr)*100}%`,
              background:'linear-gradient(90deg,#00BCD4,#2196F3)'}}/>
          </div>
        </div>
      ))}
    </Card>
  );
}

function SystemStatusPanel({ dark }) {
  const fgMuted = dark?'#9A9A9A':'#707070';
  return (
    <Card dark={dark}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
        <div style={{fontSize:14, fontWeight:600, color:dark?'#fff':'#1A1A1A'}}>Integracije in storitve</div>
        <Badge tone="orange">1 napaka</Badge>
      </div>
      <div style={{display:'flex', flexDirection:'column'}}>
        {INTEGRATIONS.slice(0,6).map((it,i)=>{
          const toneMap = {ok:'success', degraded:'orange', down:'danger'};
          const statusLbl = {ok:'Deluje', degraded:'Upočasnjeno', down:'Nedosegljivo'};
          return (
            <div key={it.name} 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:8, background:dark?'#2B2B2B':'#F5F5F5',
                display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:11, color:dark?'#C8C8C8':'#4D4D4D', flexShrink:0}}>{it.icon}</div>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontSize:13, fontWeight:500, color:dark?'#E5E5E5':'#1A1A1A', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{it.name}</div>
                <div style={{fontSize:11, color:fgMuted}}>{it.uptime}% uptime · {it.latency} ms</div>
              </div>
              <Badge tone={toneMap[it.status]}>{statusLbl[it.status]}</Badge>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

function DashboardPage({ dark, onNav }) {
  const activeOrgs = ORGS.filter(o=>o.status==='active').length;
  const totalMrr = ORGS.reduce((s,o)=>s+o.mrr,0);
  const pastDue = ORGS.filter(o=>o.status==='past_due').length;
  const openTickets = TICKETS.filter(t=>t.status==='open' || t.status==='in_progress').length;

  return (
    <>
      <PageHeader
        dark={dark}
        title="Nadzorna plošča platforme"
        subtitle="Pregled zdravja celotne clickinPMS platforme. Dober dan, Andrej — danes je 23. april 2026."
        actions={<>
          <Btn variant="ghost" dark={dark} icon="download">Tedensko poročilo</Btn>
          <Btn variant="primary" icon="plus" onClick={()=>onNav('organizations')}>Nova organizacija</Btn>
        </>}
      />

      <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:16, marginBottom:20}}>
        <StatCard dark={dark} tone="blue"   label="Aktivne organizacije" value={activeOrgs} delta="+2 ta mesec" trend={[8,8,9,9,10,10,10,11,11,11,11,activeOrgs]}/>
        <StatCard dark={dark} tone="cyan"   label="MRR"                  value={`€ ${totalMrr.toLocaleString('sl-SI')}`} delta="+5,6 %" trend={MRR_TREND}/>
        <StatCard dark={dark} tone="orange" label="Odprte prijave"        value={openTickets}   delta="+3 danes" trend={[2,3,3,4,3,5,4,3,5,4,5,openTickets]}/>
        <StatCard dark={dark} tone="green"  label="Aktivni uporabniki" value={USERS.filter(u=>u.status==='active').length} delta="+1 ta teden" trend={[9,10,10,11,11,12,12,12,12,13,13,13]}/>
      </div>

      {pastDue>0 && (
        <div style={{
          background: dark?'rgba(255,152,0,.1)':'#FFF3E0',
          border:`1px solid ${dark?'rgba(255,152,0,.3)':'#FFE0B2'}`,
          borderRadius:12, padding:'14px 18px', marginBottom:20,
          display:'flex', alignItems:'center', gap:14,
        }}>
          <div style={{width:36, height:36, borderRadius:10, background:'#FF9800', color:'#fff',
            display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
            <Icon name="alert" size={18}/>
          </div>
          <div style={{flex:1}}>
            <div style={{fontWeight:600, color:dark?'#fff':'#E65100', fontSize:14}}>{pastDue} organizacija ima zapadlo naročnino</div>
            <div style={{fontSize:13, color:dark?'#C8C8C8':'#BF5A00', marginTop:2}}>Piran Seaside Inn (INV-4082, €149) — 8 dni po roku plačila</div>
          </div>
          <Btn variant="ghost" dark={dark} onClick={()=>onNav('billing')}>Pojdi na Naročnine</Btn>
          <Btn variant="primary" size="sm">Pošlji opomin</Btn>
        </div>
      )}

      <div style={{display:'grid', gridTemplateColumns:'1.6fr 1fr', gap:16, marginBottom:16}}>
        <MRRChart dark={dark}/>
        <TopOrgs dark={dark}/>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16}}>
        <ActivityFeed dark={dark}/>
        <SystemStatusPanel dark={dark}/>
      </div>
    </>
  );
}

Object.assign(window, { DashboardPage, Sparkline, StatCard });
