// phase2-pages.jsx — KPI/1:1 · Підрядники · Шаблони задач

// ============ KPI ТА 1:1 ============
function KpiPage({ role }) {
  const team = window.DATA.TEAM;
  const oneOnOnes = window.ONE_ON_ONES;
  const [openPerson, setOpenPerson] = React.useState(null);
  const [tab, setTab] = React.useState("kpi");

  const upcoming = oneOnOnes.filter(o => o.status === "scheduled");
  const past = oneOnOnes.filter(o => o.status === "done");

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">KPI та 1:1 розмови</h1>
        <div className="page-sub">
          <span>цілі команди, оцінка ефективності, регулярні розмови</span>
          <span className="dot"></span>
          <span>квартал Q2 2026</span>
        </div>
      </div>

      <div className="toolbar">
        <div className="filter-pill" role="tablist">
          <button className={`filter-pill-item ${tab === "kpi" ? "is-active" : ""}`} onClick={() => setTab("kpi")}>
            KPI команди <span className="filter-pill-count">{team.length}</span>
          </button>
          <button className={`filter-pill-item ${tab === "1on1" ? "is-active" : ""}`} onClick={() => setTab("1on1")}>
            1:1 розмови <span className="filter-pill-count">{upcoming.length}</span>
          </button>
        </div>
      </div>

      {tab === "kpi" && (
        <div className="kpi-stack">
          {team.map(p => {
            const goals = window.KPI_GOALS[p.id] || [];
            const onTrack = goals.filter(g => g.trend === "on_track" || g.trend === "exceeding").length;
            return (
              <div key={p.id} className="kpi-person-card">
                <div className="kpi-person-head" onClick={() => setOpenPerson(openPerson === p.id ? null : p.id)}>
                  <div className="team-avatar" style={{width: 40, height: 40, fontSize: 13}}>{p.initials}</div>
                  <div style={{flex: 1, minWidth: 0}}>
                    <div className="cell-name" style={{fontSize: 15}}>{p.name}</div>
                    <div className="cell-sub">{p.role}</div>
                  </div>
                  <div className="kpi-person-summary">
                    {goals.length > 0 ? (
                      <>
                        <div className="kpi-person-num">
                          <span style={{color: onTrack === goals.length ? "var(--c-green-deep)" : "var(--ink)"}}>{onTrack}</span>
                          <span style={{color: "var(--ink-3)"}}>/{goals.length}</span>
                        </div>
                        <div className="kpi-person-label">у графіку</div>
                      </>
                    ) : (
                      <div style={{fontSize: 12, color: "var(--ink-4)"}}>немає KPI</div>
                    )}
                  </div>
                  <button className="obj-card-toggle">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{transform: openPerson === p.id ? "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>
                {openPerson === p.id && goals.length > 0 && (
                  <div className="kpi-goals-list">
                    {goals.map(g => <KpiGoalRow key={g.id} goal={g} />)}
                    <div className="kpi-actions">
                      <button className="btn">Редагувати цілі</button>
                      <button className="btn btn-primary">Запланувати 1:1</button>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {tab === "1on1" && (
        <>
          {upcoming.length > 0 && (
            <section className="section">
              <div className="section-head">
                <h2 className="section-h2">Заплановано</h2>
                <span className="section-sub">{upcoming.length}</span>
                <button className="btn btn-primary" style={{marginLeft: "auto", padding: "4px 12px", fontSize: 12}}>
                  <window.Icon.Plus /> Запланувати
                </button>
              </div>
              <div className="oneonone-list">
                {upcoming.map(o => <OneOnOneRow key={o.id} oneon={o} />)}
              </div>
            </section>
          )}
          <section className="section">
            <div className="section-head">
              <h2 className="section-h2">Минулі розмови</h2>
              <span className="section-sub">{past.length}</span>
            </div>
            <div className="oneonone-list">
              {past.map(o => <OneOnOneRow key={o.id} oneon={o} />)}
            </div>
          </section>
        </>
      )}
    </div>
  );
}

function KpiGoalRow({ goal }) {
  const trend = window.KPI_TREND_LABELS[goal.trend];
  const pct = goal.inverse
    ? Math.max(0, Math.min(100, (1 - (goal.current - goal.target) / goal.target) * 100))
    : Math.max(0, Math.min(100, goal.current / goal.target * 100));

  const formatVal = (v) => {
    if (goal.unit === "₴") return window.formatMoney(v) + " ₴";
    return v.toLocaleString("uk-UA") + goal.unit;
  };

  return (
    <div className="kpi-goal-row">
      <div className="kpi-goal-info">
        <div className="kpi-goal-title">{goal.title}</div>
        <div className="kpi-goal-vals">
          <span className="kpi-goal-current">{formatVal(goal.current)}</span>
          <span className="kpi-goal-target">з {formatVal(goal.target)}</span>
        </div>
      </div>
      <div className="kpi-goal-bar">
        <div className="load-bar-track">
          <div
            className={`load-bar-fill ${goal.trend === "behind" ? "is-high" : ""}`}
            style={{
              width: pct + "%",
              background: goal.trend === "exceeding" || goal.trend === "on_track" ? "var(--c-green-deep)"
                : goal.trend === "at_risk" ? "var(--c-orange, #d4a373)"
                : "var(--late)"
            }}
          ></div>
        </div>
      </div>
      <span className={`status-tag tone-${trend.tone}`}>{trend.label}</span>
    </div>
  );
}

function OneOnOneRow({ oneon }) {
  const person = window.getTeam(oneon.who);
  const isUpcoming = oneon.status === "scheduled";

  return (
    <div className={`oneonone-row ${isUpcoming ? "is-upcoming" : ""}`}>
      <div className="team-avatar" style={{width: 36, height: 36, fontSize: 13}}>{person?.initials}</div>
      <div style={{flex: 1, minWidth: 0}}>
        <div className="cell-name">{person?.name}</div>
        <div className="cell-sub">
          {window.formatDate(oneon.date)} · {oneon.duration} хв · {oneon.topics.length} {window.plural(oneon.topics.length, "тема", "теми", "тем")}
        </div>
        {oneon.notes && (
          <div style={{fontSize: 12, color: "var(--ink-2)", marginTop: 8, lineHeight: 1.5, padding: "8px 10px", background: "var(--bg-sunken)", borderRadius: 6, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden"}}>
            {oneon.notes}
          </div>
        )}
      </div>
      <div style={{textAlign: "right", flexShrink: 0}}>
        {isUpcoming
          ? <span className="status-tag tone-neutral">заплановано</span>
          : <span className="status-tag tone-live">проведено</span>
        }
        {oneon.nextSteps.length > 0 && (
          <div style={{fontSize: 11, color: "var(--ink-3)", marginTop: 6}}>{oneon.nextSteps.length} наст. кроків</div>
        )}
      </div>
    </div>
  );
}

// ============ ПІДРЯДНИКИ ============
function SuppliersPage({ role }) {
  const suppliers = window.DATA.SUPPLIERS;
  const cats = window.SUPPLIER_CATEGORIES;
  const [filter, setFilter] = React.useState("all");
  const [openId, setOpenId] = React.useState(null);

  let shown = suppliers;
  if (filter !== "all") shown = shown.filter(s => s.category === filter);

  const totalPaid = suppliers.reduce((s, x) => s + x.totalPaid, 0);
  const activeCount = suppliers.reduce((s, x) => s + x.activeProjects, 0);

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Підрядники</h1>
        <div className="page-sub">
          <span>{suppliers.length} {window.plural(suppliers.length, "контрагент", "контрагенти", "контрагентів")}</span>
          <span className="dot"></span>
          <span>{activeCount} активних проєктів</span>
          <span className="dot"></span>
          <span>виплачено за весь час <b style={{color: "var(--ink)"}}>{window.formatMoney(totalPaid)} ₴</b></span>
        </div>
      </div>

      <div className="kpi-row" style={{gridTemplateColumns: "repeat(4, 1fr)"}}>
        <div className="kpi">
          <div className="kpi-label">Активних</div>
          <div className="kpi-value">{suppliers.filter(s => s.activeProjects > 0).length}</div>
          <div className="kpi-sub">зараз працюємо</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Високий рейтинг</div>
          <div className="kpi-value">{suppliers.filter(s => s.rating >= 4).length}</div>
          <div className="kpi-sub">4-5 зірок</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Категорій</div>
          <div className="kpi-value">{Object.keys(cats).length}</div>
          <div className="kpi-sub">типів послуг</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Сер. чек</div>
          <div className="kpi-value">{window.formatMoney(Math.round(suppliers.reduce((s,x) => s+x.avgCost, 0) / suppliers.length))} <span style={{fontSize: 14, color: "var(--ink-3)"}}>₴</span></div>
          <div className="kpi-sub">за одну послугу</div>
        </div>
      </div>

      <div className="toolbar">
        <div className="filter-pill" role="tablist">
          <button className={`filter-pill-item ${filter === "all" ? "is-active" : ""}`} onClick={() => setFilter("all")}>Усі</button>
          {Object.entries(cats).map(([id, c]) => (
            <button key={id} className={`filter-pill-item ${filter === id ? "is-active" : ""}`} onClick={() => setFilter(id)}>
              <span style={{fontSize: 13}}><window.Ico e={c.icon} /></span> {c.label}
            </button>
          ))}
        </div>
        <button className="btn btn-primary" style={{marginLeft: "auto"}}>
          <window.Icon.Plus /> Додати підрядника
        </button>
      </div>

      <table className="data-table">
        <thead>
          <tr>
            <th>Підрядник</th>
            <th>Категорія</th>
            <th>Рейтинг</th>
            <th className="num-col">Проєктів</th>
            <th className="num-col">Сер. чек</th>
            <th className="num-col">Загалом виплачено</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {shown.map(s => {
            const cat = cats[s.category];
            return (
              <tr key={s.id} className="is-clickable" onClick={() => setOpenId(s.id)}>
                <td>
                  <div style={{display: "flex", alignItems: "center", gap: 12}}>
                    <div className="supplier-avatar" style={{background: `${cat.color}20`, color: cat.color}}><window.Ico e={cat.icon} /></div>
                    <div>
                      <div className="cell-name">{s.name}</div>
                      <div className="cell-sub">з {window.formatDate(s.since)}</div>
                    </div>
                  </div>
                </td>
                <td><span className="empl-chip empl-staff" style={{background: `${cat.color}20`, color: cat.color}}>{cat.label}</span></td>
                <td>
                  <span style={{display: "flex", gap: 2}}>
                    {[1,2,3,4,5].map(n =>
                      <span key={n} className={`rating-star ${n <= s.rating ? "is-on" : ""}`} style={{fontSize: 13}}>★</span>
                    )}
                  </span>
                </td>
                <td className="num-col">
                  <span style={{fontWeight: 500}}>{s.completedProjects}</span>
                  {s.activeProjects > 0 && <span style={{color: "var(--c-green-deep)", fontSize: 11, marginLeft: 6, fontWeight: 600}}>+{s.activeProjects}</span>}
                </td>
                <td className="num-col">{window.formatMoney(s.avgCost)} ₴</td>
                <td className="num-col num-bold">{window.formatMoney(s.totalPaid)} ₴</td>
                <td>
                  <button className="btn btn-ghost" style={{padding: "4px 8px", fontSize: 12}}>Відкрити →</button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>

      {openId && <SupplierDrawer supplier={suppliers.find(s => s.id === openId)} onClose={() => setOpenId(null)} />}
    </div>
  );
}

function SupplierDrawer({ supplier, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const cat = window.SUPPLIER_CATEGORIES[supplier.category];

  return (
    <>
      <div className="drawer-overlay" onClick={onClose}></div>
      <aside className="drawer" style={{width: "min(680px, 95vw)"}}>
        <div className="drawer-head">
          <button className="drawer-close" onClick={onClose}><window.Icon.X /></button>
          <span className="empl-chip empl-staff" style={{background: `${cat.color}20`, color: cat.color}}>{cat.label}</span>
          <div style={{marginLeft: "auto", display: "flex", gap: 2}}>
            {[1,2,3,4,5].map(n =>
              <span key={n} className={`rating-star ${n <= supplier.rating ? "is-on" : ""}`}>★</span>
            )}
          </div>
        </div>
        <div className="drawer-body">
          <div style={{display: "flex", alignItems: "center", gap: 16, marginBottom: 20}}>
            <div className="supplier-avatar" style={{background: `${cat.color}20`, color: cat.color, width: 56, height: 56, fontSize: 26, borderRadius: 12}}><window.Ico e={cat.icon} /></div>
            <div>
              <h1 className="drawer-h1" style={{marginBottom: 4}}>{supplier.name}</h1>
              <div style={{fontSize: 13, color: "var(--ink-3)"}}>з {window.formatDate(supplier.since)}</div>
            </div>
          </div>

          <div className="kpi-row" style={{gridTemplateColumns: "repeat(3, 1fr)", marginBottom: 20}}>
            <div className="kpi" style={{padding: "12px 14px"}}>
              <div className="kpi-label">Завершено</div>
              <div className="kpi-value" style={{fontSize: 22}}>{supplier.completedProjects}</div>
            </div>
            <div className="kpi" style={{padding: "12px 14px"}}>
              <div className="kpi-label">Активних</div>
              <div className="kpi-value" style={{fontSize: 22, color: supplier.activeProjects > 0 ? "var(--c-green-deep)" : "var(--ink)"}}>{supplier.activeProjects}</div>
            </div>
            <div className="kpi" style={{padding: "12px 14px"}}>
              <div className="kpi-label">Загалом</div>
              <div className="kpi-value" style={{fontSize: 18}}>{window.formatMoney(supplier.totalPaid)} ₴</div>
            </div>
          </div>

          <div className="drawer-section">
            <div className="drawer-section-h">Реквізити</div>
            <dl className="info-grid">
              <div><dt>ЄДРПОУ / ІПН</dt><dd className="td-mono">{supplier.edrpou}</dd></div>
              <div><dt>Адреса</dt><dd>{supplier.address}</dd></div>
            </dl>
          </div>

          <div className="drawer-section">
            <div className="drawer-section-h">Контакти</div>
            <div style={{fontSize: 13, padding: "12px 14px", background: "var(--bg-sunken)", borderRadius: 8, color: "var(--ink-2)"}}>
              {supplier.contact}
            </div>
          </div>

          <div className="drawer-section">
            <div className="drawer-section-h">Спеціалізація</div>
            <div className="tag-list">
              {supplier.specialties.map((sp, i) => (
                <span key={i} className="tag-item">{sp}</span>
              ))}
            </div>
          </div>

          {supplier.note && (
            <div className="drawer-section">
              <div className="drawer-section-h">Нотатки про співпрацю</div>
              <div style={{fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55, padding: "12px 14px", background: "var(--bg-sunken)", borderRadius: 8}}>
                {supplier.note}
              </div>
            </div>
          )}
        </div>
        <div className="drawer-foot">
          <button className="btn btn-primary">Замовити послугу</button>
          <button className="btn">Історія замовлень</button>
        </div>
      </aside>
    </>
  );
}

// ============ ШАБЛОНИ ЗАДАЧ ============
function TaskTemplatesPage({ role }) {
  const templates = window.DATA.TASK_TEMPLATES;
  const cats = window.TEMPLATE_CATEGORIES;
  const [openId, setOpenId] = React.useState(null);

  return (
    <div className="page">
      <div className="page-head">
        <h1 className="page-h1">Шаблони задач</h1>
        <div className="page-sub">
          <span>{templates.length} {window.plural(templates.length, "шаблон", "шаблони", "шаблонів")}</span>
          <span className="dot"></span>
          <span>для нових об'єктів і регулярних процесів</span>
        </div>
      </div>

      <div className="hint-box">
        <b>Як це працює:</b> створюючи новий об'єкт, обираєш шаблон — і автоматично створюються
        всі типові задачі по етапах з оцінкою часу. Економить 1-2 дні роботи на старті проєкту.
      </div>

      <div className="template-grid">
        {templates.map(t => (
          <div key={t.id} className="template-card" onClick={() => setOpenId(t.id)}>
            <div className="template-card-head">
              <div className="template-icon"><window.Ico e={t.icon} /></div>
              <span className="empl-chip empl-staff">{cats[t.category]}</span>
            </div>
            <div className="template-name">{t.name}</div>
            <div className="template-desc">{t.description}</div>
            <div className="template-stats">
              <div><b>{t.stages.reduce((s, st) => s + st.tasks.length, 0)}</b><span>задач</span></div>
              <div><b>{t.stages.length}</b><span>{window.plural(t.stages.length, "етап", "етапи", "етапів")}</span></div>
              <div><b>{t.estimatedDays}</b><span>{window.plural(t.estimatedDays, "день", "дні", "днів")}</span></div>
            </div>
            <div className="template-foot">
              <button className="btn">Переглянути</button>
              <button className="btn btn-primary" style={{flex: 1}}>Застосувати →</button>
            </div>
          </div>
        ))}
        <button className="template-add">
          <window.Icon.Plus />
          <span>Створити шаблон</span>
        </button>
      </div>

      {openId && <TemplateModal template={templates.find(t => t.id === openId)} onClose={() => setOpenId(null)} />}
    </div>
  );
}

function TemplateModal({ template, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const totalTasks = template.stages.reduce((s, st) => s + st.tasks.length, 0);

  return (
    <>
      <div className="drawer-overlay" onClick={onClose}></div>
      <div className="report-modal">
        <div className="report-toolbar">
          <button className="drawer-close" onClick={onClose}><window.Icon.X /></button>
          <div className="template-icon" style={{width: 32, height: 32, fontSize: 16}}><window.Ico e={template.icon} /></div>
          <div>
            <div style={{fontSize: 14, fontWeight: 600}}>{template.name}</div>
            <div style={{fontSize: 11.5, color: "var(--ink-3)"}}>{template.description}</div>
          </div>
          <div style={{marginLeft: "auto", display: "flex", gap: 8}}>
            <button className="btn">Дублювати</button>
            <button className="btn">Редагувати</button>
            <button className="btn btn-primary">Застосувати до об'єкта</button>
          </div>
        </div>
        <div style={{flex: 1, overflowY: "auto", padding: "24px 32px"}}>
          <div className="kpi-row" style={{gridTemplateColumns: "repeat(4, 1fr)"}}>
            <div className="kpi"><div className="kpi-label">Задач</div><div className="kpi-value">{totalTasks}</div></div>
            <div className="kpi"><div className="kpi-label">Етапів</div><div className="kpi-value">{template.stages.length}</div></div>
            <div className="kpi"><div className="kpi-label">Тривалість</div><div className="kpi-value">{template.estimatedDays}<span style={{fontSize: 14, color: "var(--ink-3)"}}>дн.</span></div></div>
            {template.objectGrade && <div className="kpi"><div className="kpi-label">Клас</div><div className="kpi-value">{template.objectGrade}</div></div>}
          </div>

          {template.stages.map((st, i) => (
            <section key={i} className="section">
              <div className="section-head">
                <h2 className="section-h2">{window.getStage(st.stage)?.name || st.stage}</h2>
                <span className="section-sub">{st.tasks.length} {window.plural(st.tasks.length, "задача", "задачі", "задач")}</span>
              </div>
              <table className="data-table compact-table">
                <thead>
                  <tr>
                    <th style={{width: 40}}>№</th>
                    <th>Задача</th>
                    <th>Розділ</th>
                    <th className="num-col">Оцінка</th>
                  </tr>
                </thead>
                <tbody>
                  {st.tasks.map((t, j) => (
                    <tr key={j}>
                      <td style={{color: "var(--ink-3)", fontFamily: "var(--font-mono)"}}>{j + 1}</td>
                      <td><div className="cell-name">{t.title}</div></td>
                      <td><span className="doc-type">{t.section}</span></td>
                      <td className="num-col">{t.est}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </section>
          ))}
        </div>
      </div>
    </>
  );
}

window.KpiPage = KpiPage;
window.SuppliersPage = SuppliersPage;
window.TaskTemplatesPage = TaskTemplatesPage;
