// pages.jsx — Тиждень, Об'єкти, Команда

// ============ ТИЖДЕНЬ ============
function WeekPage({ tasks, onOpenTask, onToggle }) {
  const [filter, setFilter] = React.useState("all"); // all | mine
  const weekDays = window.WEEK_DAYS;
  const team = window.DATA.TEAM;
  const me = team[0]; // ОК
  const filtered = filter === "mine" ? tasks.filter(t => t.assignee === me.id) : tasks;

  // Групуємо по днях
  const byDay = {};
  weekDays.forEach(d => byDay[d.day] = []);
  filtered.forEach(t => { if (byDay[t.day]) byDay[t.day].push(t); });

  const myCount = tasks.filter(t => t.assignee === me.id).length;
  const totalCount = tasks.length;
  const doneCount = filtered.filter(t => t.status === "done").length;
  const lateCount = filtered.filter(t => t.status === "late").length;

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Тиждень</h1>
        <div className="page-sub">
          <span>тиждень 22 · 25–29 травня 2026</span>
          <span className="dot"></span>
          <span>{filtered.length} {window.plural(filtered.length, "задача", "задачі", "задач")}</span>
          {doneCount > 0 && <><span className="dot"></span><span>{doneCount} виконано</span></>}
          {lateCount > 0 && <><span className="dot"></span><span style={{color: "var(--late)"}}>{lateCount} прострочено</span></>}
        </div>
      </div>

      {/* Фільтр */}
      <div className="filter-row">
        <div className="filter-pill" role="tablist">
          <button
            className={`filter-pill-item ${filter === "all" ? "is-active" : ""}`}
            onClick={() => setFilter("all")}
            role="tab" aria-selected={filter === "all"}
          >
            <span className="filter-pill-label">Уся команда</span>
            <span className="filter-pill-count">{totalCount}</span>
          </button>
          <button
            className={`filter-pill-item ${filter === "mine" ? "is-active" : ""}`}
            onClick={() => setFilter("mine")}
            role="tab" aria-selected={filter === "mine"}
          >
            <span className="av av-me">{me.initials}</span>
            <span className="filter-pill-label">Тільки мої</span>
            <span className="filter-pill-count">{myCount}</span>
          </button>
        </div>
      </div>

      {weekDays.map(d => {
        const dayTasks = byDay[d.day] || [];
        return (
          <section key={d.day} className={`day-section ${d.isToday ? "is-today" : ""} ${d.isPast ? "is-past" : ""} ${dayTasks.length === 0 ? "is-empty" : ""}`}>
            <div className="day-section-head">
              <div className="day-section-title">
                <span className="day-section-num">{d.day}</span>
                <span className="day-section-month">травня</span>
                <span className="day-section-name">{d.name}</span>
                {d.isToday && <span className="task-status is-live">Сьогодні</span>}
              </div>
              <span className="day-section-count">
                {dayTasks.length > 0
                  ? `${dayTasks.length} ${window.plural(dayTasks.length, "задача", "задачі", "задач")}`
                  : "—"}
              </span>
            </div>
            {dayTasks.length > 0 && (
              <div className="task-list">
                {dayTasks.map(t => <TaskRow key={t.id} task={t} onOpen={onOpenTask} onToggle={onToggle} />)}
              </div>
            )}
          </section>
        );
      })}
    </div>
  );
}

// ============ ОБ'ЄКТИ ============
function ObjectsPage({ tasks, onOpenTask, onToggle, setPage, onOpenProject }) {
  const objects = window.DATA.OBJECTS;
  const stages = window.DATA.STAGES;
  const [openObj, setOpenObj] = React.useState(null);
  const [pickerOpen, setPickerOpen] = React.useState(false);
  const [creating, setCreating] = React.useState(null);

  // загальна статистика
  const activeCount = objects.filter(o => o.activeStage !== "supervision").length;
  const supervisionCount = objects.filter(o => o.activeStage === "supervision").length;

  return (
    <div className="page">
      <div className="page-head">
        <div style={{display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16}}>
          <div>
            <h1 className="page-h1">Об'єкти</h1>
            <div className="page-sub">
              <span>{objects.length} в портфелі</span>
              <span className="dot"></span>
              <span>{activeCount} {window.plural(activeCount, "у проєктуванні", "у проєктуванні", "у проєктуванні")}</span>
              <span className="dot"></span>
              <span>{supervisionCount} на авт. нагляді</span>
            </div>
          </div>
          <button className="btn btn-primary" onClick={() => setPickerOpen(true)} style={{flexShrink: 0}}>
            <window.Icon.Plus /> Новий об'єкт
          </button>
        </div>
      </div>

      <div className="obj-stack">
        {objects.map(o => (
          <ObjectCard
            key={o.id}
            obj={o}
            tasks={tasks}
            stages={stages}
            isOpen={openObj === o.id}
            onToggle={() => setOpenObj(openObj === o.id ? null : o.id)}
            onOpenTask={onOpenTask}
            onToggleTask={onToggle}
            onOpenProject={onOpenProject}
          />
        ))}
      </div>

      {pickerOpen && (
        <window.ProjectTemplatePicker
          onClose={() => setPickerOpen(false)}
          onPick={(t) => { setPickerOpen(false); setCreating(t); }}
        />
      )}
      {creating && (
        <window.CreateProjectModal
          template={creating}
          onClose={() => setCreating(null)}
          onCreated={() => { setCreating(null); }}
        />
      )}
    </div>
  );
}

function ObjectCard({ obj, tasks, stages, isOpen, onToggle, onOpenTask, onToggleTask, onOpenProject }) {
  const objTasks = tasks.filter(t => t.obj === obj.id);
  const activeStageData = window.getStage(obj.activeStage);
  const correctionStages = window.DATA.CORRECTION_STAGES;
  const [ccOpen, setCcOpen] = React.useState(false);

  const handleCcConfirm = ({ grade, scope, basis, added, removed }) => {
    const newHistory = [...(obj.gradeHistory || []),
      { value: grade, kind: "calculated", date: window.SYS_DATE, by: "ok", basis }];
    const newTasks = added.map(tt => ({
      id: "t-" + Math.random().toString(36).slice(2, 8),
      title: tt.title, obj: obj.id, stage: "expertise",
      assignee: tt.assigneeRole === "gip" ? (obj.team?.[0] || null) : null,
      section: tt.section, est: tt.estDays + " дн", status: "todo",
      templateTaskId: tt.id, deadlineOffset: tt.deadlineOffset, subs: [],
    }));
    const plan = { ...(obj.plan || {}) };
    plan.expertise = Math.max(0, (plan.expertise || 0) + added.length - removed.length);
    if (window.__erpStore && window.__erpStore.updateObject) {
      window.__erpStore.updateObject(obj.id, {
        grade, expertiseScope: scope, gradeKind: "calculated", gradeHistory: newHistory, plan,
      }, newTasks);
    }
    setCcOpen(false);
  };

  // Загальний прогрес
  const totalDone = objTasks.filter(t => t.status === "done").length;
  const totalPlanned = Object.values(obj.plan || {}).reduce((s, n) => s + n, 0);
  const progressPct = totalPlanned > 0 ? Math.round((totalDone / totalPlanned) * 100) : 0;

  // Чи є коригування (план або задачі)
  const hasCorrections = correctionStages.some(s => {
    const planned = obj.plan?.[s.id] || 0;
    const hasTasks = objTasks.some(t => t.stage === s.id);
    return planned > 0 || hasTasks;
  });

  const buildInfo = (stage) => {
    const list = objTasks.filter(t => t.stage === stage.id);
    const done = list.filter(t => t.status === "done").length;
    const live = list.filter(t => t.status === "live").length;
    const late = list.filter(t => t.status === "late").length;
    const total = list.length;
    const planned = obj.plan?.[stage.id] || 0;
    const isCompleted = obj.completedStages?.includes(stage.id) || (planned > 0 && done === planned);
    const isActive = stage.id === obj.activeStage;
    const isSkipped = planned === 0 && !isCompleted && !isActive;
    return { stage, list, done, live, late, total, planned, isCompleted, isActive, isSkipped };
  };

  const mainStageInfo = stages.map(buildInfo);
  const correctionStageInfo = correctionStages.map(buildInfo);

  const stageTasks = isOpen
    ? objTasks.filter(t => t.stage === obj.activeStage)
    : [];

  return (
    <div className={`obj-card ${isOpen ? "is-open" : ""}`}>
      {/* Header */}
      <div className="obj-card-head" onClick={onToggle}>
        <div className="obj-card-id">
          <div className="obj-code">{obj.code}</div>
          <span className="obj-grade">{obj.grade}</span>
        </div>
        <div className="obj-card-main">
          <div className="obj-card-name">{obj.name}</div>
          <div className="obj-card-meta">
            <span>{obj.client}</span>
            <span className="dot"></span>
            <span>{obj.address}</span>
            <span className="dot"></span>
            <span>{obj.contract}</span>
          </div>
        </div>
        <div className="obj-card-now">
          <div className="obj-card-now-label">Зараз</div>
          <div className="obj-card-now-stage">{activeStageData?.name}</div>
          <div className="obj-card-deadline">до {obj.deadline}</div>
        </div>
        {onOpenProject && (
          <button
            className="btn btn-primary obj-open-btn"
            onClick={(e) => { e.stopPropagation(); onOpenProject(obj.id); }}
            title="Відкрити робочий простір об'єкта"
          >
            Відкрити →
          </button>
        )}
        <button className="obj-card-toggle" aria-label={isOpen ? "Згорнути" : "Розгорнути"}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{transform: isOpen ? "rotate(180deg)" : "none", transition: "transform 0.2s"}}>
            <path d="M3 5L7 9L11 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>

      {/* Загальний прогрес */}
      <div className="obj-overall">
        <div className="obj-overall-bar">
          <div className="obj-overall-fill" style={{width: progressPct + "%"}}></div>
        </div>
        <div className="obj-overall-meta">
          <span>{totalDone} з {totalPlanned} задач</span>
          <span>{progressPct}%</span>
        </div>
      </div>

      {/* Основна стрічка етапів */}
      <div className="stage-strip-wrap">
        <div className="stage-strip-label">Основний цикл</div>
        <div className="stage-strip">
          {mainStageInfo.map((info, idx) => (
            <React.Fragment key={info.stage.id}>
              {idx > 0 && <div className="stage-strip-sep"></div>}
              <StageChip info={info} expertiseScope={obj.expertiseScope} />
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* Коригування — показуємо тільки якщо є */}
      {hasCorrections && (
        <div className="stage-strip-wrap is-correction">
          <div className="stage-strip-label">Коригування</div>
          <div className="stage-strip">
            {correctionStageInfo.map((info, idx) => (
              <React.Fragment key={info.stage.id}>
                {idx > 0 && <div className="stage-strip-sep"></div>}
                <StageChip info={info} />
              </React.Fragment>
            ))}
          </div>
        </div>
      )}

      {/* Розгорнутий блок — клас наслідків + задачі активного етапу */}
      {isOpen && (
        <div className="obj-expand">
          <window.ConsequenceClassPanel obj={obj} onRefine={() => setCcOpen(true)} />
          <div className="obj-expand-head">
            <span className="drawer-section-h" style={{margin: 0}}>Задачі етапу «{activeStageData?.name}»</span>
            <span style={{marginLeft: "auto", fontSize: 12, color: "var(--ink-3)"}}>{stageTasks.length} {window.plural(stageTasks.length, "задача", "задачі", "задач")}</span>
          </div>
          {stageTasks.length === 0
            ? <div className="empty" style={{padding: "20px 0"}}>На цьому етапі задач ще не створено.</div>
            : <div className="task-list">
                {stageTasks.map(t => <TaskRow key={t.id} task={t} onOpen={onOpenTask} onToggle={onToggleTask} />)}
              </div>
          }
        </div>
      )}

      {ccOpen && (
        <window.ConsequenceClassModal
          obj={obj}
          tasks={tasks}
          onClose={() => setCcOpen(false)}
          onConfirm={handleCcConfirm}
        />
      )}
    </div>
  );
}

function StageChip({ info, expertiseScope }) {
  const { stage, done, live, late, planned, isCompleted, isActive, isSkipped } = info;
  const isEstimateOnly = stage.id === "expertise" && expertiseScope === "estimate";
  const isStrengthOnly = stage.id === "expertise" && expertiseScope === "strength";
  return (
    <div className={`stage-chip ${isActive ? "is-active" : ""} ${isCompleted ? "is-completed" : ""} ${isSkipped ? "is-skipped" : ""} ${late > 0 ? "has-late" : ""}`}>
      <div className="stage-chip-head">
        <span className="stage-chip-name">{stage.short}</span>
        {isCompleted && <StageIcon kind="done" />}
        {isActive && !isCompleted && <span className="stage-chip-dot"></span>}
      </div>
      <div className="stage-chip-progress">
        {planned > 0
          ? <span>{done}<span className="stage-chip-of">/{planned}</span></span>
          : <span className="stage-chip-empty">—</span>
        }
      </div>
      {isEstimateOnly && <div className="stage-chip-note">тільки кошторис</div>}
      {isStrengthOnly && <div className="stage-chip-note">МОС + кошторис</div>}
      {late > 0 && <div className="stage-chip-note is-late">{late} прострочено</div>}
      {live > 0 && <div className="stage-chip-note is-live">{live} у роботі</div>}
    </div>
  );
}

function StageIcon({ kind }) {
  if (kind === "done") return (
    <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
      <path d="M2.5 6.5L4.8 9L9.5 3.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
  return null;
}

// ============ АДМІНІСТРАЦІЯ ============
function AdminPage({ tasks, onOpenTask, onToggle }) {
  const adminTasks = tasks.filter(t => !t.obj);
  const active = adminTasks.filter(t => t.status !== "done");
  const done = adminTasks.filter(t => t.status === "done");

  // Сортування по даті
  const sorted = [...active].sort((a, b) => a.day.localeCompare(b.day));

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Адміністративні</h1>
        <div className="page-sub">
          <span>задачі поза проєктами</span>
          <span className="dot"></span>
          <span>{active.length} {window.plural(active.length, "активна", "активні", "активних")}</span>
          {done.length > 0 && <><span className="dot"></span><span>{done.length} виконано</span></>}
        </div>
      </div>

      <section className="section">
        <div className="section-head">
          <h2 className="section-h2">Найближчі</h2>
          <span className="section-sub">офіс · фінанси · HR</span>
        </div>
        {sorted.length === 0
          ? <div className="empty">Адміністративних задач немає.</div>
          : <div className="task-list">
              {sorted.map(t => (
                <TaskRow
                  key={t.id} task={t}
                  onOpen={onOpenTask} onToggle={onToggle}
                  dateLabel={window.dateLabel(t.day, window.TODAY.day, false)}
                />
              ))}
            </div>
        }
      </section>

      {done.length > 0 && (
        <section className="section">
          <div className="section-head">
            <h2 className="section-h2">Виконано</h2>
            <span className="section-sub">{done.length}</span>
          </div>
          <div className="task-list">
            {done.map(t => (
              <TaskRow
                key={t.id} task={t}
                onOpen={onOpenTask} onToggle={onToggle}
              />
            ))}
          </div>
        </section>
      )}
    </div>
  );
}

// ============ КОМАНДА ============
function TeamPage({ tasks }) {
  const team = window.DATA.TEAM;
  const [sort, setSort] = React.useState("role"); // role | name | load

  const sorted = React.useMemo(() => {
    const copy = [...team];
    if (sort === "name") copy.sort((a, b) => a.name.localeCompare(b.name, "uk"));
    else if (sort === "load") copy.sort((a, b) => b.load - a.load);
    // role — default order
    return copy;
  }, [team, sort]);

  const totalActive = tasks.filter(t => t.status !== "done").length;

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Команда</h1>
        <div className="page-sub">
          <span>{team.length} {window.plural(team.length, "людина", "людини", "людей")} у штаті</span>
          <span className="dot"></span>
          <span>{totalActive} активних задач</span>
        </div>
      </div>

      <div className="team-controls">
        <div className="team-sort">
          <span style={{fontSize: 12, color: "var(--ink-3)"}}>Сортувати:</span>
          <button className={`team-sort-btn ${sort === "role" ? "is-active" : ""}`} onClick={() => setSort("role")}>За роллю</button>
          <button className={`team-sort-btn ${sort === "name" ? "is-active" : ""}`} onClick={() => setSort("name")}>За прізвищем</button>
          <button className={`team-sort-btn ${sort === "load" ? "is-active" : ""}`} onClick={() => setSort("load")}>За завантаженням</button>
        </div>
      </div>

      <div className="team-table">
        <div className="team-table-head">
          <div className="team-col-avatar"></div>
          <div className="team-col-name">Працівник</div>
          <div className="team-col-tasks">Активні задачі</div>
          <div className="team-col-load">Завантаження</div>
          <div className="team-col-phone">Телефон</div>
          <div className="team-col-email">Email</div>
        </div>
        {sorted.map(p => {
          const myActive = tasks.filter(t => t.assignee === p.id && t.status !== "done").length;
          const myLate = tasks.filter(t => t.assignee === p.id && t.status === "late").length;
          return (
            <div key={p.id} className="team-row">
              <div className="team-col-avatar">
                <div className="team-avatar">{p.initials}</div>
              </div>
              <div className="team-col-name">
                <div className="team-name">{p.name}</div>
                <div className="team-role">{p.role}</div>
              </div>
              <div className="team-col-tasks">
                <span className="team-task-count">{myActive}</span>
                {myLate > 0 && <span className="team-late">· {myLate} прострочено</span>}
              </div>
              <div className="team-col-load">
                <div className="load-bar">
                  <div
                    className={`load-fill ${p.load >= 90 ? "is-high" : ""}`}
                    style={{width: p.load + "%"}}
                  ></div>
                </div>
                <span className={`load-val ${p.load >= 90 ? "is-high" : ""}`}>{p.load}%</span>
              </div>
              <div className="team-col-phone">{p.phone}</div>
              <div className="team-col-email">
                <a href={`mailto:${p.email}`} className="team-email-link" onClick={(e) => e.stopPropagation()}>{p.email}</a>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.WeekPage = WeekPage;
window.ObjectsPage = ObjectsPage;
window.AdminPage = AdminPage;
window.TeamPage = TeamPage;
