// ── Ayarlar Sayfası — Akın Haddecilik · Aliağa ────────────────────────────

const SETTINGS_USERS = [
  { name:'Ahmet Yılmaz',  email:'a.yilmaz@akinhaddesi.com',  role:'Tesis Müdürü',     status:'Aktif', last:'01 May 2026 · 09:14' },
  { name:'Fatma Kaya',    email:'f.kaya@akinhaddesi.com',    role:'Enerji Mühendisi',   status:'Aktif', last:'01 May 2026 · 08:50' },
  { name:'Murat Demir',   email:'m.demir@akinhaddesi.com',   role:'Vardiya Amiri',  status:'Aktif', last:'30 Apr 2026 · 22:10' },
  { name:'Elif Şahin',    email:'e.sahin@akinhaddesi.com',   role:'Üretim Planlamacı',status:'Aktif', last:'01 May 2026 · 07:30' },
  { name:'Can Özkan',     email:'c.ozkan@akinhaddesi.com',   role:'Bakım Teknisyeni',  status:'Pasif',last:'25 Apr 2026 · 14:05' },
];

const ALARM_THRESHOLDS = [
  { param:'Enerji aşırı tüketim eşiği',         value:'15%',     unit:'baz değerin üzerinde',  editable:true },
  { param:'Minimum güç faktörü',               value:'0.85',    unit:'',                editable:true },
  { param:'Puant talep uyarı seviyesi',            value:'650 kW',  unit:'',                editable:true },
  { param:'Birim enerji maliyeti uyarısı (kWh/adet)', value:'0.45',    unit:'kWh/adet',         editable:true },
  { param:'Sayaç çevrimdışı zaman aşımı',              value:'30 dk',  unit:'',                editable:true },
  { param:'Makine boşta bekleme uyarısı',         value:'20 dk',  unit:'yükle bekleme',  editable:true },
];

const INTEGRATIONS = [
  { name:'Siemens S7 PLC Ağ Geçidi',  type:'OPC-UA',  status:'Bağlı',    host:'192.168.1.10', last:'11:09' },
  { name:'Enerji Sayaç Veriyolu (MTRs)', type:'Modbus',  status:'Kısmi',      host:'192.168.1.20', last:'08:14' },
  { name:'ERP Sistemi (SAP)',        type:'REST API',status:'Bağlı',    host:'erp.akin.local', last:'10:55' },
  { name:'SMTP E-posta Uyarıları',       type:'SMTP',    status:'Bağlı',    host:'smtp.akinhaddesi.com', last:'11:00' },
  { name:'SMS Ağ Geçidi',             type:'SMS',     status:'Bağlı',    host:'sms-gw.nexor.io', last:'09:41' },
];

const INT_STATUS = {
  'Bağlı':{ color:'var(--signal-ok)',   bg:'rgba(74,123,78,0.08)' },
  'Kısmi':  { color:'var(--signal-warn)', bg:'rgba(160,122,46,0.08)' },
  'Hata':    { color:'var(--signal-err)',  bg:'rgba(142,58,58,0.08)' },
};

function SettingRow({ label, sub, children }) {
  return (
    <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:24, padding:'14px 0', borderBottom:'1px solid var(--border)', alignItems:'center' }}>
      <div>
        <div style={{ fontSize:13, fontWeight:500 }}>{label}</div>
        {sub && <div style={{ fontFamily:'var(--font-mono)', fontSize:10.5, color:'var(--text-muted)', marginTop:2 }}>{sub}</div>}
      </div>
      <div style={{ display:'flex', justifyContent:'flex-end' }}>{children}</div>
    </div>
  );
}

function Toggle({ on }) {
  const [val, setVal] = React.useState(on);
  return (
    <button onClick={()=>setVal(v=>!v)} style={{ position:'relative', width:36, height:20, borderRadius:999, background:val?'var(--accent)':'var(--border-strong)', border:0, cursor:'pointer', transition:'background 160ms', padding:0, flexShrink:0 }}>
      <span style={{ position:'absolute', top:2, left:val?16:2, width:16, height:16, borderRadius:'50%', background:'white', transition:'left 160ms', boxShadow:'0 1px 2px rgba(0,0,0,0.2)' }}/>
    </button>
  );
}

function EditableValue({ value, unit }) {
  const [val, setVal] = React.useState(value);
  const [editing, setEditing] = React.useState(false);
  if (editing) return (
    <div style={{ display:'flex', gap:6, alignItems:'center' }}>
      <input value={val} onChange={e=>setVal(e.target.value)} autoFocus onBlur={()=>setEditing(false)} onKeyDown={e=>{ if(e.key==='Enter') setEditing(false); }}
        style={{ width:80, padding:'4px 8px', fontFamily:'var(--font-mono)', fontSize:12, border:'1px solid var(--accent)', borderRadius:4, outline:'none', background:'var(--bg-elevated)', color:'var(--text)' }}/>
      {unit && <span style={{ fontFamily:'var(--font-mono)', fontSize:11, color:'var(--text-muted)' }}>{unit}</span>}
    </div>
  );
  return (
    <button onClick={()=>setEditing(true)} style={{ fontFamily:'var(--font-mono)', fontSize:12, fontWeight:500, color:'var(--accent)', background:'var(--accent-weak)', border:'1px solid var(--accent)22', borderRadius:4, padding:'4px 10px', cursor:'pointer', display:'flex', alignItems:'center', gap:5 }}>
      {val}{unit?` ${unit}`:''} <DashIcon name="external" size={11} color="var(--accent)"/>
    </button>
  );
}

const SettingsPage = ({ tweaks }) => {
  const [activeTab, setActiveTab] = React.useState('plant');
  const r = tweaks.radius === 'round' ? 14 : tweaks.radius === 'medium' ? 8 : 4;

  const tabs = [
    { id:'plant',       label:'Tesis & Hesap' },
    { id:'thresholds',  label:'Alarm Eşikleri' },
    { id:'users',       label:'Kullanıcılar & Roller' },
    { id:'integrations',label:'Entegrasyonlar' },
    { id:'notifications',label:'Bildirimler' },
  ];

  return (
    <div className="page-enter" style={{ display:'flex', flexDirection:'column', gap:20 }}>
      {/* Tab bar */}
      <div style={{ display:'flex', gap:2, background:'var(--surface)', border:'1px solid var(--border)', borderRadius:r, padding:3, width:'fit-content' }}>
        {tabs.map(t=>(
          <button key={t.id} onClick={()=>setActiveTab(t.id)} style={{ padding:'6px 14px', borderRadius:r-4, border:0, fontSize:12.5, fontFamily:'var(--font-sans)', cursor:'pointer', background: activeTab===t.id?'var(--bg-elevated)':'transparent', color: activeTab===t.id?'var(--text)':'var(--text-secondary)', boxShadow: activeTab===t.id?'var(--shadow-1)':'none', transition:'all 140ms', fontWeight: activeTab===t.id?500:400, whiteSpace:'nowrap' }}>
            {t.label}
          </button>
        ))}
      </div>

      {/* Plant & Account */}
      {activeTab === 'plant' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
          <div style={{ background:'var(--bg-elevated)', border:'1px solid var(--border)', borderRadius:r, boxShadow:'var(--shadow-1)', padding:'16px 20px' }}>
            <div style={{ fontSize:13, fontWeight:500, marginBottom:16 }}>Tesis Bilgileri</div>
            {[
              { label:'Müşteri Adı',      value:'Akın Haddesi' },
              { label:'Tesis',           value:'İzmir Üretim Tesisi' },
              { label:'Sektör',          value:'Alüminyum Radyatör ve Havlupan Üretimi' },
              { label:'Ülke',            value:'Türkiye' },
              { label:'Saat Dilimi',     value:'Europe/Istanbul (UTC+3)' },
              { label:'Para Birimi',     value:'Türk Lirası (₺)' },
              { label:'NEXOR Lisansı',   value:'Kurumsal · Bitiş: Ara 2026' },
              { label:'Hesap Yöneticisi',value:'Kemal Arslan · kemal@nexor.io' },
            ].map((row,i,arr)=>(
              <div key={i} style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, padding:'10px 0', borderBottom: i<arr.length-1?'1px solid var(--border)':'none' }}>
                <span style={{ fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.04em', display:'flex', alignItems:'center' }}>{row.label}</span>
                <span style={{ fontSize:12.5, fontWeight:500, color:'var(--text)' }}>{row.value}</span>
              </div>
            ))}
          </div>

          <div style={{ background:'var(--bg-elevated)', border:'1px solid var(--border)', borderRadius:r, boxShadow:'var(--shadow-1)', padding:'16px 20px' }}>
            <div style={{ fontSize:13, fontWeight:500, marginBottom:16 }}>Sistem Yapılandırması</div>
            {[
              { label:'Veri yenileme aralığı', sub:'Canlı verilerin yoklanma sıklığı', ctrl:<EditableValue value="30" unit="saniye"/> },
              { label:'Enerji birimi',         sub:'Enerji okumaları için birim',     ctrl:<span style={{ fontFamily:'var(--font-mono)', fontSize:12, color:'var(--text)' }}>kWh</span> },
              { label:'Talep birimi',          sub:'Güç talebi için birim',         ctrl:<span style={{ fontFamily:'var(--font-mono)', fontSize:12, color:'var(--text)' }}>kW</span> },
              { label:'Tarife yapısı',         sub:'Aktif elektrik tarife profili',     ctrl:<span style={{ fontFamily:'var(--font-mono)', fontSize:12, color:'var(--text)' }}>3 Zamanlı (Gece/Gündüz/Puant)</span> },
              { label:'Otomatik raporlama',    sub:'Günlük raporları otomatik oluştur',  ctrl:<Toggle on={true}/> },
              { label:'YZ Öngörüleri',         sub:'Yapay zeka operasyonel önerilerini aç', ctrl:<Toggle on={true}/> },
              { label:'Koyu tema (sistem)',    sub:'İşletim sistemi koyu/açık tercihini izle',       ctrl:<Toggle on={false}/> },
            ].map((row,i,arr)=>(
              <div key={i} style={{ display:'grid', gridTemplateColumns:'1fr auto', gap:12, padding:'10px 0', borderBottom: i<arr.length-1?'1px solid var(--border)':'none', alignItems:'center' }}>
                <div>
                  <div style={{ fontSize:13, fontWeight:500 }}>{row.label}</div>
                  {row.sub && <div style={{ fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-muted)', marginTop:1 }}>{row.sub}</div>}
                </div>
                {row.ctrl}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Alarm Thresholds */}
      {activeTab === 'thresholds' && (
        <div style={{ background:'var(--bg-elevated)', border:'1px solid var(--border)', borderRadius:r, boxShadow:'var(--shadow-1)', padding:'16px 20px' }}>
          <div style={{ fontSize:13, fontWeight:500, marginBottom:4 }}>Alarm Eşikleri</div>
          <div style={{ fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-muted)', marginBottom:16 }}>Düzenlemek için bir değere tıklayın. Değişiklikler anında uygulanır.</div>
          {ALARM_THRESHOLDS.map((t,i)=>(
            <div key={i} style={{ display:'grid', gridTemplateColumns:'1fr auto', gap:16, padding:'12px 0', borderBottom: i<ALARM_THRESHOLDS.length-1?'1px solid var(--border)':'none', alignItems:'center' }}>
              <div>
                <div style={{ fontSize:13, fontWeight:500 }}>{t.param}</div>
                {t.unit && <div style={{ fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-muted)', marginTop:1 }}>Birim: {t.unit}</div>}
              </div>
              <EditableValue value={t.value} unit=""/>
            </div>
          ))}
        </div>
      )}

      {/* Users */}
      {activeTab === 'users' && (
        <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)', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <div style={{ fontSize:13, fontWeight:500 }}>Kullanıcılar & Roller</div>
            <button style={{ display:'flex', alignItems:'center', gap:5, padding:'5px 12px', background:'var(--accent)', color:'var(--accent-fg)', border:0, borderRadius:r-4, cursor:'pointer', fontSize:12, fontFamily:'var(--font-sans)', fontWeight:500 }}>
              <DashIcon name="plus" size={13} color="white"/>Kullanıcı Davet Et
            </button>
          </div>
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12.5 }}>
            <thead><tr style={{ background:'var(--surface)' }}>
              {['İsim','E-posta','Rol','Durum','Son Aktif',''].map(h=>(
                <th key={h} style={{ padding:'8px 14px', textAlign:'left', fontSize:9.5, fontFamily:'var(--font-mono)', color:'var(--text-muted)', letterSpacing:'0.04em', textTransform:'uppercase', borderBottom:'1px solid var(--border)' }}>{h}</th>
              ))}
            </tr></thead>
            <tbody>
              {SETTINGS_USERS.map((u,i)=>(
                <tr key={i} style={{ borderBottom: i<SETTINGS_USERS.length-1?'1px solid var(--border)':'none' }}
                  onMouseEnter={e=>e.currentTarget.style.background='var(--surface)'}
                  onMouseLeave={e=>e.currentTarget.style.background=''}>
                  <td style={{ padding:'10px 14px' }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <div style={{ width:26, height:26, borderRadius:'50%', background:'var(--accent)', color:'var(--accent-fg)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:10, fontWeight:600, flexShrink:0 }}>{u.name.split(' ').map(p=>p[0]).join('').slice(0,2)}</div>
                      <span style={{ fontWeight:500 }}>{u.name}</span>
                    </div>
                  </td>
                  <td style={{ padding:'10px 14px', fontFamily:'var(--font-mono)', fontSize:11, color:'var(--text-muted)' }}>{u.email}</td>
                  <td style={{ padding:'10px 14px' }}><span style={{ fontSize:10, fontFamily:'var(--font-mono)', padding:'2px 7px', borderRadius:3, background:'var(--accent-weak)', color:'var(--accent)', border:'1px solid var(--accent)22', whiteSpace:'nowrap' }}>{u.role}</span></td>
                  <td style={{ padding:'10px 14px' }}><span style={{ fontSize:10, fontFamily:'var(--font-mono)', padding:'2px 6px', borderRadius:3, background: u.status==='Aktif'?'rgba(74,123,78,0.08)':'var(--surface)', color: u.status==='Aktif'?'var(--signal-ok)':'var(--text-muted)', border:`1px solid ${u.status==='Aktif'?'rgba(74,123,78,0.2)':'var(--border)'}` }}>{u.status}</span></td>
                  <td style={{ padding:'10px 14px', fontFamily:'var(--font-mono)', fontSize:11, color:'var(--text-muted)' }}>{u.last}</td>
                  <td style={{ padding:'10px 14px' }}><button style={{ fontSize:11, padding:'4px 9px', border:'1px solid var(--border)', borderRadius:3, background:'none', color:'var(--text-secondary)', cursor:'pointer', fontFamily:'var(--font-sans)' }}>Düzenle</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Integrations */}
      {activeTab === 'integrations' && (
        <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 }}>Sistem Entegrasyonları</div>
            <div style={{ fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-muted)', marginTop:2 }}>Bağlı veri kaynakları ve çıkış kanalları</div>
          </div>
          <div style={{ padding:'8px 0' }}>
            {INTEGRATIONS.map((int,i)=>{
              const s = INT_STATUS[int.status];
              return (
                <div key={i} style={{ display:'grid', gridTemplateColumns:'1fr auto auto', gap:16, padding:'12px 18px', borderBottom: i<INTEGRATIONS.length-1?'1px solid var(--border)':'none', alignItems:'center' }}>
                  <div>
                    <div style={{ fontSize:13, fontWeight:500, marginBottom:2 }}>{int.name}</div>
                    <div style={{ display:'flex', gap:10, fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-muted)' }}>
                      <span style={{ padding:'1px 6px', borderRadius:2, background:'var(--surface)', border:'1px solid var(--border)' }}>{int.type}</span>
                      <span>{int.host}</span>
                      <span>Son senkronizasyon: {int.last}</span>
                    </div>
                  </div>
                  <span style={{ fontSize:10, fontFamily:'var(--font-mono)', padding:'3px 8px', borderRadius:3, background:s.bg, color:s.color, border:`1px solid ${s.color}22`, whiteSpace:'nowrap' }}>{int.status}</span>
                  <button style={{ padding:'5px 10px', border:'1px solid var(--border)', borderRadius:3, background:'none', fontSize:11, color:'var(--text-secondary)', cursor:'pointer', fontFamily:'var(--font-sans)', whiteSpace:'nowrap' }}>Yapılandır</button>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Notifications */}
      {activeTab === 'notifications' && (
        <div style={{ background:'var(--bg-elevated)', border:'1px solid var(--border)', borderRadius:r, boxShadow:'var(--shadow-1)', padding:'16px 20px' }}>
          <div style={{ fontSize:13, fontWeight:500, marginBottom:16 }}>Bildirim Ayarları</div>
          {[
            { label:'Kritik alarmda e-posta',      sub:'Hata seviyesinde alarm oluştuğunda e-posta gönder',          on:true },
            { label:'Kritik alarmda SMS',         sub:'Kritik olaylarda tesis müdürüne SMS gönder',          on:true },
            { label:'Günlük enerji özeti e-postası',    sub:'Günlük rapor 07:00\'da teslim edilir',                       on:true },
            { label:'Haftalık performans derlemesi',     sub:'Pazartesi günleri haftalık OEE & enerji maliyet özeti',           on:true },
            { label:'YZ öngörü bildirimleri',      sub:'Yeni yüksek öncelikli YZ önerisi oluştuğunda bildir', on:true },
            { label:'Sayaç çevrimdışı uyarısı',           sub:'Bir sayaç bağlantısı koptuğunda uyar',                 on:true },
            { label:'İş emri maliyet uyarısı',         sub:'İE birim enerji maliyeti eşiği aştığında uyar',      on:true },
            { label:'Bakım hatırlatıcısı',          sub:'Planlı bakımdan 7 gün önce hatırlat',           on:false },
          ].map((n,i,arr)=>(
            <div key={i} style={{ display:'grid', gridTemplateColumns:'1fr auto', gap:16, padding:'12px 0', borderBottom: i<arr.length-1?'1px solid var(--border)':'none', alignItems:'center' }}>
              <div>
                <div style={{ fontSize:13, fontWeight:500 }}>{n.label}</div>
                <div style={{ fontFamily:'var(--font-mono)', fontSize:10, color:'var(--text-muted)', marginTop:1 }}>{n.sub}</div>
              </div>
              <Toggle on={n.on}/>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { PageSettings: SettingsPage });
