// ALPSEREN — Prototype interactif
// Tout-en-un : data, icônes, écrans et router. Pas de toggle, anthracite définitif.

const { useState, useEffect, useRef, useMemo } = React;

// ═══════════════════════════════════════════════════════════════════════════
// DATA
// ═══════════════════════════════════════════════════════════════════════════

const INTERVENTIONS = [
  { id: "iv1", day: "AUJOURD'HUI · LUNDI 11 MAI", dayKey: "today",   date: "Lundi 11 mai", time: "09:30", svc: "Ménage hebdomadaire", who: "Sofia M.", org: "Maison Blanche", dur: "3 h", status: 2, note: "Sofia connaît les particularités de la cave à vins. Aucune attention spécifique requise aujourd'hui." },
  { id: "iv2", day: "AUJOURD'HUI · LUNDI 11 MAI", dayKey: "today",   date: "Lundi 11 mai", time: "14:00", svc: "Livraison cave",       who: "Caves de Genève", org: "Bordeaux × 12", dur: "45 min", status: 1, note: null },
  { id: "iv3", day: "DEMAIN · MARDI 12 MAI",      dayKey: "tomorrow",date: "Mardi 12 mai", time: "11:00", svc: "Jardinage",            who: "Marco V.", org: "Vert & Vivant", dur: "2 h", status: 0, note: "Tailler les buis côté terrasse. Marco a déjà la clé du portail latéral." },
  { id: "iv4", day: "MERCREDI 13 MAI",            dayKey: "wed",     date: "Mercredi 13 mai", time: "08:00", svc: "Contrôle piscine", who: "AquaPro", org: "Genève", dur: "1 h", status: 0, note: null },
  { id: "iv5", day: "MERCREDI 13 MAI",            dayKey: "wed",     date: "Mercredi 13 mai", time: "16:30", svc: "Pressing — collecte", who: "Maison Blanche", org: "Linge fin", dur: "20 min", status: 0, note: null },
  { id: "iv6", day: "JEUDI 14 MAI",               dayKey: "thu",     date: "Jeudi 14 mai", time: "10:00", svc: "Fleurs fraîches",     who: "Atelier Fleur", org: "Bouquet hebdo", dur: "30 min", status: 0, note: null },
];

const STATUS_STEPS = ["Planifiée", "Confirmée", "En cours", "Terminée"];

const INITIAL_MESSAGES = [
  { id: "m1", day: "HIER", who: "them", text: "Bonsoir Madame Verdier, votre commande de la cave a bien été préparée. Livraison demain à 14 h.", sig: true },
  { id: "m2", day: "HIER", who: "me",   text: "Parfait, je vous remercie." },
  { id: "m3", day: "AUJOURD'HUI · 11 MAI", who: "them", text: "Sofia est arrivée à 09:28. Tout se déroule normalement.", sig: true },
  { id: "m4", day: "AUJOURD'HUI · 11 MAI", who: "me",   text: "Merci pour le suivi." },
  { id: "m5", day: "AUJOURD'HUI · 11 MAI", who: "them", text: "Souhaitez-vous que je programme le pressing pour jeudi ou vendredi ?", sig: true },
];

const INITIAL_DEMANDES = [
  { id: "d1", title: "Réservation Beau-Rivage · dimanche 17 mai", date: "11 MAI", status: "Confirmée" },
  { id: "d2", title: "Service de chauffeur · jeudi soir",          date: "11 MAI", status: "En attente" },
  { id: "d3", title: "Fleurs fraîches hebdomadaires",               date: "10 MAI", status: "Traitée" },
  { id: "d4", title: "Nettoyage tapis salon",                       date: "08 MAI", status: "Traitée" },
];

const CATEGORIES = ["Maison", "Voyage", "Restaurant", "Transport", "Cadeau", "Autre"];

// ═══════════════════════════════════════════════════════════════════════════
// ICONS (one-line, neutral)
// ═══════════════════════════════════════════════════════════════════════════

const Icon = ({ d, size = 22, w = 1.5 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth={w} strokeLinecap="round" strokeLinejoin="round">
    <path d={d} />
  </svg>
);

const IconBack    = () => <Icon d="M15 5 L8 12 L15 19" />;
const IconClose   = () => <Icon d="M6 6 L18 18 M18 6 L6 18" />;
const IconMessage = () => <Icon d="M4 6 h16 v11 h-9 l-4 3 v-3 H4 z" />;
const IconChev    = () => <Icon size={16} d="M9 6 L15 12 L9 18" />;
const IconSend    = () => <Icon size={18} d="M3 12 L21 4 L13 22 L11 13 Z" />;
const IconPlus    = () => <Icon size={24} d="M12 5 V19 M5 12 H19" />;
const IconPhone   = () => <Icon size={18} d="M5 5 c0 8 6 14 14 14 l1-4 -5-2 -2 2 c-3-1-5-3-6-6 l2-2 -2-5 z" />;

const TabIcon = ({ kind }) => {
  if (kind === "agenda")
    return <Icon d="M5 7 h14 v12 h-14 z M5 11 h14 M9 4 v4 M15 4 v4" />;
  if (kind === "messages")
    return <Icon d="M4 7 h16 v10 h-9 l-4 3 v-3 H4 z" />;
  if (kind === "demandes")
    return <Icon d="M6 5 h12 v14 h-12 z M9 9 h6 M9 12 h6 M9 15 h4" />;
  if (kind === "profil")
    return <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="9" r="3" /><path d="M5 20 c1-4 5-6 7-6 s6 2 7 6" /></svg>;
  return null;
};

// ═══════════════════════════════════════════════════════════════════════════
// SHELL : Phone frame + nav primitives
// ═══════════════════════════════════════════════════════════════════════════

function StatusBar() {
  return (
    <div className="status">
      <span>9:41</span>
      <div className="right">
        <span className="ind"></span>
        <span className="ind"></span>
        <span className="ind dim"></span>
      </div>
    </div>
  );
}

function Header({ left, title, right }) {
  return (
    <div className="h">
      <div>{left || <span style={{ width: 36 }}></span>}</div>
      <div className="title">{title}</div>
      <div>{right || <span style={{ width: 36 }}></span>}</div>
    </div>
  );
}

function IconBtn({ onClick, children, ariaLabel }) {
  return (
    <button type="button" className="icon-btn click-target" aria-label={ariaLabel} onClick={onClick}>
      {children}
    </button>
  );
}

function TabBar({ active, onChange }) {
  const tabs = [
    { k: "agenda",   label: "Agenda" },
    { k: "messages", label: "Messages" },
    { k: "demandes", label: "Demandes" },
    { k: "profil",   label: "Profil" },
  ];
  return (
    <nav className="tabs">
      {tabs.map(t => (
        <button key={t.k} type="button"
                className={"tab click-target" + (active === t.k ? " active" : "")}
                onClick={() => onChange(t.k)}>
          <TabIcon kind={t.k} />
          <span>{t.label}</span>
        </button>
      ))}
    </nav>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// AGENDA
// ═══════════════════════════════════════════════════════════════════════════

function AgendaScreen({ onSelectIv, onTab }) {
  // Group interventions by day
  const days = useMemo(() => {
    const out = [];
    const seen = new Map();
    for (const iv of INTERVENTIONS) {
      if (!seen.has(iv.day)) {
        seen.set(iv.day, { day: iv.day, items: [] });
        out.push(seen.get(iv.day));
      }
      seen.get(iv.day).items.push(iv);
    }
    return out;
  }, []);

  return (
    <div className="screen">
      <Header title="Agenda" right={<span className="mono">SEM 19</span>} />
      <div className="body">
        {days.map(d => (
          <div key={d.day}>
            <div className="date-row">
              <span className="lbl">{d.day}</span>
              <span className="line"></span>
            </div>
            {d.items.map(iv => (
              <div key={iv.id} className="iv click-target" onClick={() => onSelectIv(iv.id)}>
                <div className="time">{iv.time}</div>
                <div className="meta">
                  <span className="svc">{iv.svc}</span>
                  <span className="sub">{iv.who} · {iv.dur}</span>
                </div>
                <div className="chev"><IconChev /></div>
              </div>
            ))}
          </div>
        ))}
      </div>
      <TabBar active="agenda" onChange={onTab} />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// DETAIL INTERVENTION
// ═══════════════════════════════════════════════════════════════════════════

function DetailScreen({ ivId, onBack, onOpenMessages }) {
  const iv = INTERVENTIONS.find(x => x.id === ivId) || INTERVENTIONS[0];
  const initials = iv.who.split(" ").map(w => w[0]).slice(0, 2).join("");

  return (
    <div className="screen">
      <Header
        left={<IconBtn ariaLabel="Retour" onClick={onBack}><IconBack /></IconBtn>}
        title=""
        right={<IconBtn ariaLabel="Messages" onClick={onOpenMessages}><IconMessage /></IconBtn>}
      />
      <div className="body">
        <div className="dtl-hero">
          <div className="date">{iv.date}</div>
          <div className="time">{iv.time}</div>
          <div className="svc">{iv.svc}</div>
        </div>

        <div className="tl">
          {STATUS_STEPS.map((step, i, arr) => {
            const cls = i < iv.status ? "done" : i === iv.status ? "now" : "";
            return (
              <React.Fragment key={step}>
                <div className={"step " + cls}>
                  <span className="dot"></span>
                  <span className="lbl">{step}</span>
                </div>
                {i < arr.length - 1 && (
                  <span className={"seg" + (i < iv.status ? " done" : "")}></span>
                )}
              </React.Fragment>
            );
          })}
        </div>

        <div className="section">
          <div className="head">Prestataire</div>
          <div className="prest-row">
            <span className="av">{initials}</span>
            <div className="meta">
              <div className="name">{iv.who}</div>
              <div className="org">{iv.org} · {iv.dur}</div>
            </div>
            <button type="button" className="contact click-target">
              <IconPhone />
            </button>
          </div>
        </div>

        {iv.note && (
          <div className="section">
            <div className="head">Note</div>
            <div className="note">
              {iv.note}
              <span className="sig">— Benjamin · ALPSEREN</span>
            </div>
          </div>
        )}

        <div className="section">
          <div className="head">Photos</div>
          <div className="placeholder">
            <div className="txt">
              Les photos seront ajoutées<br />à l'issue de l'intervention.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// MESSAGES
// ═══════════════════════════════════════════════════════════════════════════

function MessagesScreen({ messages, onSend, onTab }) {
  const [draft, setDraft] = useState("");
  const bodyRef = useRef(null);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages.length]);

  const handleSend = (e) => {
    e.preventDefault();
    const t = draft.trim();
    if (!t) return;
    onSend(t);
    setDraft("");
  };

  // Group by day separator
  const groups = [];
  let currentDay = null;
  for (const m of messages) {
    if (m.day !== currentDay) {
      groups.push({ day: m.day, items: [] });
      currentDay = m.day;
    }
    groups[groups.length - 1].items.push(m);
  }

  return (
    <div className="screen">
      <Header title="Messages" />
      <div className="body" ref={bodyRef} style={{ paddingBottom: 96 }}>
        {groups.map((g, gi) => (
          <div key={gi}>
            <div className="day-sep">
              <span className="line"></span>
              <span className="lbl">{g.day}</span>
              <span className="line"></span>
            </div>
            {g.items.map(m => (
              <div key={m.id} className={"bub " + m.who}>
                {m.text}
                {m.sig && <span className="sig">Benjamin · Alpseren</span>}
              </div>
            ))}
          </div>
        ))}
      </div>
      <form className="composer" onSubmit={handleSend}>
        <input
          type="text"
          placeholder="Votre message à Benjamin…"
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
        />
        <button type="submit" className="send click-target" disabled={!draft.trim()} aria-label="Envoyer">
          <IconSend />
        </button>
      </form>
      <TabBar active="messages" onChange={onTab} />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// DEMANDES
// ═══════════════════════════════════════════════════════════════════════════

function StatusPill({ s }) {
  const cls = s === "Confirmée" ? "confirmed" : s === "Traitée" ? "treated" : "";
  return (
    <span className={"pill " + cls}>
      <span className="led"></span>
      {s}
    </span>
  );
}

function DemandesScreen({ demandes, onNew, onTab }) {
  return (
    <div className="screen">
      <Header title="Demandes" />
      <div className="body">
        {demandes.map(d => (
          <div key={d.id} className="dem-card click-target">
            <div className="top">
              <span className="mono">{d.date}</span>
              <StatusPill s={d.status} />
            </div>
            <div className="ttl">{d.title}</div>
          </div>
        ))}
      </div>
      <button type="button" className="fab click-target" onClick={onNew} aria-label="Nouvelle demande">
        <IconPlus />
      </button>
      <TabBar active="demandes" onChange={onTab} />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// NOUVELLE DEMANDE
// ═══════════════════════════════════════════════════════════════════════════

function NewDemandeScreen({ onCancel, onSubmit }) {
  const [cat, setCat] = useState("Maison");
  const [when, setWhen] = useState("");
  const [text, setText] = useState("");
  const canSubmit = text.trim().length > 4;

  return (
    <div className="screen">
      <Header
        left={<IconBtn ariaLabel="Retour" onClick={onCancel}><IconBack /></IconBtn>}
        title="Nouvelle demande"
        right={<IconBtn ariaLabel="Fermer" onClick={onCancel}><IconClose /></IconBtn>}
      />
      <div className="body">
        <div className="section">
          <div className="head">Catégorie</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {CATEGORIES.map(c => (
              <button key={c} type="button"
                      className={"chip click-target" + (cat === c ? " on" : "")}
                      onClick={() => setCat(c)}>
                {c}
              </button>
            ))}
          </div>
        </div>

        <div className="section">
          <div className="head">Quand</div>
          <input
            type="text" className="field"
            placeholder="Dimanche 17 mai — soirée"
            value={when}
            onChange={(e) => setWhen(e.target.value)}
          />
        </div>

        <div className="section">
          <div className="head">Demande</div>
          <textarea
            className="field" rows={5}
            placeholder="Décrivez votre demande à Benjamin…"
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
          <div className="mono" style={{ marginTop: 8, fontSize: 9.5 }}>
            Benjamin répond habituellement sous 1 h.
          </div>
        </div>

        <button type="button"
                className="cta click-target"
                disabled={!canSubmit}
                style={{ opacity: canSubmit ? 1 : 0.45, cursor: canSubmit ? "pointer" : "not-allowed" }}
                onClick={() => onSubmit({ cat, when, text })}>
          Envoyer à Benjamin
        </button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// PROFIL
// ═══════════════════════════════════════════════════════════════════════════

function ProfilScreen({ lang, onLang, onTab }) {
  const [notifAvis, setNotifAvis] = useState(true);
  const [notifMsg, setNotifMsg] = useState(true);
  const [notifWeek, setNotifWeek] = useState(false);
  const [faceId, setFaceId] = useState(true);

  return (
    <div className="screen">
      <Header title="Profil" />
      <div className="body">
        <div className="profile-hero">
          <span className="av-lg">CV</span>
          <div className="name">Claire Verdier</div>
          <div className="sub">Cologny · Cliente depuis 2023</div>
        </div>

        <div className="section">
          <div className="head">Langue</div>
          <div className="row no-tap">
            <span className="k">Affichage de l'application</span>
            <div className="toggle">
              <button type="button" className={lang === "fr" ? "on" : ""} onClick={() => onLang("fr")}>FR</button>
              <button type="button" className={lang === "en" ? "on" : ""} onClick={() => onLang("en")}>EN</button>
            </div>
          </div>
        </div>

        <div className="section">
          <div className="head">Notifications</div>
          <div className="row no-tap">
            <span className="k">Interventions à venir</span>
            <div className={"switch click-target" + (notifAvis ? " on" : "")} onClick={() => setNotifAvis(v => !v)}></div>
          </div>
          <div className="row no-tap">
            <span className="k">Messages de Benjamin</span>
            <div className={"switch click-target" + (notifMsg ? " on" : "")} onClick={() => setNotifMsg(v => !v)}></div>
          </div>
          <div className="row no-tap">
            <span className="k">Récapitulatif hebdomadaire</span>
            <div className={"switch click-target" + (notifWeek ? " on" : "")} onClick={() => setNotifWeek(v => !v)}></div>
          </div>
        </div>

        <div className="section">
          <div className="head">Confidentialité</div>
          <div className="row no-tap">
            <span className="k">Face ID</span>
            <div className={"switch click-target" + (faceId ? " on" : "")} onClick={() => setFaceId(v => !v)}></div>
          </div>
          <div className="row"><span className="k">Code d'accès</span><span className="v">›</span></div>
        </div>

        <div className="section">
          <div className="head">Support</div>
          <div className="row"><span className="k">Contacter Benjamin</span><span className="v">›</span></div>
          <div className="row"><span className="k">Conditions · Confidentialité</span><span className="v">›</span></div>
        </div>

        <div style={{
          textAlign: "center", padding: "20px 0 0",
          fontFamily: "var(--f-sys)", fontWeight: 500,
          fontSize: 10, letterSpacing: ".22em", textTransform: "uppercase",
          color: "var(--cream-50)", cursor: "pointer",
        }} className="click-target">
          Se déconnecter
        </div>
      </div>
      <TabBar active="profil" onChange={onTab} />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// TOAST (envoi message / demande envoyée)
// ═══════════════════════════════════════════════════════════════════════════

function Toast({ text }) {
  if (!text) return null;
  return (
    <div style={{
      position: "absolute", left: "50%", bottom: 110,
      transform: "translateX(-50%)",
      padding: "10px 18px",
      background: "rgba(20,17,14,.92)",
      backdropFilter: "blur(20px)",
      border: "1px solid var(--beige-edge)",
      borderRadius: 999,
      fontFamily: "var(--f-sys)", fontWeight: 500,
      fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase",
      color: "var(--beige)",
      zIndex: 20,
      whiteSpace: "nowrap",
      animation: "toast-in .25s cubic-bezier(.2,.7,.3,1)",
    }}>
      {text}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// APP (router)
// ═══════════════════════════════════════════════════════════════════════════

function App() {
  const [tab, setTab] = useState("agenda");
  const [view, setView] = useState("agenda"); // agenda | detail | messages | demandes | newDemande | profil
  const [selectedIv, setSelectedIv] = useState(null);
  const [messages, setMessages] = useState(INITIAL_MESSAGES);
  const [demandes, setDemandes] = useState(INITIAL_DEMANDES);
  const [lang, setLang] = useState("fr");
  const [toast, setToast] = useState("");

  const showToast = (t) => {
    setToast(t);
    setTimeout(() => setToast(""), 1800);
  };

  const goTab = (k) => { setTab(k); setView(k); };

  const handleSelectIv = (id) => {
    setSelectedIv(id);
    setView("detail");
  };

  const handleSend = (text) => {
    setMessages(prev => {
      const last = prev[prev.length - 1];
      const day = last ? last.day : "AUJOURD'HUI · 11 MAI";
      const next = [...prev, { id: "m" + Date.now(), day, who: "me", text }];
      // Benjamin réponse automatique
      setTimeout(() => {
        setMessages(p => [...p, {
          id: "m" + Date.now() + 1, day, who: "them",
          text: "Bien noté, Madame Verdier. Je reviens vers vous très rapidement.",
          sig: true,
        }]);
      }, 1400);
      return next;
    });
  };

  const handleNewDemande = (payload) => {
    const newDem = {
      id: "d" + Date.now(),
      title: payload.text.slice(0, 80),
      date: "AUJ.",
      status: "En attente",
    };
    setDemandes(prev => [newDem, ...prev]);
    setView("demandes");
    setTab("demandes");
    showToast("Demande envoyée");
  };

  // Render the current view (tab-screens have TabBar; sub-views don't but use shared shell)
  let screen = null;
  if (view === "agenda") {
    screen = <AgendaScreen onSelectIv={handleSelectIv} onTab={goTab} />;
  } else if (view === "detail") {
    screen = <DetailScreen
      ivId={selectedIv}
      onBack={() => { setView(tab); }}
      onOpenMessages={() => { setView("messages"); setTab("messages"); }}
    />;
  } else if (view === "messages") {
    screen = <MessagesScreen messages={messages} onSend={handleSend} onTab={goTab} />;
  } else if (view === "demandes") {
    screen = <DemandesScreen
      demandes={demandes}
      onNew={() => setView("newDemande")}
      onTab={goTab}
    />;
  } else if (view === "newDemande") {
    screen = <NewDemandeScreen
      onCancel={() => { setView("demandes"); setTab("demandes"); }}
      onSubmit={handleNewDemande}
    />;
  } else if (view === "profil") {
    screen = <ProfilScreen lang={lang} onLang={setLang} onTab={goTab} />;
  }

  return (
    <div className="stage">
      <style>{`
        @keyframes toast-in {
          from { opacity: 0; transform: translateX(-50%) translateY(10px); }
          to   { opacity: 1; transform: translateX(-50%) translateY(0); }
        }
      `}</style>
      <div className="phone">
        <div className="notch"></div>
        <StatusBar />
        <ScreenSlot view={view}>{screen}</ScreenSlot>
        <Toast text={toast} />
        <div className="home-bar"></div>
      </div>

      <div className="legend">
        <span className="brand">ALPSEREN</span>
        <span className="sub">Prototype interactif · v 0.1</span>
      </div>
    </div>
  );
}

// Crossfade screens for a softer transition
function ScreenSlot({ view, children }) {
  const [prev, setPrev] = useState({ view, node: children });
  const [active, setActive] = useState({ view, node: children });
  const firstRef = useRef(true);

  useEffect(() => {
    if (firstRef.current) {
      firstRef.current = false;
      setActive({ view, node: children });
      return;
    }
    if (view !== active.view) {
      setPrev(active);
      setActive({ view, node: children });
      const t = setTimeout(() => setPrev(null), 280);
      return () => clearTimeout(t);
    } else {
      // Same view but content changed (e.g. messages updated) — just replace
      setActive({ view, node: children });
    }
  }, [view, children]);

  return (
    <div style={{ position: "absolute", inset: 0 }}>
      {prev && (
        <div key={"prev-" + prev.view} style={{
          position: "absolute", inset: 0,
          animation: "screen-out .28s cubic-bezier(.2,.7,.3,1) forwards",
        }}>
          {prev.node}
        </div>
      )}
      <div key={"cur-" + active.view} style={{
        position: "absolute", inset: 0,
        animation: prev ? "screen-in .28s cubic-bezier(.2,.7,.3,1)" : "none",
      }}>
        {active.node}
      </div>
      <style>{`
        @keyframes screen-in {
          from { opacity: 0; transform: translateY(8px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes screen-out {
          from { opacity: 1; transform: translateY(0); }
          to   { opacity: 0; transform: translateY(-4px); }
        }
      `}</style>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
