// App.jsx — Root component
(function () {
  const { useState, useEffect } = React;

  function Settings({ kanbanLeads, clients }) {
    const { useState } = React;
    const [gcal, setGcal] = useState(true);
    const [meta, setMeta] = useState(true);
    const [smsReminders, setSmsReminders] = useState(true);
    const [emailReminders, setEmailReminders] = useState(true);
    const [reminderTiming, setReminderTiming] = useState('24h');

    const team = window.SEED.team.map((m,i) => ({ ...m, deals:[8,5,6,3][i]||4, value:[1240000,680000,815000,412000][i]||400000 }));

    const Toggle = ({ on, onClick }) => (
      <button onClick={onClick} style={{
        width:42, height:24, borderRadius:99, border:'none', cursor:'pointer', position:'relative', flexShrink:0,
        background: on ? 'linear-gradient(135deg,#7C5CFF,#4DA3FF)' : 'var(--bg2)', transition:'background .2s',
      }}>
        <div style={{ position:'absolute', top:3, left: on ? 21 : 3, width:18, height:18, borderRadius:'50%', background:'#fff', transition:'left .2s', boxShadow:'0 1px 4px rgba(0,0,0,.3)' }} />
      </button>
    );

    const fmtVal = v => v >= 1000000 ? (v/1000000).toFixed(1).replace('.',',')+' M zł' : Math.round(v/1000)+' k zł';

    return (
      <div style={{ display:'flex', flexDirection:'column', gap:20 }}>

        {/* Team accounts */}
        <div className="glass-card" style={{ padding:24 }}>
          <div style={{ fontSize:15, fontWeight:700, color:'var(--t1)', marginBottom:2 }}>Konta zespołu</div>
          <div style={{ fontSize:12, color:'var(--t3)', marginBottom:18 }}>Podgląd pracy handlowców — właściciel widzi wyniki całego zespołu</div>
          <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
            {team.map((m, i) => (
              <div key={m.name} style={{ display:'flex', alignItems:'center', gap:14, padding:'12px 0', borderBottom: i<team.length-1?'1px solid var(--bdr)':'none' }}>
                <div style={{ width:38, height:38, borderRadius:10, background:m.color, display:'flex', alignItems:'center', justifyContent:'center', fontSize:13, fontWeight:700, color:'#fff', flexShrink:0 }}>{m.initials}</div>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:13, fontWeight:600, color:'var(--t1)' }}>{m.name}</div>
                  <div style={{ fontSize:11, color:'var(--t3)' }}>{m.role}</div>
                </div>
                <div style={{ textAlign:'right' }}>
                  <div style={{ fontSize:13, fontWeight:700, color:'var(--t1)' }}>{fmtVal(m.value)}</div>
                  <div style={{ fontSize:11, color:'var(--t3)' }}>{m.deals} wygranych</div>
                </div>
              </div>
            ))}
          </div>
          <button style={{ marginTop:16, padding:'9px 16px', borderRadius:10, border:'1px solid var(--bdr)', background:'var(--bg1)', color:'var(--t1)', fontWeight:600, fontSize:13, cursor:'pointer' }}>+ Zaproś handlowca</button>
        </div>

        {/* Integrations */}
        <div className="glass-card" style={{ padding:24 }}>
          <div style={{ fontSize:15, fontWeight:700, color:'var(--t1)', marginBottom:2 }}>Integracje</div>
          <div style={{ fontSize:12, color:'var(--t3)', marginBottom:18 }}>Automatyzacje działające w tle</div>
          <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
            {[
              { label:'Kalendarz Google', on:gcal, set:setGcal },
              { label:'Leady z reklam Meta (Facebook/Instagram)', on:meta, set:setMeta },
            ].map(it => (
              <div key={it.label} style={{ display:'flex', alignItems:'center', gap:14, padding:'12px 0', borderBottom:'1px solid var(--bdr)' }}>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:13, fontWeight:600, color:'var(--t1)' }}>{it.label}</div>
                </div>
                <span style={{ fontSize:11, fontWeight:600, color: it.on?'#22C55E':'var(--t3)' }}>{it.on?'Połączono':'Rozłączone'}</span>
                <Toggle on={it.on} onClick={()=>it.set(v=>!v)} />
              </div>
            ))}
            <div style={{ display:'flex', alignItems:'center', gap:14, padding:'12px 0', borderBottom:'1px solid var(--bdr)' }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:'var(--t1)' }}>Przypomnienia SMS</div>
              </div>
              <Toggle on={smsReminders} onClick={()=>setSmsReminders(v=>!v)} />
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:14, padding:'12px 0', borderBottom:'1px solid var(--bdr)' }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:'var(--t1)' }}>Przypomnienia e-mail</div>
              </div>
              <Toggle on={emailReminders} onClick={()=>setEmailReminders(v=>!v)} />
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:14, padding:'12px 0' }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:'var(--t1)' }}>Wyślij przypomnienie przed spotkaniem</div>
              </div>
              <div style={{ width:140 }}>
                <window.DemoSelect value={reminderTiming} onChange={setReminderTiming} options={[{value:'1h',label:'1 godzinę przed'},{value:'24h',label:'24 godziny przed'},{value:'48h',label:'48 godzin przed'}]} />
              </div>
            </div>
          </div>
        </div>

        {/* Data */}
        <div className="glass-card" style={{ padding:24 }}>
          <div style={{ fontSize:15, fontWeight:700, color:'var(--t1)', marginBottom:2 }}>Dane</div>
          <div style={{ fontSize:12, color:'var(--t3)', marginBottom:18 }}>Import i utrzymanie bazy klientów</div>
          <div style={{ display:'flex', gap:10, flexWrap:'wrap' }}>
            <button onClick={() => window.__navigateTo && window.__navigateTo('clients')} style={{ padding:'9px 18px', borderRadius:10, border:'1px solid var(--bdr)', background:'var(--bg1)', color:'var(--t1)', fontWeight:600, fontSize:13, cursor:'pointer' }}>⬆ Importuj bazę (Excel/CSV)</button>
            <span style={{ fontSize:12, color:'var(--t3)', alignSelf:'center' }}>System zainstalowany na Państwa serwerze — 0 zł / msc utrzymania</span>
          </div>
        </div>
      </div>
    );
  }

  function LoginScreen({ onLogin }) {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);

    const submit = (e) => {
      e.preventDefault();
      setLoading(true);
      setTimeout(() => onLogin(), 700);
    };

    const inputStyle = { width:'100%', padding:'11px 14px', borderRadius:10, border:'1px solid var(--bdr)', background:'var(--bg-input)', color:'var(--t1)', fontSize:14, outline:'none' };

    return (
      <div style={{ height:'100vh', display:'flex', alignItems:'center', justifyContent:'center', position:'relative', zIndex:1 }}>
        <div className="glass-card" style={{ width:400, maxWidth:'92vw', padding:36 }}>
          <div style={{ display:'flex', justifyContent:'center', marginBottom:22 }}>
            <span style={{ fontSize:24, fontWeight:800, letterSpacing:-1, background:'linear-gradient(135deg,#a78bff,#4DA3FF)', WebkitBackgroundClip:'text', WebkitTextFillColor:'transparent', backgroundClip:'text' }}>DemoCRM</span>
          </div>
          <div style={{ textAlign:'center', marginBottom:26 }}>
            <div style={{ fontSize:13, color:'var(--t3)' }}>Zaloguj się, aby przejść do panelu sprzedaży</div>
          </div>
          <form onSubmit={submit} style={{ display:'flex', flexDirection:'column', gap:14 }}>
            <div>
              <label style={{ fontSize:11, fontWeight:600, color:'var(--t3)', marginBottom:5, display:'block', textTransform:'uppercase', letterSpacing:0.5 }}>E-mail</label>
              <input style={inputStyle} type="email" value={email} onChange={e=>setEmail(e.target.value)} />
            </div>
            <div>
              <label style={{ fontSize:11, fontWeight:600, color:'var(--t3)', marginBottom:5, display:'block', textTransform:'uppercase', letterSpacing:0.5 }}>Hasło</label>
              <input style={inputStyle} type="password" value={password} onChange={e=>setPassword(e.target.value)} />
            </div>
            <button type="submit" disabled={loading} style={{ marginTop:8, padding:'12px 0', borderRadius:10, border:'none', background:'linear-gradient(135deg,#7C5CFF,#4DA3FF)', color:'#fff', fontWeight:700, fontSize:14, cursor: loading?'wait':'pointer', opacity: loading?.7:1 }}>
              {loading ? 'Logowanie…' : 'Zaloguj się'}
            </button>
          </form>
          <div style={{ fontSize:11, color:'var(--t3)', textAlign:'center', marginTop:18 }}>To wersja demonstracyjna — dowolne dane zalogują Cię jako Sales Manager.</div>
        </div>
      </div>
    );
  }

  function App() {
    const [loggedIn,    setLoggedIn]    = useState(false);
    const [darkMode,    setDarkMode]    = useState(true);
    const [activeView,  setActiveView]  = useState('dashboard');
    const [kanbanLeads, setKanbanLeads] = useState(() => window.SEED.kanbanLeads);
    const [tasks,       setTasks]       = useState(() => window.SEED.tasks);
    const [todayTasks,  setTodayTasks]  = useState(() => window.SEED.todayTasks);

    // Apply theme class to <html>
    useEffect(() => {
      if (darkMode) {
        document.documentElement.classList.remove('light');
      } else {
        document.documentElement.classList.add('light');
      }
    }, [darkMode]);

    // Allow Settings to deep-link into other views; allow Shell to trigger logout
    useEffect(() => {
      window.__navigateTo = setActiveView;
      window.__onLogout = () => { setLoggedIn(false); setActiveView('dashboard'); };
    }, []);

    if (!loggedIn) return <LoginScreen onLogin={() => setLoggedIn(true)} />;

    // View transition key for re-mount animation
    const viewKey = activeView;

    let view;
    if (activeView === 'dashboard') view = <window.Dashboard todayTasks={todayTasks} setTodayTasks={setTodayTasks} kanbanLeads={kanbanLeads} />;
    else if (activeView === 'kanban')    view = <window.Kanban leads={kanbanLeads} setLeads={setKanbanLeads} />;
    else if (activeView === 'clients')   view = <window.Clients />;
    else if (activeView === 'tasks')     view = <window.Tasks tasks={tasks} setTasks={setTasks} />;
    else if (activeView === 'calendar')  view = <window.Calendar tasks={tasks} setTasks={setTasks} />;
    else if (activeView === 'reports')   view = <window.Reports />;
    else if (activeView === 'settings')  view = <Settings />;

    return (
      <window.Shell activeView={activeView} setActiveView={setActiveView} darkMode={darkMode} setDarkMode={setDarkMode}>
        <div key={viewKey} style={{ animation:'fadeSlideIn .28s cubic-bezier(.4,0,.2,1)', paddingBottom:24 }}>
          {view}
        </div>
      </window.Shell>
    );
  }

  ReactDOM.createRoot(document.getElementById('root')).render(<App />);
})();
