// Gantt view: horizontal timeline of all projects & tasks
const GTIcons = window.Icons;
const { parseDateKey: gtDate, toDateKey: gtDateKey, relativeDate: gtRel } = window.PMStore;

const ZOOM_OPTS = [
  { id: 'week',    label: '2 Hafta', days: 14 },
  { id: 'month',   label: '1 Ay',    days: 30 },
  { id: 'quarter', label: '3 Ay',    days: 90 },
];

function addDaysGT(d, n) { const r = new Date(d); r.setDate(r.getDate() + n); return r; }
function startOfDayGT(d) { const r = new Date(d); r.setHours(0,0,0,0); return r; }
function sameMonthYear(d) { return d.toLocaleDateString('tr-TR', { month: 'short', year: '2-digit' }); }

function GanttView({ state, onSelectTask }) {
  const [zoom, setZoom]               = React.useState('month');
  const [projectFilter, setPF]        = React.useState('all');
  const [showCompleted, setShowComp]  = React.useState(false);
  const [offset, setOffset]           = React.useState(0); // day offset for panning

  const zoomCfg = ZOOM_OPTS.find(z => z.id === zoom) || ZOOM_OPTS[1];
  const today   = startOfDayGT(new Date());
  const rangeStart = addDaysGT(today, -Math.round(zoomCfg.days * 0.3) + offset);
  const rangeEnd   = addDaysGT(rangeStart, zoomCfg.days);
  const totalDays  = zoomCfg.days;

  const projects = (state.projects || []).filter(p => !p.archived && (projectFilter === 'all' || p.id === projectFilter));
  const allTasks  = state.tasks || [];

  const dayPct = (d) => Math.max(0, Math.min(100, ((startOfDayGT(d) - rangeStart) / (1000 * 60 * 60 * 24 * totalDays)) * 100));

  // Day column headers
  const dayHeaders = React.useMemo(() => {
    const headers = [];
    let prev = '';
    for (let i = 0; i <= totalDays; i++) {
      const d = addDaysGT(rangeStart, i);
      const label = d.getDate() === 1 || i === 0 ? sameMonthYear(d) : '';
      headers.push({ d, label, isToday: startOfDayGT(d).getTime() === today.getTime() });
    }
    return headers;
  }, [zoom, offset]);

  const todayPct = dayPct(today);

  return (
    <div className="content gantt-content">
      {/* Toolbar */}
      <div className="gantt-toolbar">
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {ZOOM_OPTS.map(z => (
            <button key={z.id} className={`btn btn-sm ${zoom === z.id ? 'btn-primary' : 'btn-ghost'}`}
              onClick={() => setZoom(z.id)}>{z.label}</button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <button className="icon-btn" onClick={() => setOffset(o => o - Math.round(zoomCfg.days / 2))} title="Geri">
            <GTIcons.ChevronLeft size={16} />
          </button>
          <button className="btn btn-ghost btn-sm" onClick={() => setOffset(0)}>Bugün</button>
          <button className="icon-btn" onClick={() => setOffset(o => o + Math.round(zoomCfg.days / 2))} title="İleri">
            <GTIcons.ChevronRight size={16} />
          </button>
          <select className="select-control" value={projectFilter} onChange={e => setPF(e.target.value)}>
            <option value="all">Tüm Firmalar</option>
            {state.projects.filter(p => !p.archived).map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <label style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--text-muted)', cursor: 'pointer' }}>
            <input type="checkbox" checked={showCompleted} onChange={e => setShowComp(e.target.checked)}
              style={{ accentColor: 'var(--accent)' }} />
            Tamamlananlar
          </label>
        </div>
      </div>

      {/* Chart area */}
      <div className="gantt-wrap">
        {/* Left panel: project + task names */}
        <div className="gantt-left">
          <div className="gantt-left-header">Görev</div>
          {projects.map(p => {
            const pTasks = allTasks.filter(t =>
              t.projectId === p.id && !t.archived && (showCompleted || t.status !== 'done') && t.due
            );
            if (!pTasks.length) return null;
            return (
              <React.Fragment key={p.id}>
                <div className="gantt-project-row">
                  <span className="project-dot" style={{ background: p.color }} />
                  <span>{p.name}</span>
                </div>
                {pTasks.map(t => (
                  <div key={t.id} className={`gantt-task-label ${t.status === 'done' ? 'done' : ''}`}
                    onClick={() => onSelectTask(t.id)} title={t.title}>
                    {t.title}
                  </div>
                ))}
              </React.Fragment>
            );
          })}
        </div>

        {/* Right panel: timeline */}
        <div className="gantt-right">
          {/* Date headers */}
          <div className="gantt-date-header">
            {dayHeaders.filter((_, i) => zoom === 'week' || i % (zoom === 'month' ? 3 : 7) === 0).map((h, i) => (
              <div key={i} className={`gantt-date-cell ${h.isToday ? 'today' : ''}`}
                style={{ left: `${dayPct(h.d)}%` }}>
                {h.label || h.d.getDate()}
              </div>
            ))}
          </div>

          {/* Grid + task bars */}
          <div className="gantt-grid">
            {/* Today line */}
            {todayPct >= 0 && todayPct <= 100 && (
              <div className="gantt-today-line" style={{ left: `${todayPct}%` }} />
            )}

            {projects.map(p => {
              const pTasks = allTasks.filter(t =>
                t.projectId === p.id && !t.archived && (showCompleted || t.status !== 'done') && t.due
              );
              if (!pTasks.length) return null;
              return (
                <React.Fragment key={p.id}>
                  <div className="gantt-project-band" />
                  {pTasks.map(t => {
                    const dueD  = gtDate(t.due);
                    const startD = t.createdAt ? startOfDayGT(new Date(t.createdAt)) : startOfDayGT(dueD);
                    const left   = dayPct(startD);
                    const right  = dayPct(dueD);
                    const width  = Math.max(right - left, 0.8);
                    const overdue = t.status !== 'done' && dueD < today;
                    return (
                      <div key={t.id} className="gantt-bar-row">
                        {width > 0.1 && (
                          <div
                            className={`gantt-bar ${t.status === 'done' ? 'done' : ''} ${overdue ? 'overdue' : ''}`}
                            style={{ left: `${left}%`, width: `${width}%`, background: p.color }}
                            onClick={() => onSelectTask(t.id)}
                            title={`${t.title} — ${gtRel(t.due)}`}
                          >
                            <span className="gantt-bar-label">{t.title}</span>
                          </div>
                        )}
                        {/* Due date dot if bar too narrow */}
                        {width <= 0.1 && (
                          <div className="gantt-dot" style={{ left: `${right}%`, background: p.color }}
                            onClick={() => onSelectTask(t.id)} title={t.title} />
                        )}
                      </div>
                    );
                  })}
                </React.Fragment>
              );
            })}
          </div>
        </div>
      </div>

      {projects.every(p => !allTasks.some(t => t.projectId === p.id && t.due)) && (
        <div className="empty" style={{ marginTop: 40 }}>
          <div className="empty-icon"><GTIcons.GanttChart size={24} /></div>
          <div className="empty-title">Teslim tarihi olan görev bulunamadı</div>
          <div>Görevlere teslim tarihi ekleyin.</div>
        </div>
      )}
    </div>
  );
}

window.GanttView = GanttView;
