// Sidebar with brand, navigation, projects list, user card.
const SBIcons = window.Icons;
const { parseDateKey: sbDate } = window.PMStore;

const VIEWS = [
  { id: 'dashboard', label: 'Panel',         icon: 'Dashboard' },
  { id: 'all-tasks', label: 'Tüm Görevler',  icon: 'CheckSquare' },
  { id: 'calendar',  label: 'Takvim',        icon: 'Calendar' },
];

const projectAbbr = (name) =>
  name.split(/\s+/).filter(Boolean).map(w => w[0]).join('').slice(0, 2).toUpperCase();

function Sidebar({ state, user, setActiveView, setActiveProject, addProject, updateProject, deleteProject, openNewTask, onLogout }) {
  const [newProjectOpen, setNewProjectOpen] = React.useState(false);
  const [newProjectName, setNewProjectName] = React.useState('');
  const [editingProjectId, setEditingProjectId] = React.useState(null);
  const [editingProjectName, setEditingProjectName] = React.useState('');
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (newProjectOpen) setTimeout(() => inputRef.current?.focus(), 50);
  }, [newProjectOpen]);

  const handleAddProject = () => {
    const name = newProjectName.trim();
    if (!name) { setNewProjectOpen(false); return; }
    const colors = ['#047857','#1d4ed8','#b45309','#6d28d9','#be185d','#0e7490'];
    const id = window.PMStore.uid();
    addProject({ id, name, color: colors[Math.floor(Math.random()*colors.length)] });
    setActiveProject(id);
    setActiveView('kanban');
    setNewProjectName('');
    setNewProjectOpen(false);
  };

  const beginEditProject = (project) => {
    setEditingProjectId(project.id);
    setEditingProjectName(project.name);
  };

  const saveProjectEdit = () => {
    const name = editingProjectName.trim();
    if (!editingProjectId) return;
    if (name) updateProject(editingProjectId, { name });
    setEditingProjectId(null);
    setEditingProjectName('');
  };

  const removeProject = (project) => {
    const ok = window.confirm(`"${project.name}" projesi ve bu projedeki görevler silinsin mi?`);
    if (!ok) return;
    deleteProject(project.id);
    if (editingProjectId === project.id) {
      setEditingProjectId(null);
      setEditingProjectName('');
    }
  };

  const inboxCount = state.tasks.filter(t => t.status !== 'done').length;
  const todayCount = state.tasks.filter(t => {
    if (!t.due || t.status === 'done') return false;
    const d = sbDate(t.due); d.setHours(0,0,0,0);
    const n = new Date(); n.setHours(0,0,0,0);
    return d.getTime() === n.getTime();
  }).length;

  const counts = { dashboard: todayCount, 'all-tasks': inboxCount, calendar: 0 };

  const isProjectActive = (id) =>
    state.activeProjectId === id && (state.activeView === 'kanban' || state.activeView === 'list');

  return (
    <aside className="sidebar">
      <div className="sidebar-header">
        <div className="brand-mark">A</div>
        <div style={{ minWidth: 0 }}>
          <div className="brand-name">Akış</div>
          <div className="brand-sub">Proje Yönetimi</div>
        </div>
      </div>

      <div className="sidebar-actions">
        <button className="btn btn-ghost" onClick={() => setNewProjectOpen(true)}>
          <SBIcons.Folder size={15} strokeWidth={2.2} />
          Yeni Proje
        </button>
        <button className="btn btn-primary" onClick={openNewTask}>
          <SBIcons.Plus size={15} strokeWidth={2.5} />
          Yeni Görev
        </button>
      </div>

      <div className="sidebar-content">
        <div className="sidebar-section">
          {VIEWS.map(v => {
            const Icon = SBIcons[v.icon];
            const c = counts[v.id];
            return (
              <button
                key={v.id}
                className={`nav-item ${state.activeView === v.id ? 'active' : ''}`}
                onClick={() => setActiveView(v.id)}
              >
                <Icon size={17} />
                <span>{v.label}</span>
                {c > 0 && <span className="count">{c}</span>}
              </button>
            );
          })}
        </div>

        <div className="sidebar-section">
          <div className="sidebar-section-title">
            <span>Projeler</span>
            <button onClick={() => setNewProjectOpen(true)} title="Yeni proje">
              <SBIcons.Plus size={13} strokeWidth={2.5} />
            </button>
          </div>
          {state.projects.map(p => {
            const count = state.tasks.filter(t => t.projectId === p.id && t.status !== 'done').length;
            const active = isProjectActive(p.id);
            const editing = editingProjectId === p.id;
            return (
              <div key={p.id} className={`project-item-wrap ${active ? 'active' : ''}`}>
                {editing ? (
                  <div className={`project-item editing ${active ? 'active' : ''}`}>
                    <div className="project-tile" style={{ background: p.color }}>{projectAbbr(p.name)}</div>
                    <input
                      className="project-edit-input"
                      value={editingProjectName}
                      onChange={e => setEditingProjectName(e.target.value)}
                      onKeyDown={e => {
                        if (e.key === 'Enter') saveProjectEdit();
                        if (e.key === 'Escape') { setEditingProjectId(null); setEditingProjectName(''); }
                      }}
                      onBlur={saveProjectEdit}
                      autoFocus
                    />
                    {count > 0 && <span className="count">{count}</span>}
                  </div>
                ) : (
                  <button
                    className={`project-item ${active ? 'active' : ''}`}
                    onClick={() => { setActiveProject(p.id); setActiveView('kanban'); }}
                  >
                    <div className="project-tile" style={{ background: p.color }}>{projectAbbr(p.name)}</div>
                    <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, textAlign: 'left' }}>{p.name}</span>
                    {count > 0 && <span className="count">{count}</span>}
                  </button>
                )}
                <div className="project-actions">
                  <button onClick={(e) => { e.stopPropagation(); beginEditProject(p); }} title="Projeyi düzenle">
                    <SBIcons.Edit size={13} />
                  </button>
                  <button onClick={(e) => { e.stopPropagation(); removeProject(p); }} title="Projeyi sil">
                    <SBIcons.Trash size={13} />
                  </button>
                </div>
              </div>
            );
          })}
          {newProjectOpen && (
            <div style={{ padding: '6px 0' }}>
              <input
                ref={inputRef}
                className="input"
                placeholder="Proje adı..."
                value={newProjectName}
                onChange={e => setNewProjectName(e.target.value)}
                onKeyDown={e => {
                  if (e.key === 'Enter') handleAddProject();
                  if (e.key === 'Escape') { setNewProjectOpen(false); setNewProjectName(''); }
                }}
                onBlur={handleAddProject}
                style={{ fontSize: 13.5, padding: '8px 10px', minHeight: 38 }}
              />
            </div>
          )}
        </div>
      </div>

      <div className="sidebar-footer">
        <div className="user-card">
          <div className="avatar">{window.projectAbbr(user?.name || 'Zeynep Akın')}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="user-name">{user?.name || 'Zeynep Akın'}</div>
            <div className="user-email" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user?.email || 'zeynep@akisapp.com'}</div>
          </div>
          <button className="icon-btn icon-btn-sm" onClick={onLogout} title="Çıkış yap">
            <SBIcons.LogOut size={15} />
          </button>
        </div>
      </div>
    </aside>
  );
}

window.Sidebar = Sidebar;
window.projectAbbr = projectAbbr;
