// ── Tüketim İzleme Sayfası — NEXOR · İzmir Ana Tesis · Elektrik / Doğal Gaz / Su ─────

// Elektrik verileri
const ELEC_DAILY = [31200,33400,35800,32900,36400,38240,37100,35600,34200,39100,37400,35100,33800,38240];
const ELEC_HOURLY = [920,1080,980,1440,2480,3640,4020,4280,3960,4180,3520,2710,3480,4060,4280,3980,4120,3760,3940,3520,3180,2840,2480,2100];
const ELEC_METERS = [
  { id:'SAY-001', name:'Ana Geliş Fideri',      col1:'399 V', col2:'2.420 A', col3:'1.682 kW', col4:'0.94', col5:'3.2%', col6:'14.380', status:'ok' },
  { id:'SAY-002', name:'Haddehane Hattı 1+2',   col1:'397 V', col2:'1.860 A', col3:'1.294 kW', col4:'0.91', col5:'4.5%', col6:'12.200', status:'ok' },
  { id:'SAY-003', name:'Fırın Grubu 1+2',       col1:'401 V', col2:'1.920 A', col3:'1.334 kW', col4:'0.88', col5:'6.8%', col6:'13.300', status:'warn' },
  { id:'SAY-004', name:'Kompresör Odası',       col1:'—',     col2:'—',       col3:'—',        col4:'—',    col5:'—',    col6:'880',    status:'err' },
  { id:'SAY-005', name:'Soğutma & Makas',       col1:'398 V', col2:'206 A',   col3:'143 kW',   col4:'0.82', col5:'7.4%', col6:'2.220',  status:'warn' },
];
const ELEC_HEADERS = ['Sayaç','Hat / Bölge','Gerilim','Akım','Güç','Cos φ','THD-I','kWh Bugün','Durum'];

// Doğal Gaz verileri
const GAS_DAILY = [1420,1510,1680,1490,1720,1840,1780,1690,1580,1890,1760,1620,1510,1840];
const GAS_HOURLY = [80,85,82,120,180,210,240,260,250,245,230,200,210,240,260,250,245,230,200,180,160,140,120,100];
const GAS_METERS = [
  { id:'GAZ-001', name:'Ana Giriş RMS İstasyonu',col1:'4.0 Bar',  col2:'185 Sm³/h', col3:'14 °C',  col4:'9.150 kcal', col5:'—',    col6:'4.210', status:'ok' },
  { id:'GAZ-002', name:'Kütük Isıtma Fırını 1',  col1:'300 mBar', col2:'110 Sm³/h', col3:'22 °C',  col4:'9.100 kcal', col5:'—',    col6:'2.450', status:'ok' },
  { id:'GAZ-003', name:'Kütük Isıtma Fırını 2',  col1:'298 mBar', col2:'65 Sm³/h',  col3:'24 °C',  col4:'9.080 kcal', col5:'—',    col6:'1.480', status:'ok' },
  { id:'GAZ-004', name:'Isıl İşlem Fırını',      col1:'150 mBar', col2:'10 Sm³/h',  col3:'18 °C',  col4:'9.120 kcal', col5:'—',    col6:'280',   status:'warn' },
];
const GAS_HEADERS = ['Sayaç','Hat / Bölge','Basınç','Debi','Sıcaklık','Isıl Değer','—','Sm³ Bugün','Durum'];

// Su verileri
const WATER_DAILY = [410,435,480,420,495,510,460,445,410,505,480,430,415,525];
const WATER_HOURLY = [12,14,13,20,28,35,42,48,45,44,40,32,35,42,48,45,44,40,32,28,24,20,16,14];
const WATER_METERS = [
  { id:'SU-001', name:'Şebeke Ana Girişi',       col1:'5.2 Bar', col2:'21.5 m³/h', col3:'Şebeke',  col4:'—', col5:'—', col6:'525', status:'ok' },
  { id:'SU-002', name:'Soğutma Kuleleri Besleme',col1:'4.8 Bar', col2:'14.2 m³/h', col3:'Dahili',   col4:'—', col5:'—', col6:'340', status:'ok' },
  { id:'SU-003', name:'Arıtma Tesisi Girişi',    col1:'2.1 Bar', col2:'6.8 m³/h',  col3:'Atık Su',  col4:'—', col5:'—', col6:'165', status:'ok' },
  { id:'SU-004', name:'Sosyal Tesisler & Ofis',  col1:'3.5 Bar', col2:'0.5 m³/h',  col3:'Şebeke',   col4:'—', col5:'—', col6:'20',  status:'warn' },
];
const WATER_HEADERS = ['Sayaç','Hat / Bölge','Basınç','Debi','Kaynak','—','—','m³ Bugün','Durum'];

const DAILY_LABELS = ['18 Nis','19 Nis','20 Nis','21 Nis','22 Nis','23 Nis','24 Nis','25 Nis','26 Nis','27 Nis','28 Nis','29 Nis','30 Nis','01 May'];
const HOURLY_LABELS = Array.from({length:24}, (_,i) => `${String(i).padStart(2,'0')}:00`);

const TAB_CONFIG = {
  elektrik: {
    color: 'var(--accent)', label: 'Elektrik', unit: 'kWh',
    daily: ELEC_DAILY, hourly: ELEC_HOURLY, meters: ELEC_METERS, headers: ELEC_HEADERS,
    stats: [
      { label:'Günlük Aktif Tüketim', value:'38.240', unit:'kWh' },
      { label:'Anlık Talep',          value:'1.682',  unit:'kW' },
      { label:'Puant Talep (Maks)',   value:'4.820',  unit:'kW' },
      { label:'Güç Faktörü (Cos φ)', value:'0.89',   unit:'' },
      { label:'Reaktif Oran',        value:'%14.2',  unit:'' },
      { label:'Birim Fiyat',         value:'₺4.35',  unit:'/kWh' },
    ]
  },
  dogalgaz: {
    color: '#D97706', label: 'Doğal Gaz', unit: 'Sm³',
    daily: GAS_DAILY, hourly: GAS_HOURLY, meters: GAS_METERS, headers: GAS_HEADERS,
    stats: [
      { label:'Günlük Tüketim',  value:'4.210',  unit:'Sm³' },
      { label:'Anlık Debi',      value:'185',    unit:'Sm³/h' },
      { label:'Ana Basınç',      value:'4.0',    unit:'Bar' },
      { label:'Isıl Değer',      value:'9.150',  unit:'kcal/m³' },
      { label:'Gaz Maliyeti',    value:'₺36.850',unit:'' },
      { label:'Birim Fiyat',     value:'₺8.75',  unit:'/Sm³' },
    ]
  },
  su: {
    color: '#0EA5E9', label: 'Su', unit: 'm³',
    daily: WATER_DAILY, hourly: WATER_HOURLY, meters: WATER_METERS, headers: WATER_HEADERS,
    stats: [
      { label:'Günlük Tüketim',    value:'525',    unit:'m³' },
      { label:'Anlık Debi Toplamı', value:'21.5',   unit:'m³/h' },
      { label:'Şebeke Basıncı',    value:'5.2',    unit:'Bar' },
      { label:'Geri Kazanım',      value:'%18.5',  unit:'' },
      { label:'Su Maliyeti',       value:'₺11.550',unit:'' },
      { label:'Birim Fiyat',       value:'₺22.00', unit:'/m³' },
    ]
  }
};

function MiniLineChartEnergy({ vals, labels, color, W=740, H=180, PL=44, PR=14, PT=10, PB=26 }) {
  const cW=W-PL-PR, cH=H-PT-PB;
  const max=Math.max(...vals)*1.08;
  const pts=vals.map((v,i)=>({ x:PL+(i/(vals.length-1))*cW, y:PT+cH-(v/max)*cH }));
  const line=pts.map((p,i)=>`${i===0?'M':'L'}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' ');
  const area=`${line} L${pts[pts.length-1].x},${PT+cH} L${pts[0].x},${PT+cH} Z`;
  const gridYs=[0,0.33,0.67,1].map(t=>PT+cH-t*cH);
  const step=Math.ceil(vals.length/7);
  const gradId=`fill-nrg-${color.replace(/[^a-z0-9]/gi,'')}`;
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display:'block' }}>
      <defs><linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={color} stopOpacity="0.14"/><stop offset="100%" stopColor={color} stopOpacity="0"/></linearGradient></defs>
      {gridYs.map((y,i)=>(
        <g key={i}>
          <line x1={PL} y1={y} x2={W-PR} y2={y} stroke="var(--border)" strokeWidth="0.5" strokeDasharray="2 3"/>
          <text x={PL-4} y={y+4} fontSize="8.5" fill="var(--text-muted)" textAnchor="end" fontFamily="var(--font-mono)">{Math.round((1-i/3)*max)}</text>
        </g>
      ))}
      <path d={area} fill={`url(#${gradId})`}/>
      <path d={line} fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
      {vals.map((v,i)=> i%step===0 && (
        <text key={i} x={PL+(i/(vals.length-1))*cW} y={H-5} fontSize="8.5" fill="var(--text-muted)" textAnchor="middle" fontFamily="var(--font-mono)">{labels[i]}</text>
      ))}
    </svg>
  );
}

const PageEnergy = ({ tweaks }) => {
  const [sourceTab, setSourceTab] = React.useState('elektrik');
  const [timeTab, setTimeTab] = React.useState('saatlik');
  const r=tweaks.radius==='round'?14:tweaks.radius==='medium'?8:4;
  const cfg = TAB_CONFIG[sourceTab];

  return (
    <div className="page-enter" style={{ display:'flex', flexDirection:'column', gap:20 }}>
      {/* Kaynak Tabları */}
      <div style={{ display:'flex', gap:4, background:'var(--surface)', border:'1px solid var(--border)', borderRadius:r, padding:3, width:'fit-content' }}>
        {Object.entries(TAB_CONFIG).map(([key, c])=>(
          <button key={key} onClick={()=>setSourceTab(key)} style={{ padding:'7px 18px', borderRadius:r-2, border:0, fontSize:13, fontWeight:sourceTab===key?600:400, cursor:'pointer', background:sourceTab===key?'var(--bg-elevated)':'transparent', color:sourceTab===key?c.color:'var(--text-muted)', boxShadow:sourceTab===key?'var(--shadow-1)':'none', transition:'all 140ms', fontFamily:'var(--font-sans)', display:'flex', alignItems:'center', gap:6 }}>
            <div style={{ width:8, height:8, borderRadius:'50%', background:c.color, opacity:sourceTab===key?1:0.4 }}/>
            {c.label}
          </button>
        ))}
      </div>

      {/* Özet şerit */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(6,1fr)', gap:10 }}>
        {cfg.stats.map((s,i)=>(
          <div key={i} style={{ background:'var(--bg-elevated)', border:'1px solid var(--border)', borderRadius:r, padding:'12px 14px', boxShadow:'var(--shadow-1)' }}>
            <div style={{ fontFamily:'var(--font-mono)', fontSize:9, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:6 }}>{s.label}</div>
            <div style={{ fontSize:20, fontWeight:600, letterSpacing:'-0.03em', color:'var(--text)', display:'flex', alignItems:'baseline', gap:3 }}>
              {s.value}{s.unit&&<span style={{ fontSize:10, color:'var(--text-muted)', fontWeight:400 }}> {s.unit}</span>}
            </div>
          </div>
        ))}
      </div>

      {/* Trend grafiği */}
      <div style={{ background:'var(--bg-elevated)', border:'1px solid var(--border)', borderRadius:r, boxShadow:'var(--shadow-1)', overflow:'hidden' }}>
        <div style={{ padding:'13px 18px 0', borderBottom:'1px solid var(--border)' }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', paddingBottom:12 }}>
            <div>
              <div style={{ fontSize:13, fontWeight:500 }}>{cfg.label} Tüketim Trendi</div>
              <div style={{ fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-muted)', marginTop:2 }}>İzmir Ana Tesis · {cfg.unit}</div>
            </div>
            <div style={{ display:'flex', gap:2, background:'var(--surface)', border:'1px solid var(--border)', borderRadius:6, padding:2 }}>
              {['saatlik','günlük'].map(t=>(
                <button key={t} onClick={()=>setTimeTab(t)} style={{ padding:'4px 12px', borderRadius:4, border:0, fontSize:11, fontFamily:'var(--font-mono)', cursor:'pointer', background:timeTab===t?'var(--bg-elevated)':'transparent', color:timeTab===t?'var(--text)':'var(--text-muted)', boxShadow:timeTab===t?'var(--shadow-1)':'none', transition:'all 140ms' }}>
                  {t.charAt(0).toUpperCase()+t.slice(1)}
                </button>
              ))}
            </div>
          </div>
        </div>
        <div style={{ padding:'12px 0 0' }}>
          {timeTab==='saatlik'
            ? <MiniLineChartEnergy vals={cfg.hourly} labels={HOURLY_LABELS} color={cfg.color}/>
            : <MiniLineChartEnergy vals={cfg.daily} labels={DAILY_LABELS} color={cfg.color}/>
          }
        </div>
      </div>

      {/* Sayaç tablosu */}
      <div style={{ background:'var(--bg-elevated)', border:'1px solid var(--border)', borderRadius:r, boxShadow:'var(--shadow-1)', overflow:'hidden' }}>
        <div style={{ padding:'13px 18px 11px', borderBottom:'1px solid var(--border)' }}>
          <div style={{ fontSize:13, fontWeight:500 }}>{cfg.label} Sayaçları ve Analizörleri</div>
          <div style={{ fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-muted)', marginTop:2 }}>Gerçek zamanlı ölçümler</div>
        </div>
        <div style={{ overflowX:'auto' }}>
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
            <thead>
              <tr style={{ background:'var(--surface)' }}>
                {cfg.headers.filter(h=>h!=='—').map(h=>(
                  <th key={h} style={{ padding:'8px 10px', textAlign:'left', fontSize:9.5, fontFamily:'var(--font-mono)', color:'var(--text-muted)', letterSpacing:'0.04em', textTransform:'uppercase', borderBottom:'1px solid var(--border)', whiteSpace:'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {cfg.meters.map((m,i)=>{
                const scol=m.status==='ok'?'var(--signal-ok)':m.status==='warn'?'var(--signal-warn)':'var(--signal-err)';
                const sbg=m.status==='ok'?'rgba(74,123,78,0.08)':m.status==='warn'?'rgba(160,122,46,0.08)':'rgba(142,58,58,0.08)';
                const slabel=m.status==='ok'?'Çevrimiçi':m.status==='warn'?'Uyarı':'Hata';
                const cols = [m.col1,m.col2,m.col3,m.col4,m.col5,m.col6].filter((_,ci)=>cfg.headers[ci+2]!=='—');
                return (
                  <tr key={m.id} style={{ borderBottom:i<cfg.meters.length-1?'1px solid var(--border)':'none' }}
                    onMouseEnter={e=>e.currentTarget.style.background='var(--surface)'}
                    onMouseLeave={e=>e.currentTarget.style.background=''}>
                    <td style={{ padding:'9px 10px', fontFamily:'var(--font-mono)', fontSize:11, color:cfg.color, fontWeight:500 }}>{m.id}</td>
                    <td style={{ padding:'9px 10px', fontSize:12.5 }}>{m.name}</td>
                    {cols.map((c,ci)=>(
                      <td key={ci} style={{ padding:'9px 10px', fontFamily:'var(--font-mono)', fontSize:11, color:ci===cols.length-1?'var(--text)':'var(--text-secondary)', fontWeight:ci===cols.length-1?500:400 }}>{c}</td>
                    ))}
                    <td style={{ padding:'9px 10px' }}><span style={{ fontSize:9.5, fontFamily:'var(--font-mono)', padding:'2px 6px', borderRadius:3, background:sbg, color:scol, border:`1px solid ${scol}22`, textTransform:'uppercase' }}>{slabel}</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { PageEnergy });
