// ═══════════════════════════════════════════════════════════════
//  time-tracker.jsx — daily hours tracker with calendar view
//  State lives in app.jsx, this is purely presentational.
// ═══════════════════════════════════════════════════════════════

const WEEKDAYS = ["Пон", "Вто", "Сря", "Чет", "Пет", "Съб", "Нед"];
const MONTH_NAMES = ["Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"];

// ─── Preset activities (from eSky hours report) ───
const ACTIVITY_PRESETS = [
  "Consultative support — product/marketing/tech teams",
  "Affiliate partnerships — CEE market opportunities",
  "Business relationships — partner management & onboarding",
  "Campaign analysis & optimisation recommendations",
  "Promotional content review & campaign implementation",
  "Admin, reporting & internal coordination",
];
const PROJECT_PRESETS = ["eSky", "klar.bet", "Traveltopia", "AISiftr", "Todoroff", "Shortcut Studio"];

// ─── ComboField: input with datalist suggestions + recent values ───
function ComboField({ label, value, onChange, suggestions, T, minWidth = 0, listId }) {
  return (
    <div style={{ flex: 1, minWidth, display: "flex", flexDirection: "column", gap: 5 }}>
      {label && <Label T={T}>{label}</Label>}
      <input
        type="text" value={value} list={listId}
        onChange={e => onChange(e.target.value)}
        style={{
          width: "100%", padding: "9px 12px",
          border: `1px solid ${T.line}`, borderRadius: 7, fontSize: 13,
          fontFamily: MONO, fontWeight: 500, color: T.ink, background: T.field,
          outline: "none", boxSizing: "border-box",
        }}
        onFocus={e => { e.target.style.borderColor = T.blue; e.target.style.boxShadow = `0 0 0 3px ${T.blueSoft}`; }}
        onBlur={e => { e.target.style.borderColor = T.line; e.target.style.boxShadow = "none"; }}
      />
      <datalist id={listId}>
        {suggestions.map((s, i) => <option key={i} value={s} />)}
      </datalist>
    </div>
  );
}

function TimeTracker({ T, timeEntries, clients, onSave, onUpdate, onDelete, onGenerateReport }) {
  const { useState, useMemo, useCallback } = React;

  const [currentMonth, setCurrentMonth] = useState(() => {
    const d = new Date(); return { year: d.getFullYear(), month: d.getMonth() };
  });
  const [selectedDay, setSelectedDay] = useState(null); // 'YYYY-MM-DD' or null
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState({ description: "", hours: "", client_id: "", project: "", billable: true });

  const monthKey = `${currentMonth.year}-${String(currentMonth.month + 1).padStart(2, "0")}`;

  // ─── Filter entries for current month ───
  const monthEntries = useMemo(
    () => (timeEntries || []).filter(e => e.date && e.date.startsWith(monthKey)),
    [timeEntries, monthKey]
  );

  // ─── Group by date ───
  const byDate = useMemo(() => {
    const m = {};
    monthEntries.forEach(e => {
      if (!m[e.date]) m[e.date] = [];
      m[e.date].push(e);
    });
    return m;
  }, [monthEntries]);

  // ─── Calendar grid cells ───
  const calendarDays = useMemo(() => {
    const y = currentMonth.year, m = currentMonth.month;
    const firstDay = new Date(y, m, 1).getDay(); // 0=Sun
    const daysInMonth = new Date(y, m + 1, 0).getDate();
    // Convert Sunday=0 to Monday=0
    const offset = firstDay === 0 ? 6 : firstDay - 1;
    const cells = [];
    for (let i = 0; i < offset; i++) cells.push(null);
    for (let d = 1; d <= daysInMonth; d++) {
      const dateStr = `${y}-${String(m + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
      const entries = byDate[dateStr] || [];
      const totalHours = entries.reduce((s, e) => s + (e.hours || 0), 0);
      const billableHours = entries.reduce((s, e) => s + (e.billable ? (e.hours || 0) : 0), 0);
      cells.push({ day: d, date: dateStr, entries, totalHours, billableHours });
    }
    return cells;
  }, [currentMonth, byDate]);

  // ─── Monthly summary ───
  const summary = useMemo(() => {
    let total = 0, billable = 0, nonBillable = 0;
    const byClient = {};
    monthEntries.forEach(e => {
      const h = e.hours || 0;
      total += h;
      if (e.billable) billable += h; else nonBillable += h;
      const cName = e.client_name_en || e.client_name || "Без клиент";
      if (!byClient[cName]) byClient[cName] = { total: 0, billable: 0 };
      byClient[cName].total += h;
      if (e.billable) byClient[cName].billable += h;
    });
    return { total, billable, nonBillable, byClient };
  }, [monthEntries]);

  // ─── Day entries ───
  const dayEntries = selectedDay ? (byDate[selectedDay] || []) : [];

  // ─── Nav ───
  const prevMonth = () => setCurrentMonth(p => p.month === 0 ? { year: p.year - 1, month: 11 } : { ...p, month: p.month - 1 });
  const nextMonth = () => setCurrentMonth(p => p.month === 11 ? { year: p.year + 1, month: 0 } : { ...p, month: p.month + 1 });
  const goToday = () => {
    const d = new Date();
    setCurrentMonth({ year: d.getFullYear(), month: d.getMonth() });
    setSelectedDay(today());
  };

  // ─── Form ───
  const resetForm = () => { setForm({ description: "", hours: "", client_id: "", project: "", billable: true }); setEditingId(null); };
  const startEdit = (e) => {
    setForm({ description: e.description || "", hours: e.hours || "", client_id: e.client_id || "", project: e.project || "", billable: !!e.billable });
    setEditingId(e.id);
  };
  const handleSave = () => {
    const h = Number(form.hours) || 0;
    if (h <= 0 && !form.description) return;
    const payload = { date: selectedDay, hours: h, description: form.description || null, client_id: form.client_id ? Number(form.client_id) : null, project: form.project || null, billable: form.billable ? 1 : 0 };
    if (editingId) {
      onUpdate({ ...payload, id: editingId });
    } else {
      onSave(payload);
    }
    resetForm();
  };

  const isToday = (dateStr) => dateStr === today();
  const isWeekend = (cell) => {
    if (!cell) return false;
    const d = new Date(cell.date);
    return d.getDay() === 0 || d.getDay() === 6;
  };

  // ─── Client select options ───
  const clientOpts = [{ v: "", l: "— Клиент —" }, ...(clients || []).map((c, i) => ({ v: String(c._id || i), l: c.nameEn || c.name || `Клиент ${i + 1}` }))];

  // ─── Merge presets with recently-used values ───
  const activitySuggestions = useMemo(() => {
    const recent = [...new Set((timeEntries || []).map(e => e.description).filter(Boolean))];
    const merged = [...ACTIVITY_PRESETS];
    recent.forEach(r => { if (!merged.includes(r)) merged.push(r); });
    return merged;
  }, [timeEntries]);
  const projectSuggestions = useMemo(() => {
    const recent = [...new Set((timeEntries || []).map(e => e.project).filter(Boolean))];
    const merged = [...PROJECT_PRESETS];
    recent.forEach(r => { if (!merged.includes(r)) merged.push(r); });
    return merged;
  }, [timeEntries]);

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 300px", minHeight: "100%", gap: 0 }}>
      {/* ─── Left: Calendar + day detail ─── */}
      <div style={{ padding: "22px 24px", overflow: "auto", borderRight: `1px solid ${T.line}` }}>

        {/* Month header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <button onClick={prevMonth} style={{ background: "none", border: `1px solid ${T.line}`, borderRadius: 6, padding: "5px 8px", cursor: "pointer", color: T.ink, display: "flex", transform: "rotate(180deg)" }}><Icon name="chevron" size={14} /></button>
            <div style={{ fontSize: 15, fontWeight: 700, minWidth: 180, textAlign: "center" }}>
              {MONTH_NAMES[currentMonth.month]} {currentMonth.year}
            </div>
            <button onClick={nextMonth} style={{ background: "none", border: `1px solid ${T.line}`, borderRadius: 6, padding: "5px 8px", cursor: "pointer", color: T.ink, display: "flex" }}><Icon name="chevron" size={14} /></button>
          </div>
          <Button T={T} kind="ghost" size="sm" icon="clock" onClick={goToday}>Днес</Button>
        </div>

        {/* Calendar grid */}
        <div style={{ background: T.surface, border: `1px solid ${T.line}`, borderRadius: 10, overflow: "hidden", marginBottom: 18 }}>
          {/* Weekday headers */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", borderBottom: `1px solid ${T.line}` }}>
            {WEEKDAYS.map(d => (
              <div key={d} style={{ padding: "8px 0", textAlign: "center", fontSize: 10, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: T.faint }}>{d}</div>
            ))}
          </div>
          {/* Day cells */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)" }}>
            {calendarDays.map((cell, i) => {
              if (!cell) return <div key={`e${i}`} style={{ padding: 8, borderBottom: `1px solid ${T.line}`, borderRight: (i + 1) % 7 !== 0 ? `1px solid ${T.line}` : "none", background: T.field, opacity: 0.4 }} />;
              const selected = cell.date === selectedDay;
              const todayCell = isToday(cell.date);
              const weekend = isWeekend(cell);
              return (
                <div key={cell.date} onClick={() => setSelectedDay(cell.date === selectedDay ? null : cell.date)}
                  style={{
                    padding: "6px 8px", minHeight: 56, cursor: "pointer", position: "relative",
                    borderBottom: `1px solid ${T.line}`, borderRight: (i + 1) % 7 !== 0 ? `1px solid ${T.line}` : "none",
                    background: selected ? T.blueSoft : weekend ? `${T.field}` : "transparent",
                    transition: "background .1s",
                  }}
                  onMouseEnter={e => { if (!selected) e.currentTarget.style.background = T.blueSoft; }}
                  onMouseLeave={e => { if (!selected) e.currentTarget.style.background = weekend ? T.field : "transparent"; }}
                >
                  <div style={{ fontSize: 12, fontWeight: todayCell ? 800 : 500, color: todayCell ? T.blue : weekend ? T.faint : T.ink }}>
                    {cell.day}
                  </div>
                  {cell.totalHours > 0 && (
                    <div style={{ marginTop: 4 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, fontFamily: MONO, color: T.blue }}>{fmtHours(cell.totalHours)}</div>
                      {cell.billableHours < cell.totalHours && (
                        <div style={{ fontSize: 9, color: T.faint, marginTop: 1 }}>{fmtHours(cell.billableHours)} bill.</div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* ─── Selected day detail ─── */}
        {selectedDay && (
          <Card T={T} title={`${fmtDate(selectedDay)} · ${dayEntries.reduce((s, e) => s + (e.hours || 0), 0).toFixed(1)} ч`} icon="clock">
            {/* Existing entries */}
            {dayEntries.map(e => (
              <div key={e.id} style={{ padding: "10px 14px", background: e.billable ? T.blueSoft : `${T.line}`, borderRadius: 8, marginBottom: 8, display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500, color: T.ink, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.description || "—"}</div>
                  <div style={{ fontSize: 10, color: T.faint, marginTop: 2 }}>
                    {e.client_name_en || e.client_name || ""}{e.project ? ` · ${e.project}` : ""}
                    {!e.billable && " · non-billable"}
                  </div>
                </div>
                <div style={{ fontSize: 14, fontWeight: 700, fontFamily: MONO, color: T.blue, flexShrink: 0 }}>{fmtHours(e.hours)}</div>
                <button onClick={() => startEdit(e)} title="Редактирай" style={{ background: "none", border: "none", color: T.sub, cursor: "pointer", padding: 3 }}><Icon name="edit" size={14} /></button>
                <button onClick={() => onDelete(e.id)} title="Изтрий" style={{ background: "none", border: "none", color: T.danger, cursor: "pointer", padding: 3 }}><Icon name="trash" size={14} /></button>
              </div>
            ))}

            {/* Add/edit form */}
            <div style={{ padding: "14px 14px 8px", background: T.blueSoft, borderRadius: 9, marginTop: dayEntries.length > 0 ? 6 : 0 }}>
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: T.faint, marginBottom: 10 }}>
                {editingId ? "Редактирай запис" : "Нов запис"}
              </div>
              <Row>
                <ComboField label="Описание" value={form.description} onChange={v => setForm(p => ({ ...p, description: v }))} suggestions={activitySuggestions} T={T} minWidth={200} listId="tt-activities" />
                <Field label="Часове" type="number" value={form.hours} onChange={v => setForm(p => ({ ...p, hours: v }))} T={T} mono minWidth={80} />
              </Row>
              <Row>
                <Select label="Клиент" value={form.client_id} onChange={v => setForm(p => ({ ...p, client_id: v }))} options={clientOpts} T={T} minWidth={160} />
                <ComboField label="Проект" value={form.project} onChange={v => setForm(p => ({ ...p, project: v }))} suggestions={projectSuggestions} T={T} minWidth={120} listId="tt-projects" />
              </Row>
              <Row style={{ marginBottom: 4 }}>
                <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer", fontSize: 12, color: T.sub }}>
                  <input type="checkbox" checked={form.billable} onChange={e => setForm(p => ({ ...p, billable: e.target.checked }))}
                    style={{ width: 16, height: 16, cursor: "pointer", accentColor: T.blue }} />
                  Billable
                </label>
                <div style={{ flex: 1 }} />
                {editingId && <Button T={T} kind="ghost" size="sm" onClick={resetForm}>Откажи</Button>}
                <Button T={T} kind="primary" size="sm" icon={editingId ? "check" : "plus"} onClick={handleSave}>
                  {editingId ? "Запази" : "Добави"}
                </Button>
              </Row>
            </div>
          </Card>
        )}

        {!selectedDay && (
          <div style={{ textAlign: "center", padding: "40px 20px", color: T.faint, fontSize: 12 }}>
            Избери ден от календара, за да добавиш часове.
          </div>
        )}
      </div>

      {/* ─── Right: Summary ─── */}
      <div style={{ padding: "22px 18px", overflow: "auto", background: T.bg }}>
        <Card T={T} title="Месечен преглед" icon="chart">
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {/* Totals */}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontSize: 11, color: T.sub }}>Общо часове</span>
              <span style={{ fontSize: 18, fontWeight: 700, fontFamily: MONO, color: T.ink }}>{fmtHours(summary.total)}</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontSize: 11, color: T.sub }}>Billable</span>
              <span style={{ fontSize: 14, fontWeight: 600, fontFamily: MONO, color: T.blue }}>{fmtHours(summary.billable)}</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontSize: 11, color: T.sub }}>Non-billable</span>
              <span style={{ fontSize: 14, fontWeight: 600, fontFamily: MONO, color: T.faint }}>{fmtHours(summary.nonBillable)}</span>
            </div>

            {/* Progress bar */}
            {summary.total > 0 && (
              <div style={{ height: 6, borderRadius: 3, background: T.line, overflow: "hidden" }}>
                <div style={{ height: "100%", width: `${(summary.billable / summary.total) * 100}%`, background: T.blue, borderRadius: 3, transition: "width .2s" }} />
              </div>
            )}

            {/* By client breakdown */}
            {Object.keys(summary.byClient).length > 0 && (
              <>
                <div style={{ borderTop: `1px solid ${T.line}`, paddingTop: 12, marginTop: 4 }}>
                  <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: T.faint, marginBottom: 10 }}>По клиент</div>
                  {Object.entries(summary.byClient).sort((a, b) => b[1].total - a[1].total).map(([name, data]) => (
                    <div key={name} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "5px 0", fontSize: 11.5 }}>
                      <span style={{ color: T.sub, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 140 }}>{name}</span>
                      <span style={{ fontFamily: MONO, fontWeight: 600, color: T.ink }}>{fmtHours(data.total)}</span>
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        </Card>

        {/* Generate report */}
        <Card T={T} title="Генерирай Report" icon="doc">
          <div style={{ fontSize: 11.5, color: T.sub, marginBottom: 12, lineHeight: 1.6 }}>
            Създава Hours Report от записите за {MONTH_NAMES[currentMonth.month]}.
            Billable entries се групират по описание.
          </div>
          <Button T={T} kind="primary" icon="repeat" onClick={() => onGenerateReport(monthKey, monthEntries)}>
            Генерирай
          </Button>
        </Card>

        {/* Quick stats */}
        {monthEntries.length > 0 && (
          <Card T={T} title="Бърза статистика" icon="chart" style={{ marginBottom: 0 }}>
            <div style={{ fontSize: 11.5, color: T.sub, lineHeight: 1.8 }}>
              <div>Дни с часове: <strong style={{ color: T.ink }}>{Object.keys(byDate).length}</strong></div>
              <div>Записи: <strong style={{ color: T.ink }}>{monthEntries.length}</strong></div>
              <div>Ср. часове/ден: <strong style={{ color: T.ink }}>{Object.keys(byDate).length > 0 ? fmtHours(summary.total / Object.keys(byDate).length) : "0"}</strong></div>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { TimeTracker });
