/* Wood OS — Apontamento de Horas (chão de fábrica) */
const { useState: useStateTS, useMemo: useMemoTS } = React;

/* ============================================================
   Helpers
   ============================================================ */
const TS_STATUS_META = {
  em_andamento: { label: "Em andamento", dot: "#10B981", bg: "rgba(16,185,129,0.14)", fg: "#34D399", pulse: true },
  finalizado:   { label: "Finalizado",   dot: "#38BDF8", bg: "rgba(56,189,248,0.12)", fg: "#38BDF8" },
  aprovado:     { label: "Aprovado",     dot: "#22C55E", bg: "rgba(34,197,94,0.14)",  fg: "#22C55E" },
  rejeitado:    { label: "Rejeitado",    dot: "#EF4444", bg: "rgba(239,68,68,0.12)",  fg: "#EF4444" },
};

const activityMeta = (id) => MOCK.timesheet.activities.find(a => a.id === id) || MOCK.timesheet.activities[0];

const WEEK_DAYS = [
  { id: "2026-05-11", label: "Seg", short: "11" },
  { id: "2026-05-12", label: "Ter", short: "12" },
  { id: "2026-05-13", label: "Qua", short: "13" },
  { id: "2026-05-14", label: "Qui", short: "14" },
  { id: "2026-05-15", label: "Sex", short: "15" },
];

/* ============================================================
   TimesheetPage
   ============================================================ */
const TimesheetPage = ({ navigate }) => {
  const [tab, setTab] = useStateTS("week");
  const [creating, setCreating] = useStateTS(false);
  const ts = MOCK.timesheet;

  const metrics = useMemoTS(() => {
    const today = "2026-05-15";
    const monthPrefix = "2026-05";
    const monthEntries = ts.entries.filter(e => e.date.startsWith(monthPrefix));
    const todayEntries = ts.entries.filter(e => e.date === today);
    const monthHours = monthEntries.reduce((s, e) => s + e.hours, 0);
    const todayHours = todayEntries.reduce((s, e) => s + e.hours, 0);
    const monthCost = monthEntries.reduce((s, e) => s + e.hours * (ts.hourlyRates[e.worker] || 50), 0);
    const avgRate = monthCost / (monthHours || 1);
    const active = todayEntries.filter(e => e.status === "em_andamento").length;
    return { monthHours, todayHours, monthCost, avgRate, active };
  }, [ts]);

  return (
    <>
      <PageHeader
        kicker="Produção"
        title="Apontamento de Horas"
        subtitle="Registro de tempo do chão de fábrica por colaborador, obra e atividade. Cada hora vira custo real da obra."
        actions={
          <>
            <button className="wood-btn wood-btn-secondary"><Icon name="external" size={13} /> Exportar folha</button>
            <button className="wood-btn wood-btn-primary" onClick={() => setCreating(true)}>
              <Icon name="plus" size={13} /> Bater ponto
            </button>
          </>
        }
      />

      {/* KPIs */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        <MetricCard icon="clock" label="Horas no mês" value={`${metrics.monthHours.toFixed(0)}h`} sub={`${ts.entries.length} apontamentos`} accent="amber" delay={0} />
        <MetricCard icon="activity" label="Horas hoje" value={`${metrics.todayHours.toFixed(1)}h`} sub={`${metrics.active} colaboradores ativos`} accent="success" delay={60} />
        <MetricCard icon="dollar" label="Custo de mão de obra" value={fmtBRL(metrics.monthCost)} sub="acumulado no mês" accent="info" delay={120} />
        <MetricCard icon="trend-up" label="Hora média" value={fmtBRL(metrics.avgRate)} sub="custo médio por hora" accent="warning" delay={180} />
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-1 mb-5" style={{ borderBottom: "1px solid var(--wood-border)" }}>
        {[
          { id: "week",    label: "Semana",       icon: "calendar" },
          { id: "workers", label: "Por colaborador", icon: "users" },
          { id: "projects", label: "Por obra",     icon: "hammer" },
          { id: "list",    label: "Lista de pontos",icon: "log" },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            className="px-3 py-2.5 flex items-center gap-1.5 text-sm"
            style={{
              background: "transparent", border: "none", cursor: "pointer",
              color: tab === t.id ? "var(--amber-bright)" : "var(--text-3)",
              fontWeight: tab === t.id ? 600 : 500,
              borderBottom: tab === t.id ? "2px solid var(--amber-bright)" : "2px solid transparent",
              marginBottom: -1, transition: "all 0.18s"
            }}>
            <Icon name={t.icon} size={13} /> {t.label}
          </button>
        ))}
      </div>

      {tab === "week"     && <WeekView entries={ts.entries} />}
      {tab === "workers"  && <ByWorker entries={ts.entries} rates={ts.hourlyRates} />}
      {tab === "projects" && <ByProject entries={ts.entries} rates={ts.hourlyRates} />}
      {tab === "list"     && <EntryList entries={ts.entries} />}

      <BaterPontoModal open={creating} onClose={() => setCreating(false)} />
    </>
  );
};

/* ============================================================
   WeekView — pulse de horas por dia da semana
   ============================================================ */
const WeekView = ({ entries }) => {
  const byDay = useMemoTS(() => {
    const m = {};
    WEEK_DAYS.forEach(d => { m[d.id] = []; });
    entries.forEach(e => { if (m[e.date] !== undefined) m[e.date].push(e); });
    return m;
  }, [entries]);

  const dayTotal = (id) => byDay[id].reduce((s, e) => s + e.hours, 0);
  const maxDay = Math.max(...WEEK_DAYS.map(d => dayTotal(d.id)));

  return (
    <>
      <div className="wood-card p-5 mb-5">
        <div className="flex items-center justify-between mb-5">
          <div>
            <div className="text-md font-semibold tracking-tight">Semana atual</div>
            <div className="text-xs text-3">11 — 15 de maio · {entries.filter(e => WEEK_DAYS.some(d => d.id === e.date)).length} apontamentos</div>
          </div>
          <div className="flex items-center gap-3 text-xs flex-wrap">
            {MOCK.timesheet.activities.map(a => (
              <span key={a.id} className="flex items-center gap-1.5">
                <span className="wood-dot" style={{ background: a.color }} /> {a.label}
              </span>
            ))}
          </div>
        </div>

        <div className="grid gap-3" style={{ gridTemplateColumns: `repeat(${WEEK_DAYS.length}, minmax(0, 1fr))` }}>
          {WEEK_DAYS.map(day => {
            const list = byDay[day.id];
            const total = dayTotal(day.id);
            const heightShare = maxDay ? (total / maxDay) : 0;
            const isToday = day.id === "2026-05-15";
            return (
              <div key={day.id} className="rounded-lg p-3 flex flex-col" style={{
                background: isToday ? "rgba(16,185,129,0.06)" : "rgba(0,0,0,0.18)",
                border: `1px solid ${isToday ? "rgba(16,185,129,0.3)" : "var(--wood-border-soft)"}`,
                minHeight: 260
              }}>
                <div className="flex items-center justify-between mb-3">
                  <div>
                    <div className="text-xs text-3 uppercase tracking-widest" style={{ fontWeight: 500 }}>{day.label}</div>
                    <div className="text-xl font-semibold tracking-tight" style={{ color: isToday ? "var(--amber-bright)" : "var(--text)", fontVariantNumeric: "tabular-nums" }}>{day.short}/05</div>
                  </div>
                  {isToday && <span className="wood-badge wood-badge-success" style={{ padding: "1px 6px", fontSize: 9.5 }}>HOJE</span>}
                </div>

                {/* Stack of activity bars */}
                <div className="flex-1 flex flex-col gap-1 mb-3">
                  {list.map(e => {
                    const meta = activityMeta(e.activity);
                    const w = Math.max(8, (e.hours / 10) * 100);
                    return (
                      <div key={e.id} className="px-2 py-1 rounded text-xs" style={{
                        background: `${meta.color}1f`,
                        borderLeft: `2px solid ${meta.color}`,
                        color: "var(--text-2)",
                        lineHeight: 1.2
                      }}>
                        <div className="flex items-center justify-between">
                          <span className="truncate" style={{ fontWeight: 500, maxWidth: 80 }}>{e.worker.split(" ")[0]}</span>
                          <span style={{ fontVariantNumeric: "tabular-nums", fontWeight: 600, color: meta.color }}>{e.hours.toFixed(1)}h</span>
                        </div>
                      </div>
                    );
                  })}
                  {list.length === 0 && <div className="text-xs text-4 italic text-center pt-4">sem apontamentos</div>}
                </div>

                <div className="pt-2" style={{ borderTop: "1px solid var(--wood-border-soft)" }}>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-3">Total</span>
                    <span className="text-sm font-semibold tracking-tight" style={{ fontVariantNumeric: "tabular-nums", color: total > 0 ? "var(--amber-bright)" : "var(--text-4)" }}>{total.toFixed(1)}h</span>
                  </div>
                  <div className="mt-1.5"><AnimatedProgress value={heightShare * 100} max={100} height={3} /></div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Live entries */}
      <div className="wood-card p-5">
        <div className="flex items-center justify-between mb-4">
          <div>
            <div className="text-md font-semibold tracking-tight">Em andamento agora</div>
            <div className="text-xs text-3">colaboradores com ponto aberto</div>
          </div>
          <span className="wood-badge wood-badge-success">
            <span className="wood-dot wood-dot-pulse" style={{ background: "var(--success)", color: "var(--success)" }} />
            {entries.filter(e => e.status === "em_andamento").length} ativos
          </span>
        </div>
        <div className="grid grid-cols-3 gap-3">
          {entries.filter(e => e.status === "em_andamento").map(e => {
            const meta = activityMeta(e.activity);
            return (
              <div key={e.id} className="px-4 py-3 rounded-lg" style={{ background: `${meta.color}10`, border: `1px solid ${meta.color}33` }}>
                <div className="flex items-center gap-2 mb-2">
                  <Avatar name={e.worker} size={26} />
                  <div className="min-w-0">
                    <div className="text-sm" style={{ fontWeight: 600 }}>{e.worker.split(" ")[0]}</div>
                  </div>
                  <div className="flex-1" />
                  <span className="wood-badge" style={{ background: `${meta.color}1f`, color: meta.color, padding: "1px 6px", fontSize: 9.5 }}>
                    <Icon name={meta.icon} size={10} /> {meta.label}
                  </span>
                </div>
                <div className="text-xs text-3 truncate mb-2">{e.projectName}</div>
                <div className="flex items-center justify-between">
                  <span className="text-xs text-4">Iniciado às {e.start}</span>
                  <span className="text-sm" style={{ color: meta.color, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{e.hours.toFixed(1)}h</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};

/* ============================================================
   ByWorker — ranking by hours
   ============================================================ */
const ByWorker = ({ entries, rates }) => {
  const list = useMemoTS(() => {
    const m = {};
    entries.forEach(e => {
      if (!m[e.worker]) m[e.worker] = { worker: e.worker, hours: 0, projects: new Set(), entries: 0 };
      m[e.worker].hours += e.hours;
      m[e.worker].projects.add(e.projectName);
      m[e.worker].entries += 1;
    });
    return Object.values(m)
      .map(w => ({ ...w, projects: w.projects.size, cost: w.hours * (rates[w.worker] || 50), rate: rates[w.worker] || 50 }))
      .sort((a, b) => b.hours - a.hours);
  }, [entries, rates]);

  const maxHours = list[0]?.hours || 0;

  return (
    <div className="wood-card" style={{ padding: 0, overflow: "hidden" }}>
      <table className="wood-table">
        <thead>
          <tr><th>Colaborador</th><th>Horas trabalhadas</th><th>Apontamentos</th><th>Obras</th><th>R$/hora</th><th>Custo total</th></tr>
        </thead>
        <tbody>
          {list.map((w, i) => (
            <tr key={w.worker} style={{ cursor: "pointer" }}>
              <td>
                <div className="flex items-center gap-3">
                  <div className="text-xs text-4 font-mono" style={{ width: 22 }}>#{String(i + 1).padStart(2, "0")}</div>
                  <Avatar name={w.worker} size={32} />
                  <span style={{ fontWeight: 600 }}>{w.worker}</span>
                </div>
              </td>
              <td>
                <div className="flex items-center gap-3">
                  <div style={{ flex: 1, maxWidth: 200 }}>
                    <AnimatedProgress value={w.hours} max={maxHours} height={5} />
                  </div>
                  <span className="text-sm" style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums", minWidth: 60, textAlign: "right" }}>{w.hours.toFixed(1)}h</span>
                </div>
              </td>
              <td className="text-sm text-3" style={{ fontVariantNumeric: "tabular-nums" }}>{w.entries}</td>
              <td className="text-sm text-3" style={{ fontVariantNumeric: "tabular-nums" }}>{w.projects}</td>
              <td className="text-sm text-3" style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(w.rate)}</td>
              <td className="text-sm" style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums", color: "var(--amber-bright)" }}>{fmtBRL(w.cost)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

/* ============================================================
   ByProject — hours consumed per project
   ============================================================ */
const ByProject = ({ entries, rates }) => {
  const list = useMemoTS(() => {
    const m = {};
    entries.forEach(e => {
      const k = e.projectId;
      if (!m[k]) m[k] = { projectId: e.projectId, projectName: e.projectName, hours: 0, workers: new Set(), byActivity: {}, cost: 0 };
      m[k].hours += e.hours;
      m[k].workers.add(e.worker);
      m[k].cost += e.hours * (rates[e.worker] || 50);
      m[k].byActivity[e.activity] = (m[k].byActivity[e.activity] || 0) + e.hours;
    });
    return Object.values(m).map(p => ({ ...p, workers: p.workers.size })).sort((a, b) => b.hours - a.hours);
  }, [entries, rates]);

  return (
    <div className="grid grid-cols-2 gap-4">
      {list.map(p => {
        const activities = Object.entries(p.byActivity);
        const totalAct = activities.reduce((s, [, h]) => s + h, 0);
        return (
          <div key={p.projectId} className="wood-card p-5">
            <div className="flex items-start justify-between mb-3">
              <div>
                <div className="text-md font-semibold tracking-tight">{p.projectName}</div>
                <div className="text-xs text-3 font-mono">{p.projectId}</div>
              </div>
              <div className="text-right">
                <div className="text-xs text-4 uppercase tracking-widest" style={{ fontWeight: 500 }}>HORAS</div>
                <div className="text-xl font-semibold tracking-tight wood-gradient-text" style={{ fontVariantNumeric: "tabular-nums" }}>{p.hours.toFixed(1)}h</div>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-2 mb-4">
              <div className="px-3 py-2 rounded-lg" style={{ background: "rgba(0,0,0,0.18)" }}>
                <div className="text-xs text-4 uppercase tracking-widest" style={{ fontWeight: 500 }}>EQUIPE</div>
                <div className="text-sm" style={{ fontWeight: 600 }}>{p.workers} {p.workers === 1 ? "colaborador" : "colaboradores"}</div>
              </div>
              <div className="px-3 py-2 rounded-lg" style={{ background: "rgba(16,185,129,0.06)", border: "1px solid rgba(16,185,129,0.2)" }}>
                <div className="text-xs text-4 uppercase tracking-widest" style={{ fontWeight: 500 }}>CUSTO MO</div>
                <div className="text-sm" style={{ fontWeight: 600, color: "var(--amber-bright)" }}>{fmtBRL(p.cost)}</div>
              </div>
            </div>

            <div className="text-xs text-3 uppercase tracking-widest mb-2" style={{ fontWeight: 500 }}>DISTRIBUIÇÃO POR ATIVIDADE</div>
            <div className="flex h-2 rounded-full overflow-hidden" style={{ background: "rgba(0,0,0,0.3)" }}>
              {activities.map(([act, h]) => {
                const meta = activityMeta(act);
                return <div key={act} style={{ flex: h / totalAct, background: meta.color, transition: "flex 0.6s var(--ease-out)" }} title={`${meta.label}: ${h.toFixed(1)}h`} />;
              })}
            </div>
            <div className="flex items-center gap-3 flex-wrap mt-2 text-xs">
              {activities.map(([act, h]) => {
                const meta = activityMeta(act);
                return (
                  <span key={act} className="flex items-center gap-1">
                    <span className="wood-dot" style={{ background: meta.color, width: 6, height: 6 }} />
                    <span className="text-3">{meta.label}</span>
                    <span style={{ color: meta.color, fontVariantNumeric: "tabular-nums", fontWeight: 600 }}>{h.toFixed(1)}h</span>
                  </span>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
};

/* ============================================================
   EntryList — table of all entries
   ============================================================ */
const EntryList = ({ entries }) => {
  const [filter, setFilter] = useStateTS("todos");
  const list = filter === "todos" ? entries : entries.filter(e => e.status === filter);

  return (
    <>
      <div className="wood-card p-3 mb-4 flex items-center gap-2 flex-wrap">
        <FilterChip active={filter === "todos"} onClick={() => setFilter("todos")} count={entries.length}>Todos</FilterChip>
        {Object.entries(TS_STATUS_META).map(([k, m]) => {
          const c = entries.filter(e => e.status === k).length;
          if (c === 0) return null;
          return <FilterChip key={k} active={filter === k} onClick={() => setFilter(k)} count={c}>{m.label}</FilterChip>;
        })}
      </div>

      <div className="wood-card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="wood-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Colaborador</th>
              <th>Obra</th>
              <th>Atividade</th>
              <th>Data</th>
              <th>Horário</th>
              <th>Horas</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {list.map(e => {
              const meta = activityMeta(e.activity);
              const st = TS_STATUS_META[e.status];
              return (
                <tr key={e.id} style={{ cursor: "pointer" }}>
                  <td className="font-mono text-xs text-3">{e.id}</td>
                  <td>
                    <div className="flex items-center gap-2">
                      <Avatar name={e.worker} size={24} />
                      <span className="text-sm">{e.worker}</span>
                    </div>
                  </td>
                  <td className="text-sm">{e.projectName}</td>
                  <td>
                    <span className="wood-badge" style={{ background: `${meta.color}14`, color: meta.color, padding: "2px 8px" }}>
                      <Icon name={meta.icon} size={10} /> {meta.label}
                    </span>
                  </td>
                  <td className="text-sm">{fmtDate(e.date)}</td>
                  <td className="text-sm" style={{ fontVariantNumeric: "tabular-nums" }}>
                    {e.start}{e.end ? ` — ${e.end}` : ` — em curso`}
                  </td>
                  <td className="text-sm" style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{e.hours.toFixed(1)}h</td>
                  <td>
                    <span className="wood-badge" style={{ background: st.bg, color: st.fg, padding: "2px 8px" }}>
                      {st.pulse && <span className="wood-dot wood-dot-pulse" style={{ background: st.dot, color: st.dot, width: 6, height: 6 }} />}
                      {!st.pulse && <span className="wood-dot" style={{ background: st.dot, width: 6, height: 6 }} />}
                      {st.label}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

/* ============================================================
   BaterPontoModal — form
   ============================================================ */
const BaterPontoModal = ({ open, onClose }) => {
  const [activity, setActivity] = useStateTS("montagem");
  if (!open) return null;

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(0,0,0,0.65)", backdropFilter: "blur(8px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} className="wood-card slide-up" style={{ width: "100%", maxWidth: 520, padding: 24, maxHeight: "90vh", overflow: "auto" }}>
        <div className="flex items-center justify-between mb-5">
          <div>
            <div className="text-xs uppercase tracking-widest text-amber mb-1" style={{ fontWeight: 600 }}>NOVO APONTAMENTO</div>
            <div className="text-xl font-semibold tracking-tight">Bater ponto</div>
          </div>
          <button className="wood-btn wood-btn-ghost wood-btn-icon-sm" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>

        <div className="grid grid-cols-2 gap-3 mb-3">
          <div>
            <label className="wood-label">Colaborador</label>
            <select className="wood-select">
              {MOCK.teams.flatMap(t => t.avatars).map(w => <option key={w}>{w}</option>)}
            </select>
          </div>
          <div>
            <label className="wood-label">Obra</label>
            <select className="wood-select">
              {MOCK.projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </div>
        </div>

        <div className="mb-3">
          <label className="wood-label">Atividade</label>
          <div className="grid grid-cols-4 gap-2">
            {MOCK.timesheet.activities.map(a => (
              <button key={a.id} type="button" onClick={() => setActivity(a.id)}
                className="flex flex-col items-center gap-1.5 py-3 rounded-lg"
                style={{
                  background: activity === a.id ? `${a.color}14` : "var(--wood-surface-2)",
                  border: `1px solid ${activity === a.id ? a.color + "88" : "var(--wood-border)"}`,
                  color: activity === a.id ? a.color : "var(--text-2)",
                  cursor: "pointer", fontWeight: activity === a.id ? 600 : 500, transition: "all 0.18s",
                  fontSize: 11
                }}>
                <Icon name={a.icon} size={16} />
                {a.label}
              </button>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-3 gap-3 mb-3">
          <div>
            <label className="wood-label">Data</label>
            <input type="date" className="wood-input" defaultValue="2026-05-15" />
          </div>
          <div>
            <label className="wood-label">Início</label>
            <input type="time" className="wood-input" defaultValue="08:00" />
          </div>
          <div>
            <label className="wood-label">Fim (opcional)</label>
            <input type="time" className="wood-input" />
          </div>
        </div>

        <div className="mb-5">
          <label className="wood-label">Observações (opcional)</label>
          <textarea className="wood-textarea" rows={3} placeholder="O que foi feito, materiais usados, observações…" />
        </div>

        <div className="rounded-lg p-3 mb-5" style={{ background: "rgba(56,189,248,0.06)", border: "1px solid rgba(56,189,248,0.2)" }}>
          <div className="flex items-start gap-2">
            <Icon name="info" size={14} className="text-info mt-0.5" />
            <div className="text-xs text-2">
              Deixe o horário de fim em branco para iniciar um ponto aberto. Você poderá fechar quando terminar.
            </div>
          </div>
        </div>

        <div className="flex items-center justify-end gap-2 pt-4 border-t" style={{ borderColor: "var(--wood-border)" }}>
          <button className="wood-btn wood-btn-ghost" onClick={onClose}>Cancelar</button>
          <button className="wood-btn wood-btn-primary" onClick={onClose}>
            <Icon name="check" size={14} /> Registrar ponto
          </button>
        </div>
      </div>
    </div>
  );
};

/* expose */
Object.assign(window, { TimesheetPage });
