/* GUIDKO App — Gérant (Manager) screens */

const HOURS = [8,9,10,11,12,13,14,15,16,17,18];
const DAYS_FR = ["Lun","Mar","Mer","Jeu","Ven","Sam"];
const DAYS_EN = ["Mon","Tue","Wed","Thu","Fri","Sat"];
const DATES = ["18","19","20","21","22","23"];

function GerantApp({ section, navigate }) {
  switch (section) {
    case "overview": return <GerantOverview navigate={navigate}/>;
    case "planning": return <PlanningModule role="gerant"/>;
    case "students": return <StudentsModule role="gerant"/>;
    case "instructors": return <InstructorsModule/>;
    case "vehicles": return <AutoModule role="gerant" navigate={navigate}/>;
    case "analytics": return <AnalyticsModule/>;
    case "finance": return <FinanceModule/>;
    case "settings": return <SettingsModule role="gerant" navigate={navigate}/>;
    default: return <GerantOverview navigate={navigate}/>;
  }
}

function GerantOverview({ navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  const { students, lessons, instructors, vehicles } = store.state;
  const activeStudents = students.length;
  const todayLessons = lessons.filter(l => l.day === 0);
  const occupancy = Math.round((todayLessons.length / (instructors.length * 6)) * 100);
  const myVehicles = vehicles.filter(v => v.seller === "Auto-École Lubasa").length;

  return (
    <>
      <Topbar subtitle={t("AUTO-ÉCOLE LUBASA · MARS 2026", "LUBASA · MAR 2026")} title={t("Bonjour Kevin.", "Hello Kevin.")}
        actions={<Button kind="primary" onClick={() => navigate("/gerant/students")}>+ {t("Nouvel élève", "New student")}</Button>}/>
      <PageBody>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
          <KPI label={t("CHIFFRE D'AFFAIRES","REVENUE")} value="18 420 €" delta="+12,4%" sub={t("vs mois dernier","vs last month")} icon="€"/>
          <KPI label={t("TAUX D'OCCUPATION","OCCUPANCY")} value={occupancy + "%"} delta="+6 pts" sub={t("aujourd'hui","today")} icon="◎"/>
          <KPI label={t("ÉLÈVES ACTIFS","ACTIVE STUDENTS")} value={activeStudents} delta={"+" + Math.max(1, activeStudents - 56)} sub={t("3 examens cette sem.","3 exams this week")} icon="★"/>
          <KPI label={t("VÉHICULES PUBLIÉS","LISTED VEHICLES")} value={myVehicles} delta="B2B" deltaTone="flame" sub={t("3 leads non lus","3 new leads")} icon="⇄"/>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 14, marginTop: 14 }}>
          <Card style={{ padding: 22 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div>
                <Label style={{ marginBottom: 8 }}>{t("CHIFFRE D'AFFAIRES · 12 SEMAINES","REVENUE · 12 WEEKS")}</Label>
                <div style={{ display: "flex", alignItems: "baseline", gap: 12 }}>
                  <span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 50, lineHeight: 1, letterSpacing: "-0.02em" }}>187 240 €</span>
                  <Pill tone="signal">+18,4%</Pill>
                </div>
              </div>
            </div>
            <div style={{ marginTop: 20 }}>
              <SparkLine data={[8,9,11,10,12,14,13,15,17,16,18,19]} color={C.flame} width={720} height={130}/>
            </div>
          </Card>

          <Card style={{ padding: 22 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 12 }}>
              <Label>{t("AUJOURD'HUI","TODAY")}</Label>
              <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 11, color: C.flame }}>● {todayLessons.length} {t("COURS","LESSONS")}</span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
              {todayLessons.slice(0, 6).map(l => {
                const s = studentById(store.state, l.studentId);
                const ty = store.state.types[l.type];
                return (
                  <div key={l.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", borderRadius: 8, background: "#fff", border: `1px solid ${C.softLine}` }}>
                    <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 11, width: 34, color: C.slate }}>{String(l.hour).padStart(2,"0")}:00</span>
                    <span style={{ width: 3, height: 26, background: ty.color, borderRadius: 2 }}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>{s ? s.name : "—"}</div>
                      <div style={{ fontSize: 11, color: C.slate }}>{ty.l}</div>
                    </div>
                    <Pill tone={l.status === "live" ? "flame" : l.status === "done" ? "signal" : "neutral"}>{l.status === "live" ? t("En cours","Live") : l.status === "done" ? t("Fait","Done") : t("À venir","Soon")}</Pill>
                  </div>
                );
              })}
            </div>
            <Button kind="ghost" size="sm" full style={{ marginTop: 12 }} onClick={() => navigate("/gerant/planning")}>{t("Voir le planning","See schedule")} →</Button>
          </Card>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14, marginTop: 14 }}>
          <Card style={{ padding: 22 }}>
            <Label style={{ marginBottom: 14 }}>{t("RENTABILITÉ · MONITEURS","PROFIT · INSTRUCTORS")}</Label>
            {instructors.map((m, i) => {
              const count = lessons.filter(l => l.instructorId === m.id).length;
              const pct = Math.min(100, 40 + count * 12);
              return (
                <div key={m.id} style={{ marginBottom: 12 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}><Avatar name={m.name} size={24} tone={m.tone}/><span style={{ fontSize: 13, fontWeight: 500 }}>{m.name}</span></div>
                    <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 12, fontWeight: 600 }}>{(count * 280).toLocaleString("fr-FR")} €</span>
                  </div>
                  <Bar pct={pct} color={pct > 80 ? C.signal : pct > 60 ? C.flame : C.slate} h={6}/>
                </div>
              );
            })}
          </Card>

          <Card style={{ padding: 22 }}>
            <Label style={{ marginBottom: 14 }}>{t("FUNNEL ÉLÈVES","STUDENT FUNNEL")}</Label>
            {[
              { l: t("Inscrits","Enrolled"), v: students.length, w: 100 },
              { l: t("Code en cours","Code ongoing"), v: students.filter(s => s.phase === "Code").length, w: 70 },
              { l: t("En conduite","Driving"), v: students.filter(s => s.phase === "Conduite").length, w: 50 },
              { l: t("En examen","Exam"), v: students.filter(s => s.phase === "Examen").length, w: 32 },
            ].map((f, i) => (
              <div key={i} style={{ marginBottom: 10 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}><span>{f.l}</span><span style={{ fontFamily: "'Geist Mono', monospace", fontWeight: 600 }}>{f.v}</span></div>
                <div style={{ height: 22, background: "#F6F2E6", borderRadius: 4, overflow: "hidden" }}>
                  <div style={{ width: `${f.w}%`, height: "100%", background: C.ink }}/>
                </div>
              </div>
            ))}
          </Card>

          <Card dark style={{ padding: 22 }}>
            <Label color="#7A82A8" style={{ marginBottom: 10 }}>{t("VOTRE STOCK B2B","YOUR B2B STOCK")}</Label>
            <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}><span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 50, lineHeight: 1 }}>{myVehicles}</span><span style={{ color: "#9098B5", fontSize: 13 }}>{t("véhicules","vehicles")}</span></div>
            <div style={{ display: "flex", gap: 6, marginTop: 14 }}>
              {vehicles.filter(v => v.seller === "Auto-École Lubasa").slice(0,3).map(v => <CarImg key={v.id} width={64} height={46} label="" tone="ink"/>)}
              <div style={{ width: 64, height: 46, border: "1px dashed #2A3250", borderRadius: 6, display: "grid", placeItems: "center", color: "#5B6388", fontSize: 18 }}>+</div>
            </div>
            <div style={{ marginTop: 16, fontSize: 13, color: "#C9CEE3" }}>{t("3 leads non lus · 2 offres en attente","3 new leads · 2 pending offers")}</div>
            <Button kind="flame" size="sm" style={{ marginTop: 14 }} onClick={() => navigate("/gerant/vehicles")}>{t("Ouvrir la marketplace","Open marketplace")} →</Button>
          </Card>
        </div>
      </PageBody>
    </>
  );
}

// ---------- PLANNING (interactive booking) ----------
function PlanningModule({ role }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const store = useStore();
  const toast = useToast();
  const days = lang === "fr" ? DAYS_FR : DAYS_EN;
  const [slot, setSlot] = React.useState(null); // {day, hour}
  const lessons = store.state.lessons;

  function cellLesson(day, hour) { return lessons.find(l => l.day === day && hour >= l.hour && hour < l.hour + (l.dur || 1)); }

  return (
    <>
      <Topbar subtitle={t("SEMAINE 12 · 18-23 MARS 2026","WEEK 12 · MAR 18-23")} title={t("Planning","Schedule")}
        actions={<Button kind="primary" onClick={() => setSlot({ day: 0, hour: 9 })}>+ {t("Créer un créneau","New slot")}</Button>}/>
      <PageBody style={{ display: "flex", flexDirection: "column" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <div style={{ display: "flex", gap: 14, fontSize: 12, alignItems: "center", flexWrap: "wrap" }}>
            {Object.entries(store.state.types).map(([k, ty]) => (
              <span key={k} style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 10, height: 10, background: ty.color, borderRadius: 2 }}/>{ty.l}</span>
            ))}
          </div>
          <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 11, color: C.flame }}>● {lessons.length} {t("COURS BOOKÉS","BOOKED")}</span>
        </div>

        <Card style={{ padding: 0, flex: 1, overflow: "hidden", display: "flex", flexDirection: "column" }}>
          <div style={{ display: "grid", gridTemplateColumns: "70px repeat(6, 1fr)", borderBottom: `1px solid ${C.softLine}`, flexShrink: 0 }}>
            <div style={{ padding: 12 }}/>
            {days.map((d, i) => (
              <div key={d} style={{ padding: 12, borderLeft: `1px solid ${C.softLine}`, background: i === 0 ? "#FBF8EE" : "transparent" }}>
                <Label color={i === 0 ? C.flame : C.slate} style={{ fontSize: 10 }}>{d}</Label>
                <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 22, lineHeight: 1, marginTop: 2 }}>{DATES[i]}</div>
              </div>
            ))}
          </div>
          <div className="gk-scroll" style={{ flex: 1, overflowY: "auto" }}>
            <div style={{ display: "grid", gridTemplateColumns: "70px repeat(6, 1fr)" }}>
              <div>
                {HOURS.map(h => <div key={h} style={{ height: 52, padding: "6px 10px", fontFamily: "'Geist Mono', monospace", fontSize: 11, color: C.slate, borderTop: `1px solid ${C.softLine}` }}>{String(h).padStart(2,"0")}:00</div>)}
              </div>
              {days.map((_, di) => (
                <div key={di} style={{ borderLeft: `1px solid ${C.softLine}`, position: "relative" }}>
                  {HOURS.map((h, hi) => {
                    const l = cellLesson(di, h);
                    if (l && l.hour === h) {
                      const s = studentById(store.state, l.studentId);
                      const ty = store.state.types[l.type];
                      return (
                        <div key={h} onClick={() => setSlot({ day: di, hour: h, lesson: l })} style={{ position: "absolute", top: hi * 52 + 2, left: 3, right: 3, height: (l.dur || 1) * 52 - 4, background: ty.color, color: ["exam"].includes(l.type) ? "#fff" : "#0B0F1F", padding: "6px 8px", borderRadius: 5, fontSize: 11, fontWeight: 600, cursor: "pointer", overflow: "hidden", zIndex: 2 }}>
                          {s ? s.name.split(" ")[0] : "—"} · {ty.l}
                        </div>
                      );
                    }
                    if (l) return <div key={h} style={{ height: 52, borderTop: hi === 0 ? "none" : `1px solid ${C.softLine}` }}/>;
                    return <div key={h} onClick={() => setSlot({ day: di, hour: h })} className="gk-slot" style={{ height: 52, borderTop: hi === 0 ? "none" : `1px solid ${C.softLine}`, cursor: "pointer" }}/>;
                  })}
                </div>
              ))}
            </div>
          </div>
        </Card>
      </PageBody>

      <SlotModal slot={slot} onClose={() => setSlot(null)}
        onBook={(data) => { store.addLesson(data); setSlot(null); toast.push(t("Créneau réservé !","Slot booked!"), "signal"); }}
        onCancel={(id) => { store.removeLesson(id); setSlot(null); toast.push(t("Créneau annulé","Slot cancelled"), "danger"); }}/>
    </>
  );
}

function SlotModal({ slot, onClose, onBook, onCancel }) {
  const { t, lang } = useI18n();
  const C = GK.colors;
  const store = useStore();
  const days = lang === "fr" ? DAYS_FR : DAYS_EN;
  const [studentId, setStudentId] = React.useState("s1");
  const [instructorId, setInstructorId] = React.useState("m1");
  const [type, setType] = React.useState("broute");
  const [day, setDay] = React.useState(0);
  const [hour, setHour] = React.useState(9);

  React.useEffect(() => { if (slot) { setDay(slot.day); setHour(slot.hour); } }, [slot]);
  if (!slot) return null;

  if (slot.lesson) {
    const l = slot.lesson;
    const s = studentById(store.state, l.studentId);
    const m = instructorById(store.state, l.instructorId);
    const ty = store.state.types[l.type];
    return (
      <Modal open onClose={onClose} title={t("Détail du créneau","Slot detail")}>
        <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
          <span style={{ width: 4, height: 48, background: ty.color, borderRadius: 2 }}/>
          <div>
            <div style={{ fontSize: 18, fontWeight: 600 }}>{ty.l}</div>
            <div style={{ fontSize: 13, color: C.slate }}>{days[l.day]} {DATES[l.day]} · {String(l.hour).padStart(2,"0")}:00 — {String(l.hour+(l.dur||1)).padStart(2,"0")}:00</div>
          </div>
        </div>
        {[[t("Élève","Student"), s], [t("Moniteur","Instructor"), m]].map(([label, p]) => p && (
          <div key={label} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 0", borderTop: `1px solid ${C.softLine}` }}>
            <Avatar name={p.name} size={32} tone={p.tone}/>
            <div><div style={{ fontSize: 13, fontWeight: 600 }}>{p.name}</div><Label style={{ fontSize: 9 }}>{label}</Label></div>
          </div>
        ))}
        <div style={{ display: "flex", gap: 8, marginTop: 18 }}>
          <Button kind="danger" onClick={() => onCancel(l.id)}>{t("Annuler le créneau","Cancel slot")}</Button>
          <Button kind="primary" full onClick={onClose}>{t("Fermer","Close")}</Button>
        </div>
      </Modal>
    );
  }

  return (
    <Modal open onClose={onClose} title={t("Réserver un créneau","Book a slot")}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Select label={t("Jour","Day")} value={day} onChange={v => setDay(+v)} options={days.map((d, i) => ({ value: i, label: `${d} ${DATES[i]}` }))}/>
        <Select label={t("Heure","Hour")} value={hour} onChange={v => setHour(+v)} options={HOURS.map(h => ({ value: h, label: `${String(h).padStart(2,"0")}:00` }))}/>
      </div>
      <Select label={t("Élève","Student")} value={studentId} onChange={setStudentId} options={store.state.students.map(s => ({ value: s.id, label: s.name }))}/>
      <Select label={t("Moniteur","Instructor")} value={instructorId} onChange={setInstructorId} options={store.state.instructors.map(m => ({ value: m.id, label: m.name }))}/>
      <Select label={t("Type de cours","Lesson type")} value={type} onChange={setType} options={Object.entries(store.state.types).map(([k, ty]) => ({ value: k, label: ty.l }))}/>
      <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
        <Button kind="ghost" onClick={onClose}>{t("Annuler","Cancel")}</Button>
        <Button kind="flame" full onClick={() => onBook({ day, hour, studentId, instructorId, type })}>{t("Réserver","Book")} →</Button>
      </div>
    </Modal>
  );
}

window.GerantApp = GerantApp;
window.PlanningModule = PlanningModule;
Object.assign(window, { HOURS, DAYS_FR, DAYS_EN, DATES });
