/* Wood OS — Calendário & Gantt de produção */
const { useState: useStateSch, useMemo: useMemoSch } = React;

/* ============================================================
   Helpers
   ============================================================ */
const TODAY = "2026-05-15";
const MS_DAY = 86400000;

const dateToMs = (s) => new Date(s + "T00:00:00").getTime();
const msToDate = (ms) => new Date(ms).toISOString().slice(0, 10);
const daysBetween = (a, b) => Math.round((dateToMs(b) - dateToMs(a)) / MS_DAY);
const fmtMonthShort = (s) => {
  const d = new Date(s + "T00:00:00");
  return d.toLocaleDateString("pt-BR", { month: "short" }).replace(".", "");
};
const dayOfMonth = (s) => parseInt(s.split("-")[2], 10);

const enrichSchedule = () => {
  return MOCK.schedule.map(s => {
    const project = MOCK.projects.find(p => p.id === s.projectId);
    if (!project) return null;
    return { ...s, project };
  }).filter(Boolean);
};

/* ============================================================
   SchedulePage
   ============================================================ */
const SchedulePage = ({ navigate }) => {
  const [view, setView] = useStateSch("gantt");
  const [teamFilter, setTeamFilter] = useStateSch("todas");
  const [creating, setCreating] = useStateSch(false);
  const schedule = useMemoSch(enrichSchedule, []);

  const teams = useMemoSch(() => [...new Set(schedule.map(s => s.team))], [schedule]);
  const filtered = useMemoSch(() => teamFilter === "todas" ? schedule : schedule.filter(s => s.team === teamFilter), [schedule, teamFilter]);

  const metrics = useMemoSch(() => {
    const active = filtered.filter(s => s.project.status === "producao" || s.project.status === "analise" || s.project.status === "pronto");
    const upcoming = filtered.filter(s => {
      const days = daysBetween(TODAY, s.endDate);
      return days >= 0 && days <= 14;
    });
    const overdue = filtered.filter(s => daysBetween(TODAY, s.endDate) < 0 && s.project.status !== "entregue");
    const teamsActive = new Set(active.map(s => s.team)).size;
    return { active: active.length, upcoming: upcoming.length, overdue: overdue.length, teamsActive };
  }, [filtered]);

  return (
    <>
      <PageHeader
        kicker="Produção"
        title="Calendário de Produção"
        subtitle="Planejamento de obras no tempo. Visualize sobreposições, sobrecarga de equipe e janelas de entrega — Gantt, calendário ou semana."
        actions={
          <>
            <div className="iflex items-center" style={{ background: "var(--wood-surface-2)", border: "1px solid var(--wood-border)", borderRadius: 10, padding: 2 }}>
              <button onClick={() => setView("gantt")} className="wood-btn wood-btn-ghost wood-btn-sm" style={{ background: view === "gantt" ? "rgba(16,185,129,0.16)" : "transparent", color: view === "gantt" ? "var(--cream)" : undefined }}>
                <Icon name="activity" size={13} /> Gantt
              </button>
              <button onClick={() => setView("calendar")} className="wood-btn wood-btn-ghost wood-btn-sm" style={{ background: view === "calendar" ? "rgba(16,185,129,0.16)" : "transparent", color: view === "calendar" ? "var(--cream)" : undefined }}>
                <Icon name="calendar" size={13} /> Mês
              </button>
              <button onClick={() => setView("workload")} className="wood-btn wood-btn-ghost wood-btn-sm" style={{ background: view === "workload" ? "rgba(16,185,129,0.16)" : "transparent", color: view === "workload" ? "var(--cream)" : undefined }}>
                <Icon name="users" size={13} /> Equipes
              </button>
            </div>
            <button className="wood-btn wood-btn-secondary"><Icon name="external" size={13} /> Exportar</button>
            <button className="wood-btn wood-btn-primary" onClick={() => setCreating(true)}><Icon name="plus" size={13} /> Nova obra</button>
          </>
        }
      />

      <FormModal open={creating} onClose={() => setCreating(false)}
        kicker="NOVA OBRA" title="Agendar obra no calendário" icon="hammer"
        submitLabel="Adicionar ao calendário" maxWidth={620}
        footerHint="A obra aparece imediatamente no Gantt e no calendário mensal, com a equipe destacada por cor.">
        <FormRow label="Obra existente">
          <select className="wood-select">
            <option value="">Criar nova…</option>
            {MOCK.projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <div className="text-xs text-4 mt-1">Ou agende uma obra que ainda não está no sistema</div>
        </FormRow>
        <FormRow label="Nome da obra (se nova)">
          <input className="wood-input" placeholder="Ex: Apartamento Lagoa 1804" />
        </FormRow>
        <FormGrid>
          <FormRow label="Equipe" required>
            <select className="wood-select">
              {MOCK.teams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
            </select>
          </FormRow>
          <FormRow label="Cliente">
            <select className="wood-select">
              <option value="">Sem cliente vinculado</option>
              {MOCK.clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </FormRow>
        </FormGrid>
        <FormGrid>
          <FormRow label="Início" required>
            <input type="date" className="wood-input" defaultValue="2026-05-15" />
          </FormRow>
          <FormRow label="Entrega" required>
            <input type="date" className="wood-input" />
          </FormRow>
        </FormGrid>
        <FormRow label="Marcos / milestones (opcional)">
          <textarea className="wood-textarea" rows={3} placeholder="Um marco por linha — ex: '01/06 — Aprovação plantas&#10;15/06 — Início produção'" />
        </FormRow>
      </FormModal>

      {/* KPIs */}
      <div className="grid grid-cols-4 gap-4 mb-5">
        <MetricCard icon="hammer" label="Obras em andamento" value={metrics.active} sub={`${schedule.length} no total`} accent="amber" delay={0} />
        <MetricCard icon="calendar" label="Entregas em 14 dias" value={metrics.upcoming} sub="próximas 2 semanas" accent="info" delay={60} />
        <MetricCard icon="alert" label="Atrasadas" value={metrics.overdue} sub={metrics.overdue === 0 ? "nada atrasado 🎉" : "ação necessária"} accent={metrics.overdue > 0 ? "warning" : "success"} delay={120} />
        <MetricCard icon="users" label="Equipes em uso" value={metrics.teamsActive} sub={`de ${teams.length} disponíveis`} accent="info" delay={180} />
      </div>

      {/* Team filter */}
      <div className="wood-card p-3 mb-4 flex items-center gap-2 flex-wrap">
        <FilterChip active={teamFilter === "todas"} onClick={() => setTeamFilter("todas")} count={schedule.length}>Todas as equipes</FilterChip>
        {teams.map(t => {
          const c = schedule.filter(s => s.team === t).length;
          const color = schedule.find(s => s.team === t)?.color;
          return (
            <FilterChip key={t} active={teamFilter === t} onClick={() => setTeamFilter(t)} count={c}>
              <span className="wood-dot" style={{ background: color, marginRight: 5 }} /> {t}
            </FilterChip>
          );
        })}
      </div>

      {view === "gantt"    && <GanttView items={filtered} />}
      {view === "calendar" && <MonthView items={filtered} />}
      {view === "workload" && <WorkloadView items={filtered} teams={teams} />}
    </>
  );
};

/* ============================================================
   GanttView
   ============================================================ */
const GanttView = ({ items }) => {
  // Determine the time window: from earliest start to latest end
  if (items.length === 0) return <EmptyState icon="calendar" title="Sem obras" description="Nenhuma obra para esse filtro." />;

  const minStart = items.reduce((m, i) => i.startDate < m ? i.startDate : m, items[0].startDate);
  const maxEnd   = items.reduce((m, i) => i.endDate   > m ? i.endDate   : m, items[0].endDate);
  // Add padding
  const startMs = dateToMs(minStart) - 3 * MS_DAY;
  const endMs   = dateToMs(maxEnd)   + 3 * MS_DAY;
  const totalDays = Math.round((endMs - startMs) / MS_DAY);

  // Generate month labels
  const months = useMemoSch(() => {
    const out = [];
    let cur = new Date(startMs);
    cur.setDate(1);
    while (cur.getTime() < endMs) {
      const ms = cur.getTime();
      const offset = Math.max(0, (ms - startMs) / MS_DAY);
      const nextMonth = new Date(cur.getFullYear(), cur.getMonth() + 1, 1).getTime();
      const widthDays = (Math.min(nextMonth, endMs) - Math.max(ms, startMs)) / MS_DAY;
      const label = cur.toLocaleDateString("pt-BR", { month: "short", year: "2-digit" }).replace(".", "");
      out.push({ offset, widthDays, label });
      cur = new Date(cur.getFullYear(), cur.getMonth() + 1, 1);
    }
    return out;
  }, [items]);

  const todayOffset = Math.max(0, (dateToMs(TODAY) - startMs) / MS_DAY);

  // Sort: by startDate
  const sorted = [...items].sort((a, b) => a.startDate.localeCompare(b.startDate));

  const ROW_H = 56;
  const HEADER_H = 48;
  const LEFT_W = 240;
  const dayPx = 8; // 8px per day = good zoom level

  const innerWidth = totalDays * dayPx;

  return (
    <div className="wood-card overflow-hidden" style={{ padding: 0 }}>
      <div className="flex" style={{ overflowX: "auto" }}>
        {/* Left column: project labels */}
        <div style={{ width: LEFT_W, flexShrink: 0, borderRight: "1px solid var(--wood-border)" }}>
          <div className="flex items-center justify-between px-4" style={{ height: HEADER_H, background: "rgba(0,0,0,0.28)", borderBottom: "1px solid var(--wood-border)" }}>
            <div className="text-xs uppercase tracking-widest text-3" style={{ fontWeight: 600 }}>OBRA</div>
            <Icon name="more" size={12} className="text-4" />
          </div>
          {sorted.map(s => (
            <div key={s.projectId} className="flex items-center gap-2 px-4" style={{ height: ROW_H, borderBottom: "1px solid var(--wood-border-soft)" }}>
              <span className="wood-dot" style={{ background: s.color, width: 8, height: 8, flexShrink: 0 }} />
              <div className="min-w-0">
                <div className="text-sm truncate" style={{ fontWeight: 600 }}>{s.project.name}</div>
                <div className="text-xs text-4 truncate">{s.team}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Right scroll area: timeline */}
        <div style={{ flex: 1, minWidth: innerWidth, position: "relative" }}>
          {/* Header months */}
          <div style={{ height: HEADER_H, position: "relative", borderBottom: "1px solid var(--wood-border)", background: "rgba(0,0,0,0.28)" }}>
            {months.map((m, i) => (
              <div key={i} style={{ position: "absolute", top: 0, left: m.offset * dayPx, width: m.widthDays * dayPx, height: HEADER_H, borderLeft: i > 0 ? "1px solid var(--wood-border-soft)" : "none", padding: "10px 12px" }}>
                <div className="text-xs uppercase tracking-widest text-3" style={{ fontWeight: 600 }}>{m.label}</div>
              </div>
            ))}
          </div>

          {/* Rows + bars */}
          <div style={{ position: "relative" }}>
            {/* Grid lines (month boundaries) */}
            {months.map((m, i) => i > 0 && (
              <div key={`gl-${i}`} style={{ position: "absolute", top: 0, bottom: 0, left: m.offset * dayPx, width: 1, background: "var(--wood-border-soft)" }} />
            ))}

            {/* Today line */}
            <div style={{ position: "absolute", top: 0, bottom: 0, left: todayOffset * dayPx, width: 2, background: "var(--amber-bright)", zIndex: 3, boxShadow: "0 0 8px rgba(16,185,129,0.5)" }}>
              <div style={{ position: "absolute", top: -22, left: -22, background: "var(--amber-bright)", color: "#0a1a13", padding: "2px 8px", borderRadius: 4, fontSize: 10, fontWeight: 700, whiteSpace: "nowrap" }}>HOJE</div>
            </div>

            {sorted.map(s => {
              const startOff = (dateToMs(s.startDate) - startMs) / MS_DAY;
              const widthD = (dateToMs(s.endDate) - dateToMs(s.startDate)) / MS_DAY;
              const progress = s.project.progress / 100;
              const overdue = daysBetween(TODAY, s.endDate) < 0 && s.project.status !== "entregue";

              return (
                <div key={s.projectId} style={{ height: ROW_H, position: "relative", borderBottom: "1px solid var(--wood-border-soft)" }}>
                  {/* Bar */}
                  <div style={{
                    position: "absolute",
                    top: 12, height: ROW_H - 24,
                    left: startOff * dayPx, width: widthD * dayPx,
                    background: `${s.color}26`,
                    border: `1.5px solid ${overdue ? "var(--error)" : s.color}`,
                    borderRadius: 6,
                    overflow: "hidden",
                    display: "flex", alignItems: "center", padding: "0 8px",
                    cursor: "pointer"
                  }}>
                    {/* Progress fill */}
                    <div style={{
                      position: "absolute", top: 0, left: 0, bottom: 0,
                      width: `${progress * 100}%`,
                      background: `linear-gradient(90deg, ${s.color}88, ${s.color}44)`,
                    }} />
                    {/* Label */}
                    <div className="text-xs relative" style={{ fontWeight: 700, color: "var(--cream)", textShadow: "0 1px 2px rgba(0,0,0,0.6)", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>
                      {s.project.progress}% · {widthD}d
                    </div>
                  </div>

                  {/* Milestones */}
                  {s.milestones.map((mil, i) => {
                    const milOff = (dateToMs(mil.date) - startMs) / MS_DAY;
                    return (
                      <div key={i} style={{
                        position: "absolute", top: ROW_H / 2 - 5,
                        left: milOff * dayPx - 5,
                        width: 10, height: 10,
                        background: mil.done ? s.color : "var(--wood-bg)",
                        border: `2px solid ${s.color}`,
                        transform: "rotate(45deg)",
                        zIndex: 2,
                      }} title={`${mil.label} — ${fmtDate(mil.date)}`} />
                    );
                  })}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};

/* ============================================================
   MonthView — calendar grid for May 2026
   ============================================================ */
const MonthView = ({ items }) => {
  // Build a 5-week grid starting from the first day of May 2026
  const year = 2026, month = 4; // May (0-indexed)
  const first = new Date(year, month, 1);
  const firstDow = first.getDay(); // 0 = sun
  const daysInMonth = new Date(year, month + 1, 0).getDate();

  // Pad start to first sunday
  const cells = [];
  for (let i = 0; i < firstDow; i++) {
    const d = new Date(year, month, -firstDow + i + 1);
    cells.push({ date: d.toISOString().slice(0, 10), outOfMonth: true });
  }
  for (let d = 1; d <= daysInMonth; d++) {
    const dt = new Date(year, month, d).toISOString().slice(0, 10);
    cells.push({ date: dt, day: d, outOfMonth: false });
  }
  while (cells.length % 7 !== 0) {
    const last = new Date(cells[cells.length - 1].date + "T00:00:00");
    last.setDate(last.getDate() + 1);
    cells.push({ date: last.toISOString().slice(0, 10), outOfMonth: true });
  }

  const eventsAt = (date) => {
    const evts = [];
    items.forEach(s => {
      if (s.startDate === date) evts.push({ kind: "start", schedule: s });
      if (s.endDate === date) evts.push({ kind: "end", schedule: s });
      s.milestones.forEach(m => { if (m.date === date) evts.push({ kind: "milestone", schedule: s, milestone: m }); });
    });
    return evts;
  };

  return (
    <div className="wood-card overflow-hidden" style={{ padding: 0 }}>
      <div className="flex items-center justify-between px-5 py-4" style={{ borderBottom: "1px solid var(--wood-border)", background: "rgba(0,0,0,0.28)" }}>
        <div className="text-md font-semibold tracking-tight">Maio · 2026</div>
        <div className="flex items-center gap-2">
          <button className="wood-btn wood-btn-ghost wood-btn-icon-sm"><Icon name="chevron-left" size={14} /></button>
          <button className="wood-btn wood-btn-ghost wood-btn-sm">Hoje</button>
          <button className="wood-btn wood-btn-ghost wood-btn-icon-sm"><Icon name="chevron-right" size={14} /></button>
        </div>
      </div>
      <div className="grid grid-cols-7" style={{ borderBottom: "1px solid var(--wood-border)" }}>
        {["DOM", "SEG", "TER", "QUA", "QUI", "SEX", "SÁB"].map(d => (
          <div key={d} className="text-xs text-3 text-center py-2" style={{ fontWeight: 600, letterSpacing: "0.06em", background: "rgba(0,0,0,0.18)" }}>{d}</div>
        ))}
      </div>
      <div className="grid grid-cols-7">
        {cells.map((c, i) => {
          const isToday = c.date === TODAY;
          const evts = eventsAt(c.date);
          return (
            <div key={i} style={{
              minHeight: 100, padding: 6,
              borderRight: (i % 7 < 6) ? "1px solid var(--wood-border-soft)" : "none",
              borderBottom: "1px solid var(--wood-border-soft)",
              opacity: c.outOfMonth ? 0.32 : 1,
              background: isToday ? "rgba(16,185,129,0.06)" : "transparent"
            }}>
              <div className="flex items-center justify-between mb-1">
                <span className="text-xs" style={{ fontWeight: isToday ? 700 : 600, color: isToday ? "var(--amber-bright)" : "var(--text-2)", fontVariantNumeric: "tabular-nums" }}>
                  {c.day || new Date(c.date + "T00:00:00").getDate()}
                </span>
                {isToday && <span className="wood-badge wood-badge-success" style={{ padding: "0 5px", fontSize: 8.5 }}>HOJE</span>}
              </div>
              <div className="flex flex-col gap-1">
                {evts.slice(0, 3).map((e, j) => {
                  const c = e.schedule.color;
                  if (e.kind === "milestone") {
                    return (
                      <div key={j} className="text-xs px-1.5 py-0.5 rounded truncate" style={{ background: `${c}1f`, color: c, borderLeft: `2px solid ${c}`, fontWeight: 500 }}>
                        ◆ {e.milestone.label}
                      </div>
                    );
                  }
                  return (
                    <div key={j} className="text-xs px-1.5 py-0.5 rounded truncate" style={{ background: e.kind === "end" ? `${c}40` : `${c}1f`, color: c, fontWeight: 600 }}>
                      {e.kind === "start" ? "▶ " : "🏁 "}{e.schedule.project.name}
                    </div>
                  );
                })}
                {evts.length > 3 && <div className="text-xs text-4">+ {evts.length - 3}</div>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

/* ============================================================
   WorkloadView — capacity per team
   ============================================================ */
const WorkloadView = ({ items, teams }) => {
  const byTeam = useMemoSch(() => {
    const m = {};
    teams.forEach(t => { m[t] = { team: t, projects: [], color: items.find(s => s.team === t)?.color || "#737373" }; });
    items.forEach(s => { if (m[s.team]) m[s.team].projects.push(s); });
    return Object.values(m);
  }, [items, teams]);

  // Time window
  const minStart = items.reduce((m, i) => i.startDate < m ? i.startDate : m, items[0]?.startDate || TODAY);
  const maxEnd   = items.reduce((m, i) => i.endDate > m ? i.endDate : m, items[0]?.endDate || TODAY);
  const startMs = dateToMs(minStart) - 3 * MS_DAY;
  const endMs   = dateToMs(maxEnd)   + 3 * MS_DAY;
  const totalDays = Math.round((endMs - startMs) / MS_DAY);
  const dayPx = 7;

  const todayOffset = Math.max(0, (dateToMs(TODAY) - startMs) / MS_DAY);

  return (
    <div className="flex flex-col gap-3">
      {byTeam.map(t => {
        const teamLoad = MOCK.teams.find(team => team.name === t.team)?.load || 50;
        return (
          <div key={t.team} className="wood-card p-4">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-3">
                <span className="wood-dot" style={{ background: t.color, width: 10, height: 10 }} />
                <div>
                  <div className="text-md font-semibold tracking-tight">{t.team}</div>
                  <div className="text-xs text-3">{t.projects.length} {t.projects.length === 1 ? "obra" : "obras"} · carga {teamLoad}%</div>
                </div>
              </div>
              <div style={{ width: 160 }}>
                <AnimatedProgress value={teamLoad} max={100} height={4} color={teamLoad > 80 ? "linear-gradient(90deg, #F59E0B, #EF4444)" : undefined} />
              </div>
            </div>

            {/* Mini timeline */}
            <div style={{ position: "relative", height: t.projects.length * 26 + 12, overflowX: "auto" }}>
              <div style={{ position: "relative", minWidth: totalDays * dayPx }}>
                {/* Today line */}
                <div style={{ position: "absolute", top: 0, bottom: 0, left: todayOffset * dayPx, width: 1.5, background: "var(--amber-bright)", zIndex: 2 }} />
                {t.projects.map((s, i) => {
                  const startOff = (dateToMs(s.startDate) - startMs) / MS_DAY;
                  const widthD = (dateToMs(s.endDate) - dateToMs(s.startDate)) / MS_DAY;
                  return (
                    <div key={s.projectId} style={{
                      position: "absolute",
                      top: i * 26 + 4, height: 22,
                      left: startOff * dayPx,
                      width: widthD * dayPx,
                      background: `${t.color}26`,
                      border: `1px solid ${t.color}`,
                      borderRadius: 4,
                      display: "flex", alignItems: "center", padding: "0 6px",
                      overflow: "hidden", whiteSpace: "nowrap",
                    }}>
                      <span className="text-xs truncate" style={{ color: "var(--text)", fontWeight: 600 }}>{s.project.name}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
};

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