/* global React, Icon, db */
/* global ttFmtDuration, ttStartOfDay, ttStartOfWeek, ttDateInputVal, ttParseDateTime, ttProjectById, ttCycleById, ttSessionMs */
/* global TtProjectDot */
const { useState, useMemo } = React;

// ============================================================
// TtSummaryView — total time by task, project, and tag for a range.
// Sessions are joined to their task to attribute project/tags.
// Horizontal CSS bars + table.
// ============================================================

const TT_SUM_RANGES = [
  { id: 'today', label: 'Today' },
  { id: 'week',  label: 'This week' },
  { id: 'month', label: 'This month' },
  { id: 'custom', label: 'Custom' },
];

function TtSummaryView({ sessions, tasksById, cyclesById, projects, settings }) {
  const [range, setRange] = useState('week');
  const [from, setFrom] = useState(() => ttStartOfDay(Date.now()) - 6 * 86400000);
  const [to, setTo] = useState(() => ttStartOfDay(Date.now()));

  const [lo, hi] = useMemo(() => {
    const now = Date.now();
    const today = ttStartOfDay(now);
    switch (range) {
      case 'today': return [today, today + 86400000];
      case 'month': { const d = new Date(now); d.setDate(1); d.setHours(0,0,0,0); return [d.getTime(), now + 86400000]; }
      case 'custom': return [from || 0, (to || today) + 86400000];
      case 'week':
      default: { const w = ttStartOfWeek(now, settings.weekStartsMonday); return [w, w + 7 * 86400000]; }
    }
  }, [range, from, to, settings.weekStartsMonday]);

  const inRange = useMemo(
    () => sessions.filter(s => s.startedAt >= lo && s.startedAt < hi),
    [sessions, lo, hi]
  );

  const { totalMs, byTask, byProject, byCycle, byTag } = useMemo(() => {
    let total = 0;
    const taskMap = new Map();
    const projMap = new Map();
    const cycleMap = new Map();
    const tagMap = new Map();
    for (const s of inRange) {
      const ms = ttSessionMs(s);
      total += ms;
      const task = tasksById.get(s.taskId);
      taskMap.set(s.taskId, (taskMap.get(s.taskId) || 0) + ms);
      const pk = (task && task.projectId) || '__none__';
      projMap.set(pk, (projMap.get(pk) || 0) + ms);
      const ck = (task && task.cycleId) || '__none__';
      cycleMap.set(ck, (cycleMap.get(ck) || 0) + ms);
      for (const t of ((task && task.tags) || [])) tagMap.set(t, (tagMap.get(t) || 0) + ms);
    }
    const byTask = [...taskMap.entries()]
      .map(([id, ms]) => {
        const task = tasksById.get(id);
        return {
          id, ms,
          name: task && task.description ? task.description : '(no description)',
          muted: !(task && task.description),
          project: ttProjectById(projects, task && task.projectId),
        };
      })
      .sort((a, b) => b.ms - a.ms);
    const byProject = [...projMap.entries()]
      .map(([id, ms]) => {
        if (id === '__none__') return { id, name: 'No project', project: null, ms };
        const p = ttProjectById(projects, id);
        return { id, name: p ? p.name : '(deleted project)', project: p, ms };
      })
      .sort((a, b) => b.ms - a.ms);
    const byCycle = [...cycleMap.entries()]
      .map(([id, ms]) => {
        if (id === '__none__') return { id, name: 'No cycle', color: null, ms };
        const c = ttCycleById([...(cyclesById ? cyclesById.values() : [])], id);
        return { id, name: c ? c.name : '(deleted cycle)', color: c ? c.color : null, ms };
      })
      .sort((a, b) => b.ms - a.ms);
    const byTag = [...tagMap.entries()]
      .map(([tag, ms]) => ({ tag, ms }))
      .sort((a, b) => b.ms - a.ms);
    return { totalMs: total, byTask, byProject, byCycle, byTag };
  }, [inRange, tasksById, cyclesById, projects]);

  const secs = settings.listSeconds;
  const maxTask = byTask[0]?.ms || 1;
  const maxProj = byProject[0]?.ms || 1;
  const maxCycle = byCycle[0]?.ms || 1;
  const maxTag = byTag[0]?.ms || 1;
  const taskCount = byTask.length;

  return (
    <div className="trk-summary" data-screen-label="Time tracker summary">
      <div className="trk-sum-toolbar">
        <div className="trk-cal-modes">
          {TT_SUM_RANGES.map(r => (
            <button
              key={r.id}
              className={`trk-view-tab ${range === r.id ? 'is-active' : ''}`}
              onClick={() => setRange(r.id)}
            >{r.label}</button>
          ))}
        </div>
        {range === 'custom' && (
          <div className="trk-sum-custom">
            <input
              type="date" className="lh-input trk-filter-date"
              value={from ? ttDateInputVal(from) : ''}
              onChange={e => setFrom(e.target.value ? ttParseDateTime(e.target.value, '00:00') : null)}
            />
            <span className="trk-filter-dash">–</span>
            <input
              type="date" className="lh-input trk-filter-date"
              value={to ? ttDateInputVal(to) : ''}
              onChange={e => setTo(e.target.value ? ttParseDateTime(e.target.value, '00:00') : null)}
            />
          </div>
        )}
        <div style={{ flex: 1 }}></div>
        <div className="trk-sum-total">
          <span className="l">Total</span>
          <span className="v">{ttFmtDuration(totalMs, { seconds: secs })}</span>
          <span className="l">· {taskCount} {taskCount === 1 ? 'task' : 'tasks'}, {inRange.length} {inRange.length === 1 ? 'session' : 'sessions'}</span>
        </div>
      </div>

      {inRange.length === 0 ? (
        <div className="lh-empty trk-empty">
          <Icon name="bar_chart"></Icon>
          <div className="title">Nothing in this range</div>
          <div className="sub">Track some time or widen the date range.</div>
        </div>
      ) : (
        <>
          <section className="trk-sum-section trk-sum-tasks">
            <h3><Icon name="task_alt"></Icon>By task</h3>
            <div className="trk-sum-rows">
              {byTask.map(row => (
                <div className="trk-sum-row" key={row.id}>
                  <div className="trk-sum-row-label">
                    <TtProjectDot project={row.project}></TtProjectDot>
                    <span className={row.muted ? 'is-muted' : ''}>{row.name}</span>
                  </div>
                  <div className="trk-sum-bar-track">
                    <div
                      className="trk-sum-bar"
                      style={{
                        width: `${Math.max((row.ms / maxTask) * 100, 1.5)}%`,
                        background: row.project ? row.project.color : 'var(--color-primary)',
                      }}
                    ></div>
                  </div>
                  <div className="trk-sum-row-val">{ttFmtDuration(row.ms, { seconds: secs })}</div>
                  <div className="trk-sum-row-pct">{totalMs ? Math.round((row.ms / totalMs) * 100) : 0}%</div>
                </div>
              ))}
            </div>
          </section>

          <div className="trk-sum-grid">
            <section className="trk-sum-section">
              <h3><Icon name="folder"></Icon>By project</h3>
              <div className="trk-sum-rows">
                {byProject.map(row => (
                  <div className="trk-sum-row" key={row.id}>
                    <div className="trk-sum-row-label">
                      <TtProjectDot project={row.project}></TtProjectDot>
                      <span className={row.project ? '' : 'is-muted'}>{row.name}</span>
                    </div>
                    <div className="trk-sum-bar-track">
                      <div
                        className="trk-sum-bar"
                        style={{
                          width: `${Math.max((row.ms / maxProj) * 100, 1.5)}%`,
                          background: row.project ? row.project.color : 'var(--text-faint)',
                        }}
                      ></div>
                    </div>
                    <div className="trk-sum-row-val">{ttFmtDuration(row.ms, { seconds: secs })}</div>
                    <div className="trk-sum-row-pct">{totalMs ? Math.round((row.ms / totalMs) * 100) : 0}%</div>
                  </div>
                ))}
              </div>
            </section>

            <section className="trk-sum-section">
              <h3><Icon name="cycle"></Icon>By cycle</h3>
              <div className="trk-sum-rows">
                {byCycle.map(row => (
                  <div className="trk-sum-row" key={row.id}>
                    <div className="trk-sum-row-label">
                      <span className="trk-proj-dot" style={{ background: row.color || 'var(--text-faint)', width: 8, height: 8 }}></span>
                      <span className={row.color ? '' : 'is-muted'}>{row.name}</span>
                    </div>
                    <div className="trk-sum-bar-track">
                      <div
                        className="trk-sum-bar"
                        style={{
                          width: `${Math.max((row.ms / maxCycle) * 100, 1.5)}%`,
                          background: row.color || 'var(--text-faint)',
                        }}
                      ></div>
                    </div>
                    <div className="trk-sum-row-val">{ttFmtDuration(row.ms, { seconds: secs })}</div>
                    <div className="trk-sum-row-pct">{totalMs ? Math.round((row.ms / totalMs) * 100) : 0}%</div>
                  </div>
                ))}
              </div>
            </section>

            <section className="trk-sum-section">
              <h3><Icon name="tag"></Icon>By tag</h3>
              {byTag.length === 0 ? (
                <div className="trk-sum-none">No tagged tasks in this range.</div>
              ) : (
                <div className="trk-sum-rows">
                  {byTag.map(row => (
                    <div className="trk-sum-row" key={row.tag}>
                      <div className="trk-sum-row-label">
                        <Icon name="tag" className="trk-sum-tag-icon"></Icon>
                        <span>{row.tag}</span>
                      </div>
                      <div className="trk-sum-bar-track">
                        <div
                          className="trk-sum-bar is-tag"
                          style={{ width: `${Math.max((row.ms / maxTag) * 100, 1.5)}%` }}
                        ></div>
                      </div>
                      <div className="trk-sum-row-val">{ttFmtDuration(row.ms, { seconds: secs })}</div>
                      <div className="trk-sum-row-pct">{totalMs ? Math.round((row.ms / totalMs) * 100) : 0}%</div>
                    </div>
                  ))}
                </div>
              )}
            </section>
          </div>
        </>
      )}
    </div>
  );
}

window.TtSummaryView = TtSummaryView;
