// settings-v2.jsx — Ustawienia / Settings screen
// 6 sections: Ogólne · Urządzenia · Użytkownicy · Taryfy · Cele pracy · System
// De-emoji: LI() icons throughout, no emoji glyphs

// ── Destructive button hook (2-step arm/fire) ─────────────────────────────
function useArm() {
  const [armed, setArmed] = React.useState(false);
  const arm = () => { setArmed(true); setTimeout(() => setArmed(false), 3000); };
  const fire = () => { setArmed(false); };
  return { armed, arm, fire };
}

function DestructiveBtn({ label, confirmLabel, onConfirm, style }) {
  const { armed, arm, fire } = useArm();
  const handleClick = () => {
    if (!armed) { arm(); return; }
    fire(); onConfirm?.();
  };
  return (
    <button onClick={handleClick} style={{
      background: armed ? `${T.red}33` : `${T.red}14`,
      color: T.red, border: `1.5px solid ${T.red}44`,
      padding: '9px 16px', borderRadius: 10,
      fontFamily: T.fontUI, fontWeight: 600, fontSize: 12,
      cursor: 'pointer', transition: 'all 200ms', letterSpacing: 0.3,
      ...style,
    }}>
      {armed ? <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <LI name="alert-triangle" size={13} color={T.red}/>{confirmLabel}
      </span> : label}
    </button>
  );
}

// ── Settings row primitives ────────────────────────────────────────────────
function SettingsSection({ title, anchor, children }) {
  return (
    <div id={anchor} style={{ marginBottom: 32 }}>
      <div style={{
        fontFamily: T.fontBrand, fontWeight: 700, fontSize: 12,
        textTransform: 'uppercase', letterSpacing: 1.2, color: T.textMuted,
        marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8,
      }}>{title}</div>
      {children}
    </div>
  );
}

function SettingsCard({ children, style }) {
  return (
    <Surface padding={0} style={{ marginBottom: 10, ...style }}>
      {children}
    </Surface>
  );
}

function SettingsRow({ label, desc, children, last }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '14px 18px', gap: 20,
      borderBottom: last ? 'none' : `1px solid ${T.border}`,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, color: T.textPrimary, fontWeight: 500 }}>{label}</div>
        {desc && <div style={{ fontSize: 11, color: T.textMuted, marginTop: 2, lineHeight: 1.4 }}>{desc}</div>}
      </div>
      <div style={{ flexShrink: 0 }}>{children}</div>
    </div>
  );
}

function SettingsToggle({ on, onChange }) {
  return (
    <button onClick={() => onChange?.(!on)} style={{
      width: 44, height: 24, borderRadius: 99, border: 'none', cursor: 'pointer',
      background: on ? T.green : T.border,
      position: 'relative', transition: 'background 200ms', padding: 0,
    }}>
      <span style={{
        position: 'absolute', top: 3, left: on ? 22 : 3,
        width: 18, height: 18, borderRadius: '50%', background: T.bg,
        transition: 'left 200ms', display: 'block',
      }}/>
    </button>
  );
}

function SettingsSelect({ value, options, onChange, style }) {
  return (
    <select value={value} onChange={e => onChange?.(e.target.value)} style={{
      background: T.raised, border: `1px solid ${T.border}`, color: T.textPrimary,
      padding: '7px 12px', borderRadius: 8, fontFamily: T.fontUI, fontSize: 12,
      cursor: 'pointer', appearance: 'none', paddingRight: 28, ...style,
    }}>
      {options.map(o => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}
    </select>
  );
}

function ReadOnlyField({ value, style }) {
  return (
    <div style={{
      background: T.raised, border: `1px solid ${T.border}`,
      padding: '7px 12px', borderRadius: 8, fontSize: 12,
      fontFamily: T.fontMono, color: T.textSecondary, minWidth: 160, ...style,
    }}>{value}</div>
  );
}

// ── Modal wrapper ─────────────────────────────────────────────────────────
function Modal({ title, onClose, children, width = 520 }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.72)',
      backdropFilter: 'blur(8px)', zIndex: 100,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
    }} onClick={onClose}>
      <div style={{
        background: T.surface, border: `1px solid ${T.border}`, borderRadius: 20,
        padding: 28, width, maxWidth: '100%', maxHeight: '90vh', overflow: 'auto',
      }} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 22 }}>
          <div style={{ fontFamily: T.fontBrand, fontSize: 18, fontWeight: 700 }}>{title}</div>
          <button onClick={onClose} style={{
            background: T.raised, border: `1px solid ${T.border}`, color: T.textMuted,
            width: 30, height: 30, borderRadius: 8, cursor: 'pointer', fontSize: 16,
          }}>×</button>
        </div>
        {children}
      </div>
    </div>
  );
}

// ── Main component ─────────────────────────────────────────────────────────
function V2Settings({ safeMode, setSafeMode }) {
  const { t, locale, setLocale } = useLocale();
  const [currency, setCurrency] = React.useState('PLN');
  const [dso, setDso] = React.useState('stoen');
  const [tariff, setTariff] = React.useState('pstryk');
  const [telemetry, setTelemetry] = React.useState('anonymous');
  const [batteryLive, setBatteryLive] = React.useState(false);
  const [deviceModal, setDeviceModal] = React.useState(false);
  const [userModal, setUserModal] = React.useState(false);
  const [activeDeviceType, setActiveDeviceType] = React.useState(null);
  const [users, setUsers] = React.useState([
    { id: 1, name: 'diego', role: 'admin', last: '2 min temu' },
    { id: 2, name: 'anna', role: 'viewer', last: '3 godz. temu' },
  ]);

  const DEVICES = [
    { id: 1, type: 'inverter', name: 'Deye SUN-12K-SG04LP3-EU', ip: '192.168.1.52', status: 'online' },
    { id: 2, type: 'charger',  name: 'EO Charging EM301',        ip: '192.168.1.61', status: 'online' },
    { id: 3, type: 'meter',    name: 'Shelly Pro 3EM',           ip: '192.168.1.55', status: 'online' },
    { id: 4, type: 'relay',    name: 'Shelly 1PM (SG-Ready)',    ip: '192.168.1.56', status: 'online' },
  ];

  const DEVICE_ICON = { inverter: 'sun', charger: 'zap', meter: 'bar-chart-2', relay: 'plug' };

  const DSO_OPTIONS = [
    { value: 'stoen',  label: 'Stoen Operator (Warszawa) · 16.39 gr/kWh' },
    { value: 'energa', label: 'Energa-Operator (Gdańsk) · 14.82 gr/kWh' },
    { value: 'tauron', label: 'Tauron Dystrybucja (Kraków) · 13.44 gr/kWh' },
    { value: 'enea',   label: 'Enea Operator (Poznań) · 12.90 gr/kWh' },
    { value: 'pge',    label: 'PGE Dystrybucja (Lublin) · 15.20 gr/kWh' },
  ];

  const revokeUser = (id) => setUsers(u => u.filter(x => x.id !== id));

  return (
    <div style={{ padding: '28px 36px 48px', maxWidth: 860 }}>

      {/* ── 1. Ogólne ── */}
      <SettingsSection title={t('settings.general')} anchor="general">
        <SettingsCard>
          <SettingsRow label={t('settings.siteTitle')} desc={t('settings.siteTitleDesc')}>
            <ReadOnlyField value="Gridome"/>
          </SettingsRow>
          <SettingsRow label={t('settings.homeAddress')} desc={t('settings.homeAddressDesc')}>
            <ReadOnlyField value="Puławska 145, 02-715 Warszawa" style={{ minWidth: 260 }}/>
          </SettingsRow>
          <SettingsRow label={t('settings.language')}>
            <div style={{ display: 'flex', gap: 6 }}>
              {['pl','en'].map(l => (
                <button key={l} onClick={() => setLocale(l)} style={{
                  background: locale === l ? T.green : 'transparent',
                  color: locale === l ? T.bg : T.textSecondary,
                  border: `1.5px solid ${locale === l ? T.green : T.border}`,
                  padding: '6px 14px', borderRadius: 8, cursor: 'pointer',
                  fontFamily: T.fontUI, fontWeight: 700, fontSize: 12,
                  textTransform: 'uppercase', letterSpacing: 0.5, transition: 'all 140ms',
                }}>{l}</button>
              ))}
            </div>
          </SettingsRow>
          <SettingsRow label={t('settings.currency')} desc={t('settings.currencyDesc')} last>
            <SettingsSelect value={currency} onChange={setCurrency}
              options={[{value:'PLN',label:'zł PLN'},{value:'EUR',label:'€ EUR'}]}/>
          </SettingsRow>
        </SettingsCard>
      </SettingsSection>

      {/* ── 2. Urządzenia ── */}
      <SettingsSection title={t('settings.devices')} anchor="devices">
        <SettingsCard>
          {DEVICES.map((d, i) => (
            <div key={d.id} style={{
              display: 'flex', alignItems: 'center', gap: 14, padding: '14px 18px',
              borderBottom: i < DEVICES.length - 1 ? `1px solid ${T.border}` : 'none',
            }}>
              <IconBox name={DEVICE_ICON[d.type] || 'cpu'} size={16} color={T.green} boxSize={32} radius={8}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: T.textPrimary, fontWeight: 500 }}>{d.name}</div>
                <div style={{ fontSize: 11, color: T.textMuted, fontFamily: T.fontMono, marginTop: 2 }}>{d.ip}</div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: T.green }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: T.green, display: 'inline-block' }}/>
                {d.status === 'online' ? t('settings.online') : t('settings.offline')}
              </div>
            </div>
          ))}
          <div style={{ padding: '12px 18px', borderTop: `1px solid ${T.border}` }}>
            <PrimaryBtn onClick={() => setDeviceModal(true)} style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <LI name="plus" size={14} color={T.bg}/> {t('settings.addDevice')}
            </PrimaryBtn>
          </div>
        </SettingsCard>
      </SettingsSection>

      {/* ── 3. Użytkownicy ── */}
      <SettingsSection title={t('settings.users')} anchor="users">
        <SettingsCard>
          {users.map((u, i) => (
            <div key={u.id} style={{
              display: 'flex', alignItems: 'center', gap: 14, padding: '14px 18px',
              borderBottom: i < users.length - 1 ? `1px solid ${T.border}` : 'none',
            }}>
              <IconBox name="user" size={16} color={u.role === 'admin' ? T.blue : T.textMuted} boxSize={32} radius={8}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: T.textPrimary, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8 }}>
                  {u.name}
                  <span style={{
                    fontSize: 9, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase',
                    color: u.role === 'admin' ? T.blue : T.textMuted,
                    background: u.role === 'admin' ? `${T.blue}22` : T.raised,
                    padding: '2px 6px', borderRadius: 4, border: `1px solid ${u.role === 'admin' ? T.blue + '44' : T.border}`,
                  }}>{u.role}</span>
                </div>
                <div style={{ fontSize: 11, color: T.textMuted, marginTop: 2 }}>{t('settings.lastSeen')}: {u.last}</div>
              </div>
              {u.role !== 'admin' && (
                <DestructiveBtn label={t('settings.revoke')} confirmLabel={t('settings.confirmRevoke')} onConfirm={() => revokeUser(u.id)}/>
              )}
            </div>
          ))}
          <div style={{ padding: '12px 18px', borderTop: `1px solid ${T.border}` }}>
            <PrimaryBtn onClick={() => setUserModal(true)} style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <LI name="plus" size={14} color={T.bg}/> {t('settings.addViewer')}
            </PrimaryBtn>
          </div>
        </SettingsCard>
      </SettingsSection>

      {/* ── 4. Taryfy ── */}
      <SettingsSection title={t('settings.tariffs')} anchor="tariffs">
        <SettingsCard>
          <SettingsRow label={t('settings.tariffProvider')}>
            <SettingsSelect value={tariff} onChange={setTariff}
              options={[{value:'pstryk',label:'Pstryk dynamiczna'},{value:'pge',label:'PGE Day-ahead Dynamic'}]}/>
          </SettingsRow>
          <SettingsRow label={t('settings.dso')} desc={t('settings.dsoDesc')}>
            <SettingsSelect value={dso} onChange={setDso} options={DSO_OPTIONS} style={{ maxWidth: 300 }}/>
          </SettingsRow>
          <SettingsRow label={t('settings.formula')} desc={t('settings.formulaDesc')} last>
            <ReadOnlyField value="(TGE_spot + DSO_variable + taxes) × 1.23"/>
          </SettingsRow>
        </SettingsCard>
      </SettingsSection>

      {/* ── 5. Cele pracy ── */}
      <SettingsSection title={t('settings.operation')} anchor="operation">
        {/* Safe mode — big danger card */}
        <div style={{
          background: safeMode ? `${T.red}18` : T.surface,
          border: `1px solid ${safeMode ? T.red + '44' : T.border}`,
          borderRadius: 14, padding: 20, marginBottom: 10,
          transition: 'all 300ms',
        }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
            <IconBox name="shield-alert" size={20} color={safeMode ? T.red : T.textMuted} bg={safeMode ? `${T.red}22` : T.raised} boxSize={40}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: safeMode ? T.red : T.textPrimary, marginBottom: 4 }}>
                {t('settings.safeMode')}
              </div>
              <div style={{ fontSize: 12, color: T.textMuted, lineHeight: 1.5, maxWidth: 480 }}>
                {t('settings.safeModeDesc')}
              </div>
            </div>
            <SettingsToggle on={safeMode} onChange={setSafeMode}/>
          </div>
        </div>

        <SettingsCard>
          <SettingsRow label={t('settings.batteryLive')} desc={t('settings.batteryLiveDesc')}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{
                fontSize: 10, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase',
                color: batteryLive ? T.green : T.amber,
                background: batteryLive ? `${T.green}18` : `${T.amber}18`,
                padding: '3px 8px', borderRadius: 4,
                border: `1px solid ${batteryLive ? T.green + '44' : T.amber + '44'}`,
              }}>{batteryLive ? t('settings.active') : t('settings.locked')}</span>
              <SettingsToggle on={batteryLive} onChange={setBatteryLive}/>
            </div>
          </SettingsRow>
          <SettingsRow label={t('settings.telemetry')} last>
            <SettingsSelect value={telemetry} onChange={setTelemetry}
              options={[{value:'off',label:t('settings.telemetryOff')},{value:'anonymous',label:t('settings.telemetryAnon')},{value:'full',label:t('settings.telemetryFull')}]}/>
          </SettingsRow>
        </SettingsCard>
      </SettingsSection>

      {/* ── 6. System ── */}
      <SettingsSection title={t('settings.system')} anchor="system">
        <SettingsCard>
          <SettingsRow label={t('settings.version')}>
            <ReadOnlyField value="Gridome v0.9.12 · pilot2"/>
          </SettingsRow>
          <SettingsRow label={t('settings.backup')} desc={t('settings.backupDesc')}>
            <div style={{ display: 'flex', gap: 8 }}>
              <GhostBtn style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11 }}>
                <LI name="download" size={13} color={T.green}/>{t('settings.backupBtn')}
              </GhostBtn>
              <GhostBtn style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11 }}>
                <LI name="upload" size={13} color={T.green}/>{t('settings.restoreBtn')}
              </GhostBtn>
            </div>
          </SettingsRow>
          <SettingsRow label={t('settings.logs')} last>
            <button style={{
              background: 'transparent', border: `1px solid ${T.border}`, color: T.textSecondary,
              padding: '7px 14px', borderRadius: 8, cursor: 'pointer',
              fontFamily: T.fontUI, fontSize: 11, display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <LI name="file-text" size={13} color={T.textMuted}/>{t('settings.viewLogs')}
            </button>
          </SettingsRow>
        </SettingsCard>
        {/* Version humor footer */}
        <div style={{ marginTop: 16, fontSize: 11, color: T.textMuted, lineHeight: 1.6, fontFamily: T.fontMono }}>
          {t('settings.versionFooter')}
        </div>
      </SettingsSection>

      {/* Add device modal */}
      {deviceModal && (
        <AddDeviceModal
          activeType={activeDeviceType}
          setActiveType={setActiveDeviceType}
          onClose={() => { setDeviceModal(false); setActiveDeviceType(null); }}
          t={t}
        />
      )}

      {/* Add viewer modal */}
      {userModal && (
        <AddViewerModal onClose={() => setUserModal(false)} t={t}/>
      )}
    </div>
  );
}

// ── Add Device Modal ───────────────────────────────────────────────────────
const DEVICE_TYPES = [
  { key: 'shelly',   icon: 'zap',         labelKey: 'settings.deviceShelly' },
  { key: 'ocpp',     icon: 'car',         labelKey: 'settings.deviceOCPP' },
  { key: 'inverter', icon: 'sun',         labelKey: 'settings.deviceInverter' },
  { key: 'meter',    icon: 'bar-chart-2', labelKey: 'settings.deviceMeter' },
  { key: 'homewiz',  icon: 'wifi',        labelKey: 'settings.deviceHomewiz' },
  { key: 'tasmota',  icon: 'cpu',         labelKey: 'settings.deviceTasmota' },
];

function AddDeviceModal({ activeType, setActiveType, onClose, t }) {
  return (
    <Modal title={t('settings.addDevice')} onClose={onClose}>
      {!activeType ? (
        <>
          <div style={{ fontSize: 12, color: T.textMuted, marginBottom: 16 }}>{t('settings.pickDeviceType')}</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
            {DEVICE_TYPES.map(dt => (
              <button key={dt.key} onClick={() => setActiveType(dt.key)} style={{
                background: T.raised, border: `1.5px solid ${T.border}`, borderRadius: 12,
                padding: '16px 12px', cursor: 'pointer', display: 'flex', flexDirection: 'column',
                alignItems: 'center', gap: 10, transition: 'all 140ms',
              }}
              onMouseEnter={e => e.currentTarget.style.borderColor = T.green}
              onMouseLeave={e => e.currentTarget.style.borderColor = T.border}>
                <IconBox name={dt.icon} size={20} color={T.green} boxSize={40}/>
                <span style={{ fontSize: 12, color: T.textPrimary, fontWeight: 600, textAlign: 'center' }}>
                  {t(dt.labelKey)}
                </span>
              </button>
            ))}
          </div>
        </>
      ) : (
        <ShellyForm t={t} onBack={() => setActiveType(null)} onClose={onClose}/>
      )}
    </Modal>
  );
}

function ShellyForm({ t, onBack, onClose }) {
  const [ip, setIp] = React.useState('192.168.1.');
  const [name, setName] = React.useState('');
  return (
    <>
      <button onClick={onBack} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: T.textMuted, fontSize: 12, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 6, fontFamily: T.fontUI }}>
        <LI name="chevron-right" size={12} color={T.textMuted} style={{ transform: 'rotate(180deg)' }}/>{t('settings.back')}
      </button>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <FormField label={t('settings.deviceName')}>
          <input value={name} onChange={e => setName(e.target.value)} placeholder="Shelly Pro 3EM"
            style={{ width: '100%', background: T.raised, border: `1px solid ${T.border}`, borderRadius: 8, padding: '9px 12px', color: T.textPrimary, fontFamily: T.fontMono, fontSize: 13 }}/>
        </FormField>
        <FormField label={t('settings.ipAddress')}>
          <input value={ip} onChange={e => setIp(e.target.value)}
            style={{ width: '100%', background: T.raised, border: `1px solid ${T.border}`, borderRadius: 8, padding: '9px 12px', color: T.textPrimary, fontFamily: T.fontMono, fontSize: 13 }}/>
        </FormField>
        <FormField label={t('settings.channel')}>
          <SettingsSelect value="0" options={[{value:'0',label:'Channel 0 (main)'},{value:'1',label:'Channel 1'},{value:'2',label:'Channel 2'}]}/>
        </FormField>
        <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
          <PrimaryBtn style={{ flex: 1 }} onClick={onClose}>{t('settings.addDeviceConfirm')}</PrimaryBtn>
          <GhostBtn onClick={onBack}>{t('settings.cancel')}</GhostBtn>
        </div>
        <div style={{ fontSize: 10, color: T.textMuted, lineHeight: 1.5 }}>{t('settings.readOnlyNote')}</div>
      </div>
    </>
  );
}

function FormField({ label, children }) {
  return (
    <div>
      <div style={{ fontSize: 10, color: T.textMuted, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 6 }}>{label}</div>
      {children}
    </div>
  );
}

// ── Add Viewer Modal ────────────────────────────────────────────────────────
function AddViewerModal({ onClose, t }) {
  const [uname, setUname] = React.useState('');
  return (
    <Modal title={t('settings.addViewer')} onClose={onClose} width={440}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <FormField label={t('settings.username')}>
          <input value={uname} onChange={e => setUname(e.target.value)} placeholder="anna"
            style={{ width: '100%', background: T.raised, border: `1px solid ${T.border}`, borderRadius: 8, padding: '9px 12px', color: T.textPrimary, fontFamily: T.fontMono, fontSize: 13 }}/>
        </FormField>
        <div style={{ padding: '12px 14px', background: `${T.blue}14`, border: `1px solid ${T.blue}30`, borderRadius: 10, fontSize: 12, color: T.textSecondary, lineHeight: 1.5 }}>
          {t('settings.viewerNote')}
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
          <PrimaryBtn style={{ flex: 1 }} onClick={onClose}>{t('settings.createViewer')}</PrimaryBtn>
          <GhostBtn onClick={onClose}>{t('settings.cancel')}</GhostBtn>
        </div>
        <div style={{ fontSize: 10, color: T.textMuted }}>{t('settings.readOnlyNote')}</div>
      </div>
    </Modal>
  );
}

Object.assign(window, {
  V2Settings, SettingsSection, SettingsCard, SettingsRow, SettingsToggle,
  SettingsSelect, ReadOnlyField, Modal, FormField,
  DestructiveBtn, AddDeviceModal, AddViewerModal, ShellyForm,
});
