// Tasks.jsx
(function () {
  const { useState } = React;

  const priorityConfig = {
    high:   { label: 'Wysoki',  color: '#EF4444', bg: 'rgba(239,68,68,.12)'   },
    medium: { label: 'Średni',  color: '#F59E0B', bg: 'rgba(245,158,11,.12)'  },
    low:    { label: 'Niski',   color: '#22C55E', bg: 'rgba(34,197,94,.12)'   },
  };

  function getCategory(task) {
    const today = '2026-07-21';
    if (task.due < today) return 'overdue';
    if (task.due === today) return 'today';
    return 'upcoming';
  }

  function fmtDue(due) {
    const [y, m, d] = due.split('-');
    const months = ['sty','lut','mar','kwi','maj','cze','lip','sie','wrz','paź','lis','gru'];
    return `${parseInt(d)} ${months[parseInt(m)-1]}`;
  }

  // ── Task Item ─────────────────────────────────────────────────────
  function TaskItem({ task, onToggle }) {
    const pc = priorityConfig[task.priority];
    const cat = getCategory(task);
    const isOverdue = cat === 'overdue' && !task.done;
    const assignee = (window.SEED.team || []).find(m => m.id === task.assignee);
    return (
      <div style={{
        display:'flex', alignItems:'center', gap:12, padding:'12px 16px',
        borderRadius:12, transition:'background .15s',
        background:'transparent',
        opacity: task.done ? 0.5 : 1,
        borderLeft: `3px solid ${task.done ? 'transparent' : pc.color}`,
      }}
      onMouseEnter={e=>e.currentTarget.style.background='var(--bg-hover)'}
      onMouseLeave={e=>e.currentTarget.style.background='transparent'}
      >
        {/* Checkbox */}
        <div onClick={() => onToggle(task.id)} style={{
          width:18, height:18, borderRadius:6, flexShrink:0, cursor:'pointer',
          border: task.done ? 'none' : `1.5px solid ${pc.color}`,
          background: task.done ? '#22C55E' : 'transparent',
          display:'flex', alignItems:'center', justifyContent:'center',
          transition:'all .15s',
        }}>
          {task.done && <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.5" strokeLinecap="round"><path d="M20 6L9 17l-5-5"/></svg>}
        </div>

        {/* Text */}
        <div style={{ flex:1 }}>
          <div style={{ fontSize:13, color:'var(--t1)', textDecoration: task.done ? 'line-through' : 'none', lineHeight:1.4 }}>{task.text}</div>
        </div>

        {/* Assignee */}
        {assignee && (
          <span style={{ display:'flex', alignItems:'center', gap:6, flexShrink:0 }} title={assignee.name}>
            <span style={{ width:22, height:22, borderRadius:7, background:assignee.color, display:'flex', alignItems:'center', justifyContent:'center', fontSize:9.5, fontWeight:700, color:'#fff' }}>{assignee.initials}</span>
            <span style={{ fontSize:11.5, color:'var(--t2)', whiteSpace:'nowrap' }}>{assignee.name.split(' ')[0]}</span>
          </span>
        )}

        {/* Priority badge */}
        <span style={{ fontSize:11, padding:'2px 8px', borderRadius:99, background:pc.bg, color:pc.color, fontWeight:600, flexShrink:0 }}>{pc.label}</span>

        {/* Due date */}
        <span style={{ fontSize:12, color: isOverdue ? '#EF4444' : 'var(--t3)', fontWeight: isOverdue ? 600 : 400, flexShrink:0, minWidth:40, textAlign:'right' }}>
          {isOverdue ? '⚠ ' : ''}{fmtDue(task.due)}
        </span>
      </div>
    );
  }

  // ── Add Task Modal ────────────────────────────────────────────────
  function AddTaskModal({ onClose, onSave }) {
    const team = window.SEED.team || [];
    const [form, setForm] = useState({ text:'', priority:'medium', due:'2026-07-21', assignee: team[0]?.id || '' });
    const set = (k,v) => setForm(f => ({ ...f, [k]:v }));
    const canSave = form.text.trim().length > 0;

    const submit = () => {
      if (!canSave) return;
      onSave({ id:'T'+Math.random().toString(36).slice(2,8).toUpperCase(), text:form.text.trim(), priority:form.priority, due:form.due, done:false, assignee:form.assignee });
      onClose();
    };

    const inputStyle = { width:'100%', padding:'9px 12px', borderRadius:9, border:'1px solid var(--bdr)', background:'var(--bg-input)', color:'var(--t1)', fontSize:13, outline:'none' };
    const labelStyle = { fontSize:11, fontWeight:600, color:'var(--t3)', marginBottom:5, display:'block', textTransform:'uppercase', letterSpacing:0.5 };

    return (
      <>
        <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:60, backdropFilter:'blur(3px)' }} />
        <div style={{ position:'fixed', top:'50%', left:'50%', transform:'translate(-50%,-50%)', width:420, maxWidth:'92vw', background:'var(--bg-sidebar)', border:'1px solid var(--bdr)', borderRadius:18, zIndex:61, padding:24, boxShadow:'0 30px 80px rgba(0,0,0,.5)', backdropFilter:'blur(32px)' }}>
          <div style={{ fontSize:16, fontWeight:700, color:'var(--t1)', marginBottom:18 }}>Nowe zadanie</div>
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            <div><label style={labelStyle}>Treść zadania *</label><input style={inputStyle} value={form.text} onChange={e=>set('text',e.target.value)} placeholder="np. Zadzwoń do klienta" autoFocus /></div>
            <div>
              <label style={labelStyle}>Przypisz do</label>
              <window.DemoSelect value={form.assignee} onChange={v=>set('assignee',v)} options={team.map(m => ({ value:m.id, label:m.name }))} />
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
              <div>
                <label style={labelStyle}>Priorytet</label>
                <window.DemoSelect value={form.priority} onChange={v=>set('priority',v)} options={[{value:'high',label:'Wysoki'},{value:'medium',label:'Średni'},{value:'low',label:'Niski'}]} />
              </div>
              <div><label style={labelStyle}>Termin</label><input type="date" style={inputStyle} value={form.due} onChange={e=>set('due',e.target.value)} /></div>
            </div>
          </div>
          <div style={{ display:'flex', gap:8, marginTop:22 }}>
            <button onClick={onClose} style={{ flex:1, padding:'10px 0', borderRadius:10, border:'1px solid var(--bdr)', background:'var(--bg1)', color:'var(--t1)', fontWeight:600, fontSize:13, cursor:'pointer' }}>Anuluj</button>
            <button onClick={submit} disabled={!canSave} style={{ flex:1, padding:'10px 0', borderRadius:10, border:'none', background: canSave ? 'linear-gradient(135deg,#7C5CFF,#4DA3FF)' : 'var(--bg2)', color: canSave ? '#fff' : 'var(--t3)', fontWeight:600, fontSize:13, cursor: canSave ? 'pointer' : 'not-allowed' }}>Dodaj zadanie</button>
          </div>
        </div>
      </>
    );
  }

  // ── Tasks (main export) ───────────────────────────────────────────
  window.Tasks = function Tasks({ tasks, setTasks }) {
    const [tab, setTab] = useState('today');
    const [showAdd, setShowAdd] = useState(false);
    const today = '2026-07-21';

    const tabs = [
      { id:'today',    label:'Dziś',         filter: t => t.due === today },
      { id:'overdue',  label:'Zaległe',      filter: t => t.due < today && !t.done },
      { id:'upcoming', label:'Nadchodzące',  filter: t => t.due > today },
    ];

    const [assigneeFilter, setAssigneeFilter] = useState('all');
    const team = window.SEED.team || [];
    const activeTab = tabs.find(t => t.id === tab);
    const filtered = tasks.filter(activeTab.filter).filter(t => assigneeFilter === 'all' || t.assignee === assigneeFilter);

    const toggle = (id) => setTasks(prev => prev.map(t => t.id === id ? { ...t, done: !t.done } : t));

    const overdueCnt = tasks.filter(t => t.due < today && !t.done).length;
    const todayCnt   = tasks.filter(t => t.due === today).length;

    return (
      <div>
        {/* Header */}
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:20 }}>
          <div>
            <div style={{ fontSize:15, fontWeight:700, color:'var(--t1)' }}>Wszystkie zadania</div>
            <div style={{ fontSize:12, color:'var(--t3)', marginTop:2 }}>
              {tasks.filter(t=>!t.done).length} aktywnych · {tasks.filter(t=>t.done).length} ukończonych
            </div>
          </div>
          <button onClick={()=>setShowAdd(true)} style={{ padding:'8px 16px', borderRadius:10, border:'none', background:'linear-gradient(135deg,#7C5CFF,#4DA3FF)', color:'#fff', fontWeight:600, fontSize:13, cursor:'pointer', display:'flex', alignItems:'center', gap:6 }}>
            + Nowe zadanie
          </button>
        </div>

        {/* Team overview — click an employee to see their tasks */}
        <div className="glass-card" style={{ padding:'16px 18px', marginBottom:16 }}>
          <div style={{ fontSize:13, fontWeight:700, color:'var(--t1)', marginBottom:12 }}>Zadania zespołu</div>
          <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
            <button onClick={()=>setAssigneeFilter('all')} style={{
              display:'flex', alignItems:'center', gap:8, padding:'6px 14px 6px 6px', borderRadius:99,
              border: assigneeFilter==='all' ? '1.5px solid #7C5CFF' : '1px solid var(--bdr)',
              background: assigneeFilter==='all' ? 'rgba(124,92,255,.18)' : 'var(--bg1)', cursor:'pointer', outline:'none',
              boxShadow: assigneeFilter==='all' ? '0 0 0 3px rgba(124,92,255,.12)' : 'none', transition:'all .15s',
            }}>
              <span style={{ width:26, height:26, borderRadius:'50%', background:'var(--bg2)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:12 }}>👥</span>
              <span style={{ fontSize:13, fontWeight: assigneeFilter==='all'?700:500, color: assigneeFilter==='all'?'#7C5CFF':'var(--t1)' }}>Wszyscy ({tasks.filter(t=>!t.done).length})</span>
            </button>
            {team.map(m => {
              const cnt = tasks.filter(t => t.assignee === m.id && !t.done).length;
              const active = assigneeFilter === m.id;
              return (
                <button key={m.id} onClick={()=>setAssigneeFilter(m.id)} style={{
                  display:'flex', alignItems:'center', gap:8, padding:'6px 14px 6px 6px', borderRadius:99,
                  border: active ? `1.5px solid ${m.color}` : '1px solid var(--bdr)',
                  background: active ? `${m.color}22` : 'var(--bg1)', cursor:'pointer', outline:'none',
                  boxShadow: active ? `0 0 0 3px ${m.color}22` : 'none', transition:'all .15s',
                }}>
                  <span style={{ width:26, height:26, borderRadius:'50%', background:m.color, display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, color:'#fff' }}>{m.initials}</span>
                  <span style={{ fontSize:13, fontWeight: active?700:500, color: active?m.color:'var(--t1)' }}>{m.name.split(' ')[0]} ({cnt})</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display:'flex', gap:6, marginBottom:16, alignItems:'center', flexWrap:'wrap' }}>
          {assigneeFilter !== 'all' && (
            <span style={{ fontSize:12, color:'var(--t3)', marginRight:4 }}>
              Zadania: <strong style={{ color:'var(--t1)' }}>{team.find(m=>m.id===assigneeFilter)?.name}</strong>
            </span>
          )}
          {tabs.map(t => (
            <button key={t.id} onClick={()=>setTab(t.id)} style={{
              padding:'7px 16px', borderRadius:9, border:'1px solid var(--bdr)',
              background: tab===t.id ? 'rgba(124,92,255,.2)' : 'var(--bg1)',
              color: tab===t.id ? '#7C5CFF' : 'var(--t2)',
              fontWeight: tab===t.id ? 600 : 400, fontSize:13,
              cursor:'pointer', outline:'none', transition:'all .15s',
              boxShadow: tab===t.id ? 'inset 0 0 0 1px rgba(124,92,255,.4)' : 'none',
              position:'relative',
            }}>
              {t.label}
              {t.id==='overdue' && overdueCnt>0 && (
                <span style={{ marginLeft:6, padding:'1px 6px', borderRadius:99, background:'#EF4444', color:'#fff', fontSize:10, fontWeight:700 }}>{overdueCnt}</span>
              )}
              {t.id==='today' && todayCnt>0 && (
                <span style={{ marginLeft:6, padding:'1px 6px', borderRadius:99, background:'rgba(124,92,255,.6)', color:'#fff', fontSize:10, fontWeight:700 }}>{todayCnt}</span>
              )}
            </button>
          ))}
        </div>

        {/* List */}
        <div className="glass-card" style={{ padding:'8px 0', overflow:'hidden' }}>
          {filtered.length === 0 ? (
            <div style={{ padding:'40px', textAlign:'center', color:'var(--t3)', fontSize:14 }}>
              {tab==='overdue' ? '🎉 Brak zaległych zadań!' : 'Brak zadań w tej kategorii'}
            </div>
          ) : (
            filtered.map((t,i) => (
              <div key={t.id}>
                <TaskItem task={t} onToggle={toggle} />
                {i < filtered.length-1 && <div style={{ height:1, background:'var(--bdr)', margin:'0 16px' }} />}
              </div>
            ))
          )}
        </div>

        {/* Priority legend */}
        <div style={{ display:'flex', gap:16, marginTop:16, padding:'12px 16px' }}>
          <span style={{ fontSize:11, color:'var(--t3)' }}>Priorytet:</span>
          {Object.entries(priorityConfig).map(([k, v]) => (
            <span key={k} style={{ display:'flex', alignItems:'center', gap:5, fontSize:11, color:'var(--t2)' }}>
              <span style={{ width:8, height:8, borderRadius:2, background:v.color, display:'inline-block' }} />
              {v.label}
            </span>
          ))}
        </div>

        {showAdd && <AddTaskModal onClose={()=>setShowAdd(false)} onSave={t => setTasks(prev => [t, ...prev])} />}
      </div>
    );
  };
})();
