// Dashboard view: stats, project progress, upcoming tasks, activity.
const DBIcons = window.Icons;
const { projectProgress: dbProjectProgress, relativeDate: dbRelDate, formatDate: dbFmtDate, isOverdue: dbOverdue, parseDateKey: dbDate } = window.PMStore;
const { Tag: DBTag, Priority: DBPriority, ProgressBar: DBProgress } = window.UI;

function Dashboard({ state, user, onSelectTask, setActiveView, setActiveProject }) {
  const total = state.tasks.length;
  const done = state.tasks.filter(t => t.status === 'done').length;
  const inProgress = state.tasks.filter(t => t.status === 'doing' || t.status === 'review').length;
  const overdue = state.tasks.filter(t => dbOverdue(t.due, t.status)).length;
  const dueToday = state.tasks.filter(t => {
    if (!t.due || t.status === 'done') return false;
    const d = dbDate(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 upcoming = [...state.tasks]
    .filter(t => t.due && t.status !== 'done')
    .sort((a,b) => dbDate(a.due) - dbDate(b.due))
    .slice(0, 6);

  const tagById = Object.fromEntries(state.tags.map(t => [t.id, t]));
  const projById = Object.fromEntries(state.projects.map(p => [p.id, p]));

  // Activity heatmap — deterministic pattern based on actual tasks completed in recent days
  const heat = React.useMemo(() => {
    const cells = Array.from({ length: 100 }, (_, i) => {
      // simple deterministic pattern; bias toward green
      const seed = (i * 9301 + 49297) % 233280;
      const r = seed / 233280;
      if (r < 0.45) return 0;
      if (r < 0.65) return 1;
      if (r < 0.83) return 2;
      if (r < 0.95) return 3;
      return 4;
    });
    return cells;
  }, []);

  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 6) return 'İyi geceler';
    if (h < 12) return 'Günaydın';
    if (h < 18) return 'İyi öğleden sonra';
    return 'İyi akşamlar';
  })();

  const todayStr = new Date().toLocaleDateString('tr-TR', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

  return (
    <div className="content">
      <div className="dash-header">
        <div>
          <h2 className="dash-greeting">{greeting}, {(user?.name || 'Hasan').split(' ')[0]}</h2>
          <div className="dash-sub">{todayStr} · Bugün <strong style={{color:'var(--text)'}}>{dueToday}</strong> görev teslim, <strong style={{color:'var(--text)'}}>{inProgress}</strong> aktif görev var.</div>
        </div>
      </div>

      <div className="stats-grid">
        <StatCard
          icon={<DBIcons.CheckSquare size={18} />}
          iconBg="var(--accent-soft)" iconColor="var(--accent-text)"
          value={total} label="Toplam görev"
          delta={`${done} tamamlandı`} deltaDir="up"
        />
        <StatCard
          icon={<DBIcons.Activity size={18} />}
          iconBg="var(--status-doing-bg)" iconColor="var(--status-doing)"
          value={inProgress} label="Devam eden"
          delta={`${state.projects.length} aktif proje`}
        />
        <StatCard
          icon={<DBIcons.Clock size={18} />}
          iconBg="var(--p-med-bg)" iconColor="var(--p-med)"
          value={dueToday} label="Bugün teslim"
          delta={dueToday > 0 ? 'Önceliklendir!' : 'Sakin bir gün'}
        />
        <StatCard
          icon={<DBIcons.AlertCircle size={18} />}
          iconBg="var(--p-high-bg)" iconColor="var(--p-high)"
          value={overdue} label="Geciken"
          delta={overdue > 0 ? 'İncele' : 'Hepsi güncel'}
          deltaDir={overdue > 0 ? 'down' : 'up'}
        />
      </div>

      <div className="dash-grid">
        {/* Project progress */}
        <div className="card">
          <h3 className="dash-section-title">
            <span>Proje ilerlemesi</span>
            <span className="link" onClick={() => setActiveView('kanban')}>Hepsini gör →</span>
          </h3>
          {state.projects.map(p => {
            const pct = dbProjectProgress(p.id, state.tasks);
            const projTasks = state.tasks.filter(t => t.projectId === p.id);
            const doneCount = projTasks.filter(t => t.status === 'done').length;
            return (
              <div key={p.id} className="project-progress" onClick={() => { setActiveProject(p.id); setActiveView('kanban'); }}>
                <div className="project-tile" style={{ background: p.color, width: 32, height: 32, fontSize: 12 }}>
                  {window.projectAbbr(p.name)}
                </div>
                <div style={{ minWidth: 0 }}>
                  <div className="project-progress-name">{p.name}</div>
                  <div className="project-progress-meta">{doneCount}/{projTasks.length} görev · {p.description}</div>
                </div>
                <DBProgress value={pct} color={p.color} />
                <div className="pct">{pct}%</div>
              </div>
            );
          })}
        </div>

        {/* Upcoming + activity */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="card">
            <h3 className="dash-section-title">
              <span>Yaklaşan görevler</span>
              <span className="link" onClick={() => setActiveView('list')}>Liste →</span>
            </h3>
            {upcoming.length === 0 ? (
              <div style={{ padding: 12, color: 'var(--text-muted)', fontSize: 13 }}>Yaklaşan görev yok 🎉</div>
            ) : upcoming.map(t => {
              const proj = projById[t.projectId];
              const overdueT = dbOverdue(t.due, t.status);
              const dt = dbDate(t.due);
              const months = ['OCA','ŞUB','MAR','NİS','MAY','HAZ','TEM','AĞU','EYL','EKİ','KAS','ARA'];
              return (
                <div key={t.id} className="upcoming-item" onClick={() => onSelectTask(t.id)}>
                  <div className="upcoming-date" style={overdueT ? { color: 'var(--p-high)' } : undefined}>
                    <div className="upcoming-date-day">{dt.getDate()}</div>
                    <div className="upcoming-date-month">{months[dt.getMonth()]}</div>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="upcoming-title">{t.title}</div>
                    <div className="upcoming-meta">
                      {proj && <><span className="project-dot" style={{ background: proj.color }} /><span>{proj.name}</span></>}
                      <span>·</span>
                      <span style={overdueT ? { color: 'var(--p-high)', fontWeight: 600 } : undefined}>{dbRelDate(t.due)}</span>
                    </div>
                  </div>
                  <DBPriority value={t.priority} />
                </div>
              );
            })}
          </div>

          <div className="card">
            <h3 className="dash-section-title">
              <span>Son 100 günün etkinliği</span>
              <span style={{ fontSize: 11, color: 'var(--text-faint)', fontWeight: 500 }}>az → çok</span>
            </h3>
            <div className="heatmap">
              {heat.map((lvl, i) => (
                <div key={i} className={`heat-cell ${lvl > 0 ? `heat-${lvl}` : ''}`} />
              ))}
            </div>
            <div style={{ marginTop: 12, fontSize: 12, color: 'var(--text-muted)', display: 'flex', justifyContent: 'space-between' }}>
              <span><strong style={{color:'var(--accent)'}}>{done}</strong> görev tamamlandı</span>
              <span>Bu çeyrekte</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCard({ icon, iconBg, iconColor, value, label, delta, deltaDir }) {
  return (
    <div className="stat-card">
      <div className="stat-icon" style={{ background: iconBg, color: iconColor }}>{icon}</div>
      <div className="stat-value">{value}</div>
      <div className="stat-label">{label}</div>
      {delta && <div className={`stat-delta ${deltaDir || ''}`}>{delta}</div>}
    </div>
  );
}

window.Dashboard = Dashboard;
