/* ShiftBud — main app: calendar (day roster) + sidebar, status colors, coverage, i18n */
/* eslint-disable */
const { useState: uS } = React;
const T = (k, p) => window.SBI.t(k, p);
const DOW = (d) => window.SBI.dow(d);
const MONTH = () => window.SBI.month();

/* ── Error boundary — shows crash details instead of blank screen ── */
class ErrorBoundary extends React.Component {
  constructor(p) { super(p); this.state = { err: null }; }
  static getDerivedStateFromError(e) { return { err: e }; }
  render() {
    if (!this.state.err) return this.props.children;
    return (
      <div style={{ padding: 32, fontFamily: "monospace", background: "#fff8f8", color: "#c0392b",
                    border: "2px solid #f5c6cb", borderRadius: 12, margin: 24 }}>
        <strong>ShiftBud Error</strong>
        <pre style={{ marginTop: 12, whiteSpace: "pre-wrap", fontSize: 13 }}>
          {this.state.err.message}{"\n\n"}{this.state.err.stack}
        </pre>
        <button onClick={() => this.setState({ err: null })}
          style={{ marginTop: 12, padding: "8px 16px", background: "#c0392b", color: "#fff",
                   border: "none", borderRadius: 6, cursor: "pointer" }}>
          Retry
        </button>
      </div>
    );
  }
}

const GROUPS = [
{ id: "all", label: "f_all", roles: null },
{ id: "foh", label: "f_foh", roles: ["Server", "Host", "Barista"] },
{ id: "kitchen", label: "f_kitchen", roles: ["Head Chef", "Cook", "Dishwasher"] },
{ id: "mgmt", label: "f_mgmt", roles: ["Manager"] }];


/* ---------- Sidebar (menu band) ---------- */
function Sidebar({ view, setView, conflicts, onAccount, restaurantName, ownerName }) {
  const items = [
  { id: "calendar", label: "nav_calendar", icon: "calendar" },
  { id: "coverage", label: "nav_coverage", icon: "grid" },
  { id: "team", label: "nav_team", icon: "users" },
  { id: "inbox", label: "nav_inbox", icon: "chat", badge: conflicts },
  { id: "settings", label: "nav_settings", icon: "settings" }];

  const me = SB.staffById(1) || { name: ownerName || restaurantName || "Owner", role: "owner", id: 0 };
  return (
    <aside className="ap-side">
      <div className="ap-brand">
        <span className="ap-logo" style={{ background: "none", padding: 0 }}>
          <ShiftBudIcon size={48} />
        </span>
        <div>
          <div className="ap-brand-name display">ShiftBud</div>
          <div className="ap-brand-sub">{restaurantName}</div>
        </div>
      </div>
      <nav className="ap-nav">
        {items.map((it) =>
        <button key={it.id} className={"ap-navitem" + (view === it.id ? " active" : "")} onClick={() => setView(it.id)}>
            <Icon name={it.icon} /><span>{T(it.label)}</span>
            {it.badge ? <span className="ap-navbadge">{it.badge}</span> : null}
          </button>
        )}
      </nav>
      <div className="ap-side-foot">
        <button className={"ap-navitem ap-help-item" + (view === "help" ? " active" : "")} onClick={() => setView("help")}>
          <Icon name="help" /><span>{T("nav_help")}</span>
        </button>
        <div className="ap-me">
          <Avatar staff={me} size={38} mono dot />
          <div style={{ minWidth: 0 }}>
            <div className="ap-me-name">{me.name}</div>
            <div className="ap-me-role">{T("owner_role")}</div>
          </div>
          <button className="icon-btn ap-me-btn" title={T("account_menu")} onClick={onAccount}><Icon name="settings" /></button>
        </div>
      </div>
    </aside>);

}

/* ---------- Topbar ---------- */
function Topbar({ title, sub, covStatus, conflicts, onAdd, weekly, onPrev, onNext, onToday, thisWeek }) {
  const chipClass = { ok: " ok", gaps: " warn", none: " bad", closed: " muted" }[covStatus.state] || " warn";
  return (
    <header className="ap-top">
      <div className="ap-weeknav">
        {weekly && <button className="ap-navarrow" title={T("prev_week")} onClick={onPrev}><Icon name="arrowR" style={{ transform: "rotate(180deg)" }} /></button>}
        <div className="ap-weekrange">
          <span className="eyebrow">{sub}</span>
          <span className="display ap-title">{title}</span>
        </div>
        {weekly && !thisWeek && <button className="ap-today-btn" title={T("this_week_tag")} onClick={onToday}>{T("today")}</button>}
        {weekly && <button className="ap-navarrow" title={T("next_week")} onClick={onNext}><Icon name="arrowR" /></button>}
      </div>
      <div className="row gap10">
        <div className={"ap-chip" + chipClass}>
          <span className="dotc" /><span>{covStatus.label}</span>
        </div>
        {conflicts > 0 && <div className="ap-chip bad"><Icon name="alert" style={{ width: 15, height: 15 }} /><span className="mono">{conflicts}</span><span>{T("conflicts")}</span></div>}
        <button className="btn btn-primary" onClick={onAdd}><Icon name="plus" />{T("add_shift")}</button>
      </div>
    </header>);

}

/* ---------- Legend ---------- */
function StatusLegend() {
  return (
    <div className="sb-legend">
      <span><i style={{ background: "var(--st-green)" }} />{T("lg_confirmed")}</span>
      <span><i style={{ background: "var(--st-orange)" }} />{T("lg_pending")}</span>
      <span><i style={{ background: "var(--st-red)" }} />{T("lg_conflict")}</span>
    </div>);

}

/* ---------- General message alert ---------- */
function GeneralMsgAlert({ msg, onDismiss }) {
  const staff = SB.staffById(msg.staff_id) || { name: msg.staff_name, color: "#888" };
  const time = msg.created_at ? new Date(msg.created_at).toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" }) : "";
  return (
    <div className="alert-item">
      <div className="alert-ico" style={{ background: "var(--green-mist)", color: "var(--green)" }}>
        <Icon name="chat" />
      </div>
      <div className="alert-body">
        <div className="at">{T("msg_from_staff")}</div>
        <div className="ad"><strong>{staff.name}</strong>: "{msg.body}"</div>
        <div className="alert-meta">{time} via WhatsApp</div>
        <div className="row gap8" style={{ marginTop: 10 }}>
          <button className="btn btn-ghost btn-sm" onClick={() => onDismiss(msg.id)}>
            <Icon name="check" />{T("msg_acknowledge")}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Today rail (conflicts + who's on) ---------- */
function TodayRail({ store, now }) {
  const onNow = now.dayIndex == null ? [] : store.shifts.filter((s) => s.week === 0 && s.day === now.dayIndex && s.status !== "cancelled" && s.start <= now.hour && s.end > now.hour).sort((a, b) => a.end - b.end);
  return (
    <aside className="ap-rail">
      <div className="ap-railcard">
        <div className="row between" style={{ marginBottom: 12 }}>
          <span className="ap-railtitle">{T("on_floor")}</span>
          <span className="mono ap-clock">{now.hhmm}</span>
        </div>
        {onNow.length === 0 && <div className="ap-clear" style={{ color: "var(--muted)" }}><Icon name="clock" /> {T("now_empty")}</div>}
        <div className="col" style={{ gap: 9 }}>
          {onNow.map((s) => {
            const st = SB.staffById(s.staffId) || { name: "?", color: "#aaa", id: s.staffId };
            return (
              <div key={s.id} className="row gap10">
                <Avatar staff={st} size={30} mono dot />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="ap-rn-name">{st.name}</div>
                  <div className="role-tag">{st.role}</div>
                </div>
                <span className="mono ap-rn-time">{T("till", { t: SB.fmtHour(s.end) })}</span>
              </div>);

          })}
        </div>
      </div>

      <div className="ap-railcard ap-conflicts">
        <div className="row between" style={{ marginBottom: 12 }}>
          <span className="ap-railtitle">{T("conflicts_res")}</span>
          {(store.alerts.length + (store.generalMsgs || []).length) > 0 &&
            <span className="badge st-cancelled">{store.alerts.length + (store.generalMsgs || []).length}</span>}
        </div>
        {store.alerts.length === 0 && (store.generalMsgs || []).length === 0 &&
          <div className="ap-clear"><Icon name="sparkle" /> {T("all_resolved")}</div>}
        <div className="col" style={{ gap: 9 }}>
          {(store.generalMsgs || []).map((m) =>
            <GeneralMsgAlert key={"gm-" + m.id} msg={m} onDismiss={store.dismissGeneralMsg} />
          )}
          {store.alerts.map((a) =>
          <AlertItem key={a.id} alert={a} onCover={store.coverShift} onDismiss={store.dismissAlert}
          onSwap={store.swapShifts} onDeclineSwap={store.declineSwap} shifts={store.shifts}
          unavail={store.unavail}
          candidates={coverCandidates(store.shifts, a.day, a.staffId)} />
          )}
        </div>
      </div>
    </aside>);

}

/* ---------- Publish confirmation modal ---------- */
function PublishConfirmModal({ drafts, onConfirm, onClose }) {
  const staffNames = [...new Set(drafts.map((s) => {
    const st = SB.staffById(s.staffId);
    return st ? st.name.split(" ")[0] : "?";
  }))];
  return (
    <Modal title={T("publish_confirm_title")} onClose={onClose}
      foot={<>
        <button className="btn btn-ghost" onClick={onClose}>{T("cancel")}</button>
        <button className="btn btn-primary" onClick={onConfirm}>
          <Icon name="chat" />{T("publish_confirm_btn", { n: drafts.length })}
        </button>
      </>}>
      <div className="modal-body">
        <p style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.55 }}>
          {T("publish_confirm_body", { n: drafts.length })}
        </p>
        <div style={{ background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 10, padding: "10px 14px", display: "flex", flexWrap: "wrap", gap: 7 }}>
          {staffNames.map((name) => (
            <span key={name} style={{ fontSize: 13, fontWeight: 600, background: "var(--green-mist)", color: "var(--green-deep)", borderRadius: 20, padding: "3px 10px" }}>{name}</span>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: "var(--muted)" }}>
          <Icon name="chat" style={{ width: 14, height: 14, flexShrink: 0 }} />
          {T("publish_confirm_note")}
        </div>
      </div>
    </Modal>
  );
}

/* ---------- Delete week confirmation modal ---------- */
function DeleteWeekModal({ weekLabel, onConfirm, onClose }) {
  return (
    <Modal title={T("del_week")} onClose={onClose}
      foot={<>
        <button className="btn btn-ghost" onClick={onClose}>{T("cancel")}</button>
        <button className="btn btn-danger" onClick={onConfirm}><Icon name="trash" />{T("delete")}</button>
      </>}>
      <div className="modal-body">
        <div className="del-warn">
          <span className="del-warn-ico"><Icon name="trash" /></span>
          <div>{T("del_week_body", { label: weekLabel })}</div>
        </div>
      </div>
    </Modal>
  );
}

/* ---------- Calendar view ---------- */
function CalendarView({ store, openShift, weekDays, now, weekLabel }) {
  const [group, setGroup] = uS("all");
  const [confirmPublish, setConfirmPublish] = uS(false);
  const [confirmDeleteWeek, setConfirmDeleteWeek] = uS(false);
  const [aiPlanning, setAiPlanning] = uS(false);
  const [aiResult, setAiResult] = uS(null);

  const runAiPlan = async () => {
    const targetOffset = store.weekOffset; // einmalig speichern — closure-sicher
    setAiPlanning(true);
    setAiResult(null);
    try {
      // 1. Job starten — antwortet sofort mit job_id
      const r = await fetch(`/api/planning/generate?week_offset=${targetOffset}`, {
        method: "POST", credentials: "include",
      });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      const { job_id } = await r.json();

      // 2. Pollen bis fertig (alle 3 Sekunden, max. 45 Sekunden = 15 Versuche)
      for (let i = 0; i < 15; i++) {
        await new Promise(res => setTimeout(res, 3000));
        try {
          const sr = await fetch(`/api/planning/status/${job_id}`, { credentials: "include" });
          if (!sr.ok) continue; // 502 etc. → weiter warten
          const job = await sr.json();
          if (job.status === "done") {
            setAiResult(job.summary || T("ai_plan_created"));
            await store.loadShifts(targetOffset);
            return;
          }
          if (job.status === "error") {
            setAiResult("Fehler: " + (job.summary || "Unbekannter Fehler"));
            await store.loadShifts(targetOffset);
            return;
          }
        } catch (_) { continue; } // Netzwerkfehler beim Pollen → weiter warten
      }
      setAiResult(T("ai_timeout"));
      await store.loadShifts(targetOffset);
    } catch (e) {
      console.error("runAiPlan", e);
      // Auch bei Fehler Schichten neu laden — könnten bereits erstellt sein
      await store.loadShifts(targetOffset);
      setAiResult(T("ai_maybe_created"));
    } finally {
      setAiPlanning(false);
    }
  };
  const cats = store.categories;
  const validIds = ["all", ...cats.map((c) => c.id)];
  const active = validIds.includes(group) ? group : "all";
  const weekShifts = store.shifts.filter((s) => s.week === store.weekOffset);
  const filtered = active === "all" ? weekShifts : weekShifts.filter((s) => s.category === active);
  const drafts = filtered.filter((s) => s.draft);
  const onDelete = (s) => {if (window.__SB_reqDelete) window.__SB_reqDelete(s);};
  return (
    <div className="ap-cal fade-in">
      {confirmPublish && (
        <PublishConfirmModal
          drafts={drafts}
          onClose={() => setConfirmPublish(false)}
          onConfirm={() => { store.sendAllDrafts(store.weekOffset); setConfirmPublish(false); }}
        />
      )}
      {confirmDeleteWeek && (
        <DeleteWeekModal
          weekLabel={weekLabel}
          onClose={() => setConfirmDeleteWeek(false)}
          onConfirm={() => { store.deleteWeek(store.weekOffset); setConfirmDeleteWeek(false); }}
        />
      )}
      <main className="ap-cal-main">
        <div className="ap-strip">
          <div className="ap-filters">
            <button className={"ap-fchip" + (active === "all" ? " active" : "")} onClick={() => setGroup("all")}>{T("f_all")}</button>
            {cats.map((c) =>
            <button key={c.id} className={"ap-fchip" + (active === c.id ? " active" : "")} onClick={() => setGroup(c.id)}>{c.label}</button>
            )}
          </div>
          <div className="row gap10">
            {store.weekOffset >= 0 && (
              <button className="btn btn-ghost btn-sm" onClick={runAiPlan} disabled={aiPlanning}>
                {aiPlanning
                  ? <><span className="ap-spinner" />{T("ai_planning")}</>
                  : <><Icon name="sparkle" />{T("ai_planner")}</>}
              </button>
            )}
            {weekShifts.length > 0 && <button className="btn btn-ghost btn-sm" style={{ color: "var(--st-red)" }} onClick={() => setConfirmDeleteWeek(true)}><Icon name="trash" />{T("del_week")}</button>}
            <StatusLegend />
          </div>
        </div>
        {aiResult && (
          <div className="ap-draftbar" style={{ background: "var(--green-mist)", borderColor: "var(--green-light)" }}>
            <span className="ap-draftbar-t" style={{ color: "var(--green-deep)" }}><Icon name="sparkle" style={{ width: 16, height: 16 }} />{aiResult}</span>
            <button className="btn btn-ghost btn-sm" onClick={() => setAiResult(null)}><Icon name="x" /></button>
          </div>
        )}
        {drafts.length > 0 &&
        <div className="ap-draftbar">
            <span className="ap-draftbar-t"><Icon name="alert" style={{ width: 16, height: 16 }} />{drafts.length === 1 ? T("draft_one") : T("draft_many", { n: drafts.length })}</span>
            <button className="btn btn-primary btn-sm" onClick={() => setConfirmPublish(true)}>
              <Icon name="chat" />{drafts.length === 1 ? T("sendbtn_one") : T("sendbtn_many", { n: drafts.length })}
            </button>
          </div>
        }
        <div className="ap-board ap-board-roster">
          <DayRoster shifts={filtered} weekDays={weekDays} weekdayHours={store.weekdayHours} categories={store.categories}
          onShiftClick={openShift} onSend={store.sendShift} onConfirm={store.confirmShift} onDelete={onDelete}
          draggable onMove={store.moveShift} colorMode="status"
          todayIndex={store.weekOffset === 0 ? now.dayIndex : null}
          nowHour={store.weekOffset === 0 ? now.hour : null}
          broadcastIds={store.broadcastShiftIds}
          customHolidays={store.holidays || []} />
        </div>

      </main>
      <TodayRail store={store} now={now} />
    </div>);

}

/* ---------- Coverage view (staffing heatmap) ---------- */
function heat(n) {
  if (n === 0) return { bg: "#f6d8d3", fg: "#a8281a" };
  if (n === 1) return { bg: "#e4efe3", fg: "#3c6a4d" };
  if (n === 2) return { bg: "#c2e2cb", fg: "#1f6740" };
  if (n === 3) return { bg: "#8fcda4", fg: "#0e5230" };
  if (n === 4) return { bg: "#56b27e", fg: "#fff" };
  return { bg: "#2f9460", fg: "#fff" };
}
function CoverageView({ store, weekDays }) {
  const open = SB.RESTAURANT.openHour,close = SB.RESTAURANT.closeHour;
  const hours = [];for (let h = open; h < close; h++) hours.push(h);
  const weekShifts = store.shifts.filter((s) => s.week === store.weekOffset);
  const headcount = (day, h) => weekShifts.filter((s) => s.day === day && s.status !== "cancelled" && s.start <= h && s.end > h).length;
  const days = weekDays || SB.WEEK;

  let peak = { n: -1 },gaps = [];
  days.forEach((d) => hours.forEach((h) => {
    const n = headcount(d.index, h);
    if (n > peak.n) peak = { n, day: d, h };
    if (n === 0) gaps.push({ day: d, h });
  }));

  return (
    <div className="ap-cov fade-in">
      <div className="ap-cov-insights">
        <div className="ap-ins">
          <div className="ap-ins-ico" style={{ background: "#d6f0e0", color: "var(--st-green)" }}><Icon name="users" /></div>
          <div><div className="ap-ins-big display">{peak.n}</div><div className="ap-ins-lab">{T("peak_head", { d: DOW(peak.day.dow), t: SB.fmtHour(peak.h) })}</div></div>
        </div>
        <div className="ap-ins">
          <div className="ap-ins-ico" style={{ background: "#f6d8d3", color: "var(--st-red)" }}><Icon name="alert" /></div>
          <div><div className="ap-ins-big display">{gaps.length}</div><div className="ap-ins-lab">{T("uncovered", { x: gaps.length ? T("incl", { d: DOW(gaps[0].day.dow), t: SB.fmtHour(gaps[0].h) }) : "" })}</div></div>
        </div>
        <div className="ap-ins">
          <div className="ap-ins-ico" style={{ background: "#fbe6cc", color: "var(--st-orange)" }}><Icon name="clock" /></div>
          <div><div className="ap-ins-big display">{open}:00–{close % 24 === 0 ? "24" : close}:00</div><div className="ap-ins-lab">{T("hours_tracked")}</div></div>
        </div>
      </div>

      <div className="ap-card">
        <div className="ap-cardhead">
          <div><h3 className="display">{T("cs_title")}</h3><span className="role-tag">{T("cs_desc")}</span></div>
          <div className="ap-heatscale">
            <span className="mono">0</span>
            {[0, 1, 2, 3, 4, 5].map((n) => <i key={n} style={{ background: heat(n).bg }} />)}
            <span className="mono">5+</span>
          </div>
        </div>
        <div className="ap-heat" style={{ gridTemplateColumns: "52px repeat(7, 1fr)" }}>
          <div />
          {days.map((d) =>
          <div key={d.index} className={"ap-heat-dh" + (d.isToday ? " today" : "")}>{DOW(d.dow)}<small>{d.num}</small></div>
          )}
          {hours.map((h) =>
          <React.Fragment key={h}>
              <div className="ap-heat-hr mono">{SB.fmtHour(h)}</div>
              {days.map((d) => {
              const n = headcount(d.index, h);
              const c = heat(n);
              return <div key={d.index} className="ap-heat-cell" style={{ background: c.bg, color: c.fg }}>{n > 0 ? n : ""}</div>;
            })}
            </React.Fragment>
          )}
        </div>
      </div>
    </div>);

}

/* ---------- Team view ---------- */
function AddStaffModal({ onClose, onAdd }) {
  const [name, setName] = uS("");
  const [phone, setPhone] = uS("");
  const [role, setRole] = uS("");
  const valid = name.trim() && phone.trim();
  const submit = () => {if (valid) {onAdd({ name: name.trim(), phone: phone.trim(), role: role.trim() || "Staff" });onClose();}};
  return (
    <Modal title={T("as_title")} onClose={onClose}
    foot={<>
        <button className="btn btn-ghost" onClick={onClose}>{T("cancel")}</button>
        <button className="btn btn-primary" onClick={submit} disabled={!valid}><Icon name="userplus" />{T("as_add")}</button>
      </>}>
      <div className="modal-body">
        <div className="field"><label>{T("as_name")}</label><input value={name} onChange={(e) => setName(e.target.value)} placeholder={T("as_name_ph")} autoFocus /></div>
        <div className="field"><label>{T("as_phone")}</label><input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+49 151 0000 000" /></div>
        <div className="field"><label>{T("as_role")}</label>
          <input value={role} onChange={(e) => setRole(e.target.value)} placeholder={T("as_role_ph")} />
        </div>
        <div className="ap-set-d">{T("as_note")}</div>
      </div>
    </Modal>);

}
function TeamView({ store }) {
  const [adding, setAdding] = uS(false);
  const weekHours = (id) => store.shifts.filter((s) => s.staffId === id && s.status !== "cancelled").reduce((a, s) => a + (s.end - s.start), 0);
  const onToday = (id) => store.shifts.some((s) => s.staffId === id && s.day === SB.TODAY_INDEX && s.status !== "cancelled");
  return (
    <div className="ap-pad fade-in">
      <div className="ap-team-head">
        <div><h3 className="display" style={{ fontSize: 18 }}>{T("team_members", { n: SB.STAFF.length })}</h3><span className="role-tag">{T("team_help")}</span></div>
        <button className="btn btn-primary" onClick={() => setAdding(true)}><Icon name="userplus" />{T("add_member")}</button>
      </div>
      <div className="ap-team">
        {SB.STAFF.map((s) =>
        <button key={s.id} className="ap-card ap-staffcard" onClick={() => window.__SB_openMember && window.__SB_openMember(s.id)}>
            <div className="row gap12">
              <Avatar staff={s} size={46} mono dot={onToday(s.id)} />
              <div style={{ minWidth: 0 }}>
                <div className="ap-sc-name">{s.name}</div>
                <div className="role-tag">{s.role}</div>
              </div>
            </div>
            <div className="row gap6 mono ap-sc-phone"><Icon name="phone" style={{ width: 14, height: 14, color: "var(--faint)" }} />{s.phone}</div>
            <div className="ap-sc-foot row between">
              <span className="role-tag">{T("hours_week", { h: weekHours(s.id) })}</span>
              {!s.whatsappInvited
                ? <span className="badge" style={{ background:"#fdf3e0", color:"#92610a", border:"1px solid #e9c46a" }}>📵 Nicht eingeladen</span>
                : onToday(s.id)
                  ? <span className="badge st-confirmed"><span className="dot" />{T("on_today")}</span>
                  : <span className="badge" style={{ background: "var(--bg-deep)", color: "var(--muted)" }}>{T("off")}</span>
              }
            </div>
          </button>
        )}
      </div>
      {adding && <AddStaffModal onClose={() => setAdding(false)} onAdd={store.addStaff} />}
    </div>);

}

/* ---------- Inbox view ---------- */
function InboxView({ store }) {
  return (
    <div className="ap-pad fade-in">
      <div className="ap-inbox">
        <div className="ap-card ap-feed">
          <div className="ap-cardhead"><h3 className="display">{T("recent_wa")}</h3><span className="badge st-confirmed"><span className="dot" />{T("auto_claude")}</span></div>
          <div className="ap-thread scroll-y"><MessageThread messages={store.messages} /></div>
        </div>
        <div className="ap-card ap-conflicts">
          <div className="ap-cardhead"><h3 className="display">{T("action_items")}</h3>{store.alerts.length > 0 && <span className="badge st-cancelled">{store.alerts.length}</span>}</div>
          <div className="col gap10" style={{ padding: "4px 18px 18px" }}>
            {store.alerts.length === 0 && <div className="ap-clear"><Icon name="sparkle" /> {T("inbox_zero")}</div>}
            {store.alerts.map((a) =>
            <AlertItem key={a.id} alert={a} onCover={store.coverShift} onDismiss={store.dismissAlert}
            onSwap={store.swapShifts} onDeclineSwap={store.declineSwap} shifts={store.shifts}
            unavail={store.unavail}
            candidates={coverCandidates(store.shifts, a.day, a.staffId)} />
            )}
          </div>
        </div>
      </div>
    </div>);

}

/* ---------- Settings view ---------- */
function Toggle({ on, onClick }) {
  return <button className={"ap-toggle" + (on ? " on" : "")} onClick={onClick}><span className="ap-knob" /></button>;
}
function SettingsRow({ title, desc, children }) {
  return (
    <div className="ap-setrow">
      <div style={{ flex: 1 }}><div className="ap-set-t">{title}</div>{desc && <div className="ap-set-d">{desc}</div>}</div>
      {children}
    </div>);

}
function LangSwitch({ lang, onLang }) {
  return (
    <div className="ap-seg">
      <button className={"ap-seg-btn" + (lang === "de" ? " active" : "")} onClick={() => onLang("de")}>Deutsch</button>
      <button className={"ap-seg-btn" + (lang === "en" ? " active" : "")} onClick={() => onLang("en")}>English</button>
    </div>);

}
const LANGS = [
{ id: "de", label: "Deutsch", sub: "German" },
{ id: "en", label: "English", sub: "Englisch" }];

function LangPicker({ lang, onLang, onClose }) {
  return (
    <Modal title={T("acc_lang")} onClose={onClose}
    foot={<button className="btn btn-ghost" onClick={onClose}>{T("cancel")}</button>}>
      <div className="modal-body">
        {LANGS.map((l) =>
        <button key={l.id} className={"lang-opt" + (lang === l.id ? " active" : "")}
        onClick={() => {onLang(l.id);onClose();}}>
            <span className="lang-opt-flag"><Icon name="globe" /></span>
            <span style={{ flex: 1, textAlign: "left" }}>
              <span className="lang-opt-t">{l.label}</span>
              <span className="lang-opt-d">{l.sub}</span>
            </span>
            {lang === l.id && <Icon name="check" style={{ width: 18, height: 18, color: "var(--green)" }} />}
          </button>
        )}
      </div>
    </Modal>);

}
function LangMenu({ lang, onLang }) {
  const [open, setOpen] = uS(false);
  const cur = LANGS.find((l) => l.id === lang);
  return (
    <>
      <button className="ap-langrow-btn" onClick={() => setOpen(true)}>
        <span className="ap-langrow-cur">{cur ? cur.label : lang}</span>
        <Icon name="chevR" style={{ width: 16, height: 16, color: "var(--faint)" }} />
      </button>
      {open && <LangPicker lang={lang} onLang={onLang} onClose={() => setOpen(false)} />}
    </>);

}
const HOUR_OPTS = (() => {const a = [];for (let h = 0; h <= 24; h += 0.25) a.push(h);return a;})();
function fmtQuarter(h) {
  const hh = Math.floor(h) % 24 === 0 && h >= 24 ? 24 : Math.floor(h) % 24;
  const mm = Math.round((h - Math.floor(h)) * 60);
  return String(hh).padStart(2, "0") + ":" + String(mm).padStart(2, "0");
}
function HourSelect({ value, onChange }) {
  return (
    <select className="ap-input sm" value={value} onChange={(e) => onChange(+e.target.value)}>
      {HOUR_OPTS.map((h) => <option key={h} value={h}>{fmtQuarter(h)}</option>)}
    </select>);

}
function AddCatInput({ onAdd }) {
  const [v, setV] = uS("");
  const add = () => {if (v.trim()) {onAdd(v.trim());setV("");}};
  return (
    <div className="ap-catadd">
      <input className="ap-input" value={v} placeholder={T("cat_ph")} onChange={(e) => setV(e.target.value)}
      onKeyDown={(e) => {if (e.key === "Enter") add();}} />
      <button className="btn btn-soft btn-sm" onClick={add}><Icon name="plus" />{T("add_cat")}</button>
    </div>);

}
function CategoriesCard({ store }) {
  return (
    <div className="ap-card">
      <div className="ap-cardhead"><div><h3 className="display">{T("s_cats")}</h3><span className="role-tag">{T("s_cats_d")}</span></div></div>
      <div className="ap-setbody">
        <div className="ap-catlist">
          {store.categories.map((c) =>
          <div key={c.id} className="ap-catrow">
              <span className="ap-catdot" />
              <input className="ap-input" value={c.label} onChange={(e) => store.renameCategory(c.id, e.target.value)} />
              <button className="icon-btn ap-catdel" title={T("delete")} onClick={() => store.removeCategory(c.id)}><Icon name="trash" /></button>
            </div>
          )}
        </div>
        <AddCatInput onAdd={store.addCategory} />
      </div>
    </div>);

}
function HoursCard({ store }) {
  return (
    <div className="ap-card">
      <div className="ap-cardhead"><div><h3 className="display">{T("s_hours_tpl")}</h3><span className="role-tag">{T("s_hours_tpl_d")}</span></div></div>
      <div className="ap-setbody">
        {SB.DOW_KEYS.map((dow) =>
        <div key={dow} className="ap-hrow">
            <div className="ap-hrow-day">{DOW(dow)}</div>
            <div className="ap-hrow-blocks">
              {store.weekdayHours[dow].map((b, i) =>
            <div key={i} className="ap-block">
                  <HourSelect value={b.start} onChange={(v) => store.setDayBlock(dow, i, { start: v })} />
                  <span className="muted">–</span>
                  <HourSelect value={b.end} onChange={(v) => store.setDayBlock(dow, i, { end: v })} />
                  <button className="ap-block-x" title={T("delete")} onClick={() => store.removeDayBlock(dow, i)}><Icon name="x" /></button>
                </div>
            )}
              {store.weekdayHours[dow].length === 0 && <span className="ap-closed">{T("closed")}</span>}
              <button className="ap-addblock" onClick={() => store.addDayBlock(dow)}>{T("add_block")}</button>
            </div>
          </div>
        )}
      </div>
    </div>);

}
function OwnerNumberRow({ store }) {
  const ownerStaff = (store.staff || []).find((s) => s.role === "Inhaber");
  const realPhone = ownerStaff && !ownerStaff.phone.startsWith("owner:") ? ownerStaff.phone : "";
  const [num, setNum] = uS(realPhone);
  const [editing, setEditing] = uS(false);
  const [draft, setDraft] = uS(realPhone);
  React.useEffect(() => { if (realPhone && !num) { setNum(realPhone); setDraft(realPhone); } }, [realPhone]);
  const save = async () => {
    const val = draft.trim();
    if (val && ownerStaff) await store.updateStaff(ownerStaff.id, { phone: val });
    setNum(val || num); setEditing(false); store.pushToast(T("t_owner_changed"), "phone");
  };
  return (
    <div className="ap-setrow">
      <div style={{ flex: 1 }}>
        <div className="ap-set-t">{T("s_owner")}</div>
        <div className="ap-set-d">{T("s_owner_d")}</div>
        {editing && <div className="owner-warn"><Icon name="alert" style={{ width: 14, height: 14, flex: "none" }} />{T("owner_warn")}</div>}
      </div>
      {!editing ?
      <div className="row gap10">
          <span className="owner-num mono">{num || <span style={{ color: "var(--muted)", fontStyle: "italic" }}>Noch nicht hinterlegt</span>}</span>
          <button className="btn btn-ghost btn-sm" onClick={() => {setDraft(num);setEditing(true);}}>{num ? T("change") : "Eintragen"}</button>
        </div> :

      <div className="row gap8" style={{ flexWrap: "wrap", justifyContent: "flex-end" }}>
          <input className="ap-input" value={draft} onChange={(e) => setDraft(e.target.value)} autoFocus />
          <button className="btn btn-ghost btn-sm" onClick={() => setEditing(false)}>{T("cancel")}</button>
          <button className="btn btn-primary btn-sm" onClick={save}><Icon name="check" />{T("save")}</button>
        </div>
      }
    </div>);

}
// ── Bundesland-Presets ────────────────────────────────────────────────────────
const BUNDESLAND_PRESETS = {
  "Bundesweit": [
    { name: "Neujahr",                    month: 1,  day: 1  },
    { name: "Tag der Arbeit",             month: 5,  day: 1  },
    { name: "Tag d. Deutschen Einheit",   month: 10, day: 3  },
    { name: "1. Weihnachtstag",           month: 12, day: 25 },
    { name: "2. Weihnachtstag",           month: 12, day: 26 },
  ],
  "Bayern": [
    { name: "Heilige Drei Könige",        month: 1,  day: 6  },
    { name: "Mariä Himmelfahrt",          month: 8,  day: 15 },
    { name: "Allerheiligen",              month: 11, day: 1  },
    { name: "Heiligabend (½)",            month: 12, day: 24 },
    { name: "Silvester (½)",              month: 12, day: 31 },
  ],
  "NRW": [
    { name: "Allerheiligen",              month: 11, day: 1  },
  ],
  "Baden-Württemberg": [
    { name: "Heilige Drei Könige",        month: 1,  day: 6  },
    { name: "Allerheiligen",              month: 11, day: 1  },
  ],
  "Österreich": [
    { name: "Heilige Drei Könige",        month: 1,  day: 6  },
    { name: "Staatsfeiertag",             month: 5,  day: 1  },
    { name: "Mariä Himmelfahrt",          month: 8,  day: 15 },
    { name: "Nationalfeiertag",           month: 10, day: 26 },
    { name: "Allerheiligen",              month: 11, day: 1  },
    { name: "Mariä Empfängnis",           month: 12, day: 8  },
  ],
  "Schweiz": [
    { name: "Berchtoldstag",              month: 1,  day: 2  },
    { name: "Bundesfeiertag",             month: 8,  day: 1  },
  ],
};

const MONTH_NAMES = ["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"];

function HolidaysCard({ store }) {
  const holidays = store.holidays || [];
  const [newName, setNewName] = uS("");
  const [newMonth, setNewMonth] = uS(1);
  const [newDay, setNewDay] = uS(1);
  const [showPresets, setShowPresets] = uS(false);

  const add = () => {
    const n = newName.trim();
    if (!n) return;
    const already = holidays.some(h => h.month === +newMonth && h.day === +newDay);
    if (already) { store.pushToast("Dieser Tag existiert bereits", "alert"); return; }
    store.saveHolidays([...holidays, { name: n, month: +newMonth, day: +newDay }]);
    setNewName("");
  };

  const remove = (i) => store.saveHolidays(holidays.filter((_, idx) => idx !== i));

  const addPreset = (preset) => {
    const toAdd = preset.filter(p => !holidays.some(h => h.month === p.month && h.day === p.day));
    if (toAdd.length === 0) { store.pushToast("Alle Feiertage bereits vorhanden", "alert"); return; }
    store.saveHolidays([...holidays, ...toAdd]);
    store.pushToast(`${toAdd.length} Feiertage hinzugefügt`, "check");
  };

  return (
    <div className="ap-card">
      <div className="ap-cardhead">
        <div><h3 className="display">Feiertage</h3><span className="role-tag">Im Kalender angezeigte Feiertage — je nach Bundesland / Land</span></div>
        <button className="btn btn-ghost btn-sm" onClick={() => setShowPresets(v => !v)}>
          <Icon name="globe" /> Presets
        </button>
      </div>

      {/* Preset-Buttons */}
      {showPresets && (
        <div style={{ padding: "10px 20px 4px", display: "flex", flexWrap: "wrap", gap: 7 }}>
          {Object.entries(BUNDESLAND_PRESETS).map(([label, preset]) => (
            <button key={label} className="btn btn-soft btn-sm" onClick={() => addPreset(preset)}>
              + {label}
            </button>
          ))}
        </div>
      )}

      {/* Liste */}
      <div className="ap-setbody">
        {holidays.length === 0 && (
          <div style={{ fontSize: 13, color: "var(--muted)", fontStyle: "italic", padding: "4px 0 8px" }}>
            Keine Feiertage konfiguriert — wähle ein Preset oder füge manuell hinzu.
          </div>
        )}
        <div style={{ display: "flex", flexDirection: "column", gap: 4, marginBottom: holidays.length ? 12 : 0 }}>
          {holidays.sort((a,b) => a.month - b.month || a.day - b.day).map((h, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "5px 0" }}>
              <span className="mono" style={{ fontSize: 12, color: "var(--muted)", width: 46, flexShrink: 0 }}>
                {String(h.day).padStart(2,"0")} {MONTH_NAMES[h.month - 1]}
              </span>
              <span style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>{h.name}</span>
              <button className="icon-btn" style={{ width: 28, height: 28 }} onClick={() => remove(i)}>
                <Icon name="x" style={{ width: 13, height: 13 }} />
              </button>
            </div>
          ))}
        </div>

        {/* Neuen hinzufügen */}
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center", borderTop: holidays.length ? "1px solid var(--border)" : "none", paddingTop: holidays.length ? 12 : 0 }}>
          <input className="ap-input" style={{ flex: 1, minWidth: 140 }} value={newName}
            onChange={e => setNewName(e.target.value)}
            onKeyDown={e => e.key === "Enter" && add()}
            placeholder="Name (z.B. Betriebsurlaub)" />
          <select className="ap-input sm" value={newDay} onChange={e => setNewDay(+e.target.value)}>
            {Array.from({length:31},(_,i)=><option key={i+1} value={i+1}>{i+1}</option>)}
          </select>
          <select className="ap-input sm" style={{ width: 70 }} value={newMonth} onChange={e => setNewMonth(+e.target.value)}>
            {MONTH_NAMES.map((m,i)=><option key={i} value={i+1}>{m}</option>)}
          </select>
          <button className="btn btn-soft btn-sm" onClick={add}>
            <Icon name="plus" /> Hinzufügen
          </button>
        </div>
      </div>
    </div>
  );
}

function SettingsView({ store, lang, onLang }) {
  const [s, setS] = uS({ absence: true, swap: true, claude: true });
  const tog = (k) => setS((p) => ({ ...p, [k]: !p[k] }));
  const [nameDraft, setNameDraft] = uS(store.restaurantName);
  const [nameSaving, setNameSaving] = uS(false);

  const saveName = async () => {
    const val = nameDraft.trim();
    if (!val || val === store.restaurantName) return;
    setNameSaving(true);
    await fetch("/auth/me", { method: "PATCH", credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ business_name: val }) });
    store.setRestaurantName(val);
    setNameSaving(false);
    store.pushToast(T("t_name_saved"), "check");
  };

  return (
    <div className="ap-pad fade-in">
      <div className="ap-settings">
        <div className="ap-card">
          <div className="ap-cardhead"><h3 className="display">{T("s_restaurant")}</h3></div>
          <div className="ap-setbody">
            <SettingsRow title={T("s_name")}>
              <div className="row gap8">
                <input className="ap-input" value={nameDraft}
                  onChange={(e) => setNameDraft(e.target.value)}
                  onBlur={saveName}
                  onKeyDown={(e) => e.key === "Enter" && saveName()} />
                {nameDraft.trim() !== store.restaurantName && (
                  <button className="btn btn-primary btn-sm" onClick={saveName} disabled={nameSaving}>
                    {nameSaving ? "…" : <><Icon name="check" />Speichern</>}
                  </button>
                )}
              </div>
            </SettingsRow>
          </div>
        </div>

        <div className="ap-card">
          <div className="ap-cardhead"><h3 className="display">{T("s_appearance")}</h3></div>
          <div className="ap-setbody">
            <SettingsRow title={T("s_dark")} desc={T("s_dark_d")}>
              <button className={"ap-darktoggle" + (store.theme === "dark" ? " on" : "")} onClick={store.toggleTheme}>
                <span className="ap-dt-ico sun"><Icon name="sun" /></span>
                <span className="ap-dt-ico moon"><Icon name="moon" /></span>
                <span className="ap-dt-knob" />
              </button>
            </SettingsRow>
          </div>
        </div>

        <CategoriesCard store={store} />
        <HoursCard store={store} />

        <div className="ap-card">
          <div className="ap-cardhead"><h3 className="display">{T("s_wa")}</h3><span className="badge st-confirmed"><span className="dot" />{T("connected")}</span></div>
          <div className="ap-setbody">
            <SettingsRow title={T("s_absence")} desc={T("s_absence_d")}><Toggle on={s.absence} onClick={() => tog("absence")} /></SettingsRow>
            <SettingsRow title={T("s_swap")} desc={T("s_swap_d")}><Toggle on={s.swap} onClick={() => tog("swap")} /></SettingsRow>
          </div>
        </div>

        <HolidaysCard store={store} />
        <BillingView store={store} />

        <div className="ap-card">
          <div className="ap-cardhead"><h3 className="display">{T("s_assist")}</h3></div>
          <div className="ap-setbody">
            <SettingsRow title={T("s_twilio")} desc="whatsapp:+49 30 1200 8890"><span className="badge st-confirmed"><span className="dot" />{T("active")}</span></SettingsRow>
            <OwnerNumberRow store={store} />
          </div>
        </div>

        <div className="ap-card" style={{ borderColor: "var(--st-red)" }}>
          <div className="ap-cardhead"><h3 className="display" style={{ color: "var(--st-red)" }}>{T("danger_zone")}</h3></div>
          <div className="ap-setbody">
            <SettingsRow title={T("del_account")} desc={T("del_account_d")}>
              <button className="btn btn-danger btn-sm" onClick={() => store.openDeleteAccount && store.openDeleteAccount()}>
                <Icon name="trash" />{T("del_account")}
              </button>
            </SettingsRow>
          </div>
        </div>
      </div>
    </div>);

}

/* ---------- Account menu (user-specific) ---------- */
function DeleteAccountModal({ store, onClose, onDeleteSuccess }) {
  const [confirm, setConfirm] = uS("");
  const [busy, setBusy] = uS(false);
  const confirmWord = window.SBI.lang === "en" ? "DELETE" : "LÖSCHEN";
  const valid = confirm === confirmWord;
  const doDelete = async () => {
    if (!valid) return;
    setBusy(true);
    try {
      await fetch("/auth/account", { method: "DELETE", credentials: "include" });
      onDeleteSuccess && onDeleteSuccess();   // alle Fenster schließen
      await store.logout();                   // dann ausloggen
    } catch (e) {
      setBusy(false);
    }
  };
  return (
    <Modal title={T("del_account")} onClose={onClose}
      foot={<>
        <button className="btn btn-ghost" onClick={onClose}>{T("cancel")}</button>
        <button className="btn btn-danger" onClick={doDelete} disabled={!valid || busy}>
          <Icon name="trash" />{busy ? "…" : T("del_account_btn")}
        </button>
      </>}>
      <div className="modal-body">
        <div className="del-warn">
          <span className="del-warn-ico"><Icon name="alert" /></span>
          <div>{T("del_account_warn")}</div>
        </div>
        <div className="field" style={{ marginTop: 20 }}>
          <label>{T("del_account_confirm")} <strong>{confirmWord}</strong></label>
          <input value={confirm} onChange={e => setConfirm(e.target.value)} placeholder={confirmWord} autoFocus />
        </div>
      </div>
    </Modal>
  );
}

function AccountMenu({ store, lang, onLang, onClose, onProfile, onPassword, onDeleteAccount }) {
  const me = SB.staffById(1) || { name: store.ownerName || "Owner", role: "owner", id: 0 };
  const items = [
  { icon: "user", t: "acc_profile", d: "acc_profile_d", act: onProfile },
  { icon: "lock", t: "acc_password", d: "acc_password_d", act: onPassword },
  { icon: "bell", t: "acc_notif", d: "acc_notif_d", act: () => store.pushToast(T("acc_notif")) }];

  return (
    <div className="acc-scrim" onMouseDown={onClose}>
      <div className="acc-menu" onMouseDown={(e) => e.stopPropagation()}>
        <div className="acc-head">
          <Avatar staff={me} size={46} mono />
          <div style={{ minWidth: 0 }}>
            <div className="acc-name">{me.name}</div>
            <div className="acc-mail mono">{store.ownerEmail || "–"}</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" /></button>
        </div>
        <div className="acc-body">
          {items.map((it) =>
          <button key={it.t} className="acc-item" onClick={() => {onClose();it.act && it.act();}}>
              <span className="acc-item-ico"><Icon name={it.icon} /></span>
              <span style={{ flex: 1, minWidth: 0 }}><span className="acc-item-t">{T(it.t)}</span><span className="acc-item-d">{T(it.d)}</span></span>
              <Icon name="chevR" style={{ width: 16, height: 16, color: "var(--faint)" }} />
            </button>
          )}
          <div className="acc-langrow">
            <span className="acc-item-ico"><Icon name="globe" /></span>
            <span style={{ flex: 1 }} className="acc-item-t">{T("acc_lang")}</span>
            <LangMenu lang={lang} onLang={onLang} />
          </div>
        </div>
        <div className="acc-foot">
          <button className="btn btn-ghost acc-logout" onClick={() => {onClose();store.logout();}}><Icon name="logout" />{T("acc_logout")}</button>
        </div>
      </div>
    </div>);

}

/* ---------- Help view ---------- */
const FAQS = [1,2,3,4,5].map(i => ({ q: `faq_q${i}`, a: `faq_a${i}` }));

function HelpView({ store }) {
  const [subject, setSubject] = uS("");
  const [message, setMessage] = uS("");
  const [sending, setSending] = uS(false);
  const [sent, setSent] = uS(false);
  const [openFaq, setOpenFaq] = uS(null);

  const sendSupport = async () => {
    if (!subject.trim() || !message.trim()) return;
    setSending(true);
    try {
      await fetch("/auth/support", {
        method: "POST", credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ subject: subject.trim(), message: message.trim() }),
      });
      setSent(true);
      setSubject(""); setMessage("");
      store.pushToast(T("t_support_sent"), "check");
    } catch (e) {
      store.pushToast("Fehler beim Senden.", "alert");
    } finally { setSending(false); }
  };

  return (
    <div className="ap-pad fade-in">
      <div className="ap-settings">

        {/* FAQ */}
        <div className="ap-card">
          <div className="ap-cardhead"><h3 className="display">{T("help_faq_title")}</h3></div>
          <div className="ap-setbody">
            {FAQS.map((f, i) => (
              <div key={i} className="help-faq" style={{ cursor: "pointer" }} onClick={() => setOpenFaq(openFaq === i ? null : i)}>
                <div className="row between">
                  <div className="help-faq-q">{T(f.q)}</div>
                  <Icon name="chevR" style={{ width: 16, height: 16, color: "var(--muted)", transform: openFaq === i ? "rotate(90deg)" : "none", transition: "transform .15s", flexShrink: 0 }} />
                </div>
                {openFaq === i && <div className="help-faq-a" style={{ marginTop: 6 }}>{T(f.a)}</div>}
              </div>
            ))}
          </div>
        </div>

        {/* Support-Formular */}
        <div className="ap-card">
          <div className="ap-cardhead"><h3 className="display">{T("help_contact_title")}</h3></div>
          <div className="ap-setbody">
            {sent ? (
              <div style={{ display: "flex", gap: 12, alignItems: "center", padding: "8px 0", color: "var(--green-deep)" }}>
                <Icon name="check" style={{ width: 20, height: 20 }} />
                <span style={{ fontWeight: 600 }}>{T("help_sent_ok")}</span>
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <div className="field">
                  <label>{T("help_subject")}</label>
                  <input className="ap-input" style={{ width: "100%" }} value={subject}
                    onChange={e => setSubject(e.target.value)} placeholder={T("help_subject_ph")} />
                </div>
                <div className="field">
                  <label>{T("help_message")}</label>
                  <textarea className="ap-input" style={{ width: "100%", minHeight: 100, resize: "vertical", fontFamily: "inherit" }}
                    value={message} onChange={e => setMessage(e.target.value)}
                    placeholder={T("help_msg_ph")} />
                </div>
                <div className="row" style={{ gap: 12, alignItems: "center" }}>
                  <button className="btn btn-primary" onClick={sendSupport} disabled={sending || !subject.trim() || !message.trim()}>
                    {sending ? "…" : T("help_send")}
                  </button>
                  <span style={{ fontSize: 12, color: "var(--muted)" }}>{T("help_reply_hint")}</span>
                </div>
              </div>
            )}
          </div>
        </div>

      </div>
    </div>
  );
}

/* ---------- Profile editor ---------- */
/* ---------- Verified-field change flow (email / phone) ---------- */
function VerifyFieldRow({ label, value, kind, onVerified }) {
  const [phase, setPhase] = uS("idle");
  const [draft, setDraft] = uS(value);
  const [code, setCode] = uS("");
  const [err, setErr] = uS("");
  const [busy, setBusy] = uS(false);
  const target = draft;

  const requestChange = async () => {
    setBusy(true); setErr("");
    try {
      const r = await fetch("/auth/change-email/request", {
        method: "POST", credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ new_email: draft }),
      });
      const d = await r.json();
      if (!r.ok) { setErr(d.detail || "Fehler"); setBusy(false); return; }
      setPhase("verifying");
    } catch (e) { setErr("Verbindungsfehler"); }
    setBusy(false);
  };

  const confirm = async () => {
    setBusy(true); setErr("");
    try {
      const r = await fetch("/auth/change-email/confirm", {
        method: "POST", credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code: code.trim() }),
      });
      const d = await r.json();
      if (!r.ok) { setErr(d.detail || T("verify_wrong")); setBusy(false); return; }
      onVerified(d.new_email || draft);
      setPhase("idle"); setCode(""); setErr("");
    } catch (e) { setErr("Verbindungsfehler"); }
    setBusy(false);
  };
  return (
    <div className="vf">
      <label className="vf-label">{label}</label>
      {phase === "idle" &&
      <div className="vf-row">
          <span className="vf-val">{value}</span>
          <button className="btn btn-ghost btn-sm" onClick={() => {setDraft(value);setPhase("editing");}}>{T("change")}</button>
        </div>
      }
      {phase === "editing" &&
      <div className="vf-edit fade-in">
          <input className="ap-input" type={kind === "email" ? "email" : "tel"} value={draft} onChange={(e) => setDraft(e.target.value)} autoFocus />
          <div className="vf-note"><Icon name="lock" style={{ width: 13, height: 13, flex: "none" }} />{kind === "email" ? T("verify_email_d") : T("verify_phone_d")}</div>
          {err && <div className="pw-err">{err}</div>}
          <div className="row gap8" style={{ justifyContent: "flex-end" }}>
            <button className="btn btn-ghost btn-sm" onClick={() => setPhase("idle")}>{T("cancel")}</button>
            <button className="btn btn-primary btn-sm" disabled={!draft.trim() || draft === value || busy} onClick={requestChange}>{busy ? "…" : T("request_change")}</button>
          </div>
        </div>
      }
      {phase === "verifying" &&
      <div className="vf-edit fade-in">
          <div className="vf-sent">{T("verify_sent", { target })}</div>
          <input className="ap-input mono" value={code} onChange={(e) => {setCode(e.target.value);setErr(false);}} placeholder="123456" maxLength={6} autoFocus />
          {err && <div className="pw-err">{err}</div>}
          <div className="row between" style={{ alignItems: "center" }}>
            <button className="vf-resend" onClick={requestChange}>{T("verify_resend")}</button>
            <div className="row gap8">
              <button className="btn btn-ghost btn-sm" onClick={() => setPhase("idle")}>{T("cancel")}</button>
              <button className="btn btn-primary btn-sm" onClick={confirm} disabled={busy || code.length < 6}><Icon name="check" />{busy ? "…" : T("verify_confirm")}</button>
            </div>
          </div>
        </div>
      }
    </div>);

}

/* ---------- Profile editor ---------- */
function ProfileModal({ store, onClose }) {
  const me = SB.staffById(1) || { name: store.ownerName || "Owner", role: "owner", id: 0, phone: "" };
  const [name, setName] = uS(store.ownerName || me.name);
  const [email, setEmail] = uS("");
  const [phone, setPhone] = uS(me.phone);
  useEffect(() => {
    fetch("/auth/me", { credentials: "include" }).then(r => r.json()).then(d => {
      if (d.email) setEmail(d.email);
      if (d.name) setName(d.name);
    }).catch(() => {});
  }, []);
  const save = () => {me.name = name.trim() || me.name;store.pushToast(T("t_profile_saved"), "user");onClose();};
  return (
    <Modal title={T("pf_title")} onClose={onClose}
    foot={<>
        <button className="btn btn-ghost" onClick={onClose}>{T("cancel")}</button>
        <button className="btn btn-primary" onClick={save}><Icon name="check" />{T("pf_save")}</button>
      </>}>
      <div className="modal-body">
        <div className="pf-photo">
          <Avatar staff={{ ...me, name }} size={64} mono />
          <div>
            <div className="ap-set-t">{T("pf_photo")}</div>
            <button className="btn btn-ghost btn-sm" style={{ marginTop: 6 }} onClick={() => store.pushToast(T("pf_change_photo"))}>{T("pf_change_photo")}</button>
          </div>
        </div>
        <div className="field"><label>{T("pf_name")}</label><input value={name} onChange={(e) => setName(e.target.value)} /></div>
        <VerifyFieldRow label={T("pf_email")} value={email} kind="email" onVerified={(v) => {setEmail(v);store.pushToast(T("t_email_changed"), "lock");}} />
        <VerifyFieldRow label={T("pf_phone")} value={phone} kind="phone" onVerified={(v) => {setPhone(v);me.phone = v;store.pushToast(T("t_phone_changed"), "lock");}} />
        <div className="field"><label>{T("pf_role")}</label><input value={me.role} disabled /></div>
      </div>
    </Modal>);

}

/* ---------- Change-password interface ---------- */
function PasswordModal({ store, onClose }) {
  const [cur, setCur] = uS("");
  const [nw, setNw] = uS("");
  const [confirm, setConfirm] = uS("");
  const [err, setErr] = uS("");
  const [busy, setBusy] = uS(false);
  const score = (() => {let s = 0;if (nw.length >= 8) s++;if (/[A-Z]/.test(nw) && /[a-z]/.test(nw)) s++;if (/\d/.test(nw)) s++;if (/[^A-Za-z0-9]/.test(nw)) s++;return s;})();
  const strengthLabel = score <= 1 ? T("pw_weak") : score === 2 ? T("pw_ok") : T("pw_strong");
  const strengthColor = score <= 1 ? "var(--st-red)" : score === 2 ? "var(--st-orange)" : "var(--st-green)";
  const tooShort = nw.length > 0 && nw.length < 8;
  const mismatch = confirm.length > 0 && nw !== confirm;
  const valid = cur.length > 0 && nw.length >= 8 && nw === confirm;
  const save = async () => {
    if (!valid) return;
    setErr(""); setBusy(true);
    try {
      await window.SBAPI.changePassword(cur, nw);
      store.pushToast(T("t_pw_changed"), "lock");
      onClose();
    } catch (e) {
      setErr(e.message || "Fehler beim Ändern des Passworts.");
    } finally { setBusy(false); }
  };
  return (
    <Modal title={T("pw_title")} onClose={onClose}
    foot={<>
        <button className="btn btn-ghost" onClick={onClose}>{T("cancel")}</button>
        <button className="btn btn-primary" onClick={save} disabled={!valid || busy}><Icon name="lock" />{busy ? "…" : T("pw_save")}</button>
      </>}>
      <div className="modal-body">
        <div className="field"><label>{T("pw_current")}</label><input type="password" value={cur} onChange={(e) => setCur(e.target.value)} autoFocus /></div>
        <div className="field">
          <label>{T("pw_new")}</label>
          <input type="password" value={nw} onChange={(e) => setNw(e.target.value)} />
          {nw.length > 0 &&
          <div className="pw-strength">
              <div className="pw-bars">{[0, 1, 2, 3].map((i) => <span key={i} className={"pw-bar" + (i < score ? " on" : "")} style={i < score ? { background: strengthColor } : {}} />)}</div>
              <span className="pw-strength-lab" style={{ color: strengthColor }}>{strengthLabel}</span>
            </div>
          }
          {tooShort && <div className="pw-err">{T("pw_short")}</div>}
        </div>
        <div className="field">
          <label>{T("pw_confirm")}</label>
          <input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} />
          {mismatch && <div className="pw-err">{T("pw_mismatch")}</div>}
        </div>
        {err && <div className="pw-err" style={{ marginTop: 8 }}><Icon name="alert" style={{ width: 14, height: 14 }} />{" "}{err}</div>}
      </div>
    </Modal>);

}

/* ---------- Forgot Password Modal ---------- */
function ForgotPasswordModal({ onClose }) {
  const [email, setEmail] = uS("");
  const [busy, setBusy]   = uS(false);
  const [sent, setSent]   = uS(false);
  const submit = async (e) => {
    e.preventDefault();
    setBusy(true);
    try {
      await fetch("/auth/reset-request", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      setSent(true);
    } finally { setBusy(false); }
  };
  return (
    <Modal title={T("fp_title")} onClose={onClose}
      foot={<><div style={{ flex: 1 }} /><button className="btn btn-ghost" onClick={onClose}>{T("fp_back")}</button></>}>
      <div className="modal-body">
        {sent ? (
          <div style={{ padding: "12px 0", color: "var(--st-green)", fontWeight: 600 }}>
            <Icon name="check" style={{ width: 18, height: 18, marginRight: 8, verticalAlign: "middle" }} />
            {T("fp_sent")}
          </div>
        ) : (
          <form onSubmit={submit}>
            <p style={{ fontSize: 14, color: "var(--ink-2)", marginBottom: 16 }}>{T("fp_sub")}</p>
            <div className="field">
              <label>{T("fp_email")}</label>
              <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} autoFocus required />
            </div>
            <button type="submit" className="btn btn-primary" style={{ marginTop: 8, width: "100%" }} disabled={busy}>
              {busy ? "…" : T("fp_send")}
            </button>
          </form>
        )}
      </div>
    </Modal>
  );
}

/* ---------- Reset Password Page ---------- */
function ResetPasswordPage() {
  const token = new URLSearchParams(window.location.search).get("token") || "";
  const [pass, setPass]       = uS("");
  const [pass2, setPass2]     = uS("");
  const [err, setErr]         = uS("");
  const [busy, setBusy]       = uS(false);
  const [done, setDone]       = uS(false);
  const submit = async (e) => {
    e.preventDefault();
    if (pass.length < 8) { setErr(T("rp_short")); return; }
    if (pass !== pass2)  { setErr(T("rp_mismatch")); return; }
    setBusy(true); setErr("");
    try {
      const r = await fetch("/auth/reset-confirm", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, password: pass }),
      });
      if (r.ok) { setDone(true); }
      else { const d = await r.json(); setErr(d.detail || T("rp_invalid")); }
    } finally { setBusy(false); }
  };
  return (
    <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", background: "var(--bg)" }}>
      <div style={{ width: "100%", maxWidth: 400, padding: 24 }}>
        <h1 className="display login-h1" style={{ marginBottom: 8 }}>ShiftBud</h1>
        <div className="login-card" style={{ marginTop: 0 }}>
          <h2 style={{ fontSize: 20, fontWeight: 700, marginBottom: 8 }}>{T("rp_title")}</h2>
          {done ? (
            <div style={{ color: "var(--st-green)", fontWeight: 600, padding: "12px 0" }}>
              <Icon name="check" style={{ width: 18, height: 18, marginRight: 8, verticalAlign: "middle" }} />
              {T("rp_success")}
              <a href="/" style={{ display: "block", marginTop: 16, color: "var(--green)" }}>{T("fp_back")}</a>
            </div>
          ) : (
            <form onSubmit={submit}>
              <div className="field" style={{ marginTop: 16 }}>
                <label>{T("rp_new")}</label>
                <input type="password" value={pass} onChange={(e) => setPass(e.target.value)} autoFocus required minLength={8} autoComplete="new-password" />
              </div>
              <div className="field" style={{ marginTop: 12 }}>
                <label>{T("rp_confirm")}</label>
                <input type="password" value={pass2} onChange={(e) => setPass2(e.target.value)} required autoComplete="new-password" />
              </div>
              {err && <div className="login-err"><Icon name="alert" style={{ width: 15, height: 15 }} />{err}</div>}
              <button type="submit" className="btn btn-primary login-btn" disabled={busy || !token}>
                {busy ? "…" : T("rp_btn")}
              </button>
              {!token && <div className="login-err" style={{ marginTop: 8 }}>{T("rp_invalid")}</div>}
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- Login page ---------- */
function LoginForm({ store, compact, onSwitch }) {
  const [email, setEmail]     = uS("");
  const [pass, setPass]       = uS("");
  const [err, setErr]         = uS(false);
  const [busy, setBusy]       = uS(false);
  const [remember, setRemember] = uS(true);
  const [forgotOpen, setForgotOpen] = uS(false);
  const [unverified, setUnverified] = uS(false);
  const [resent, setResent] = uS(false);
  const submit = async (e) => {
    if (e) e.preventDefault();
    setErr(false); setUnverified(false); setResent(false);
    setBusy(true);
    try {
      await store.login(email, pass);
    } catch (e) {
      if (e.message === "EMAIL_NOT_VERIFIED") setUnverified(true);
      else setErr(true);
    } finally {
      setBusy(false);
    }
  };
  const resendVerification = async () => {
    try {
      await fetch("/auth/resend-verification", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email })
      });
      setResent(true);
    } catch (_) {}
  };
  return (
    <>
      <form className="login-card" onSubmit={submit}>
        <h1 className="display login-h1">{T("login_welcome")}</h1>
        <p className="login-p">{T("login_sub")}</p>
        <div className="field" style={{ marginTop: 18 }}>
          <label>{T("login_user")}</label>
          <input type="email" value={email} onChange={(e) => {setEmail(e.target.value);setErr(false);}} autoFocus autoComplete="username" />
        </div>
        <div className="field" style={{ marginTop: 12 }}>
          <label>{T("login_pass")}</label>
          <input type="password" value={pass} onChange={(e) => {setPass(e.target.value);setErr(false);}} autoComplete="current-password" />
        </div>
        {err && <div className="login-err"><Icon name="alert" style={{ width: 15, height: 15 }} />{T("login_err")}</div>}
        {unverified && (
          <div className="login-err" style={{ background: "#fff8e1", color: "#856404", borderColor: "#ffc107", flexDirection: "column", alignItems: "flex-start", gap: 6 }}>
            <span><Icon name="bell" style={{ width: 15, height: 15 }} /> Bitte bestätige zuerst deine E-Mail-Adresse.</span>
            {resent
              ? <span style={{ color: "var(--st-green)", fontWeight: 600 }}>✓ Bestätigungslink wurde erneut gesendet.</span>
              : <button type="button" onClick={resendVerification} style={{ background: "none", border: "none", color: "#856404", textDecoration: "underline", cursor: "pointer", padding: 0, fontSize: 13 }}>Link erneut senden</button>
            }
          </div>
        )}
        <div className="login-row">
          <label className="ap-check login-remember">
            <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
            <span className="ap-check-box"><Icon name="check" /></span>
            <span>{T("login_remember")}</span>
          </label>
          <button type="button" className="login-forgot" onClick={() => setForgotOpen(true)}>{T("login_forgot")}</button>
        </div>
        <button type="submit" className="btn btn-primary login-btn" disabled={busy}>
          {busy ? "…" : <><Icon name="logout" style={{ transform: "scaleX(-1)" }} />{T("login_btn")}</>}
        </button>
      </form>
      <div style={{ textAlign: "center", marginTop: 14, fontSize: 13, color: "var(--ink-2)" }}>
        Noch kein Konto?{" "}
        <button type="button" className="login-forgot" onClick={onSwitch}>Jetzt registrieren</button>
      </div>
      {forgotOpen && <ForgotPasswordModal onClose={() => setForgotOpen(false)} />}
    </>
  );
}

/* ---------- Register form ---------- */
function RegisterForm({ store, onSwitch }) {
  const [email, setEmail]       = uS("");
  const [name, setName]         = uS("");
  const [business, setBusiness] = uS("");
  const [pass, setPass]         = uS("");
  const [pass2, setPass2]       = uS("");
  const [err, setErr]           = uS("");
  const [busy, setBusy]         = uS(false);
  const [done, setDone]         = uS(false);
  const [resent, setResent]     = uS(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    if (pass.length < 8) { setErr("Passwort muss mindestens 8 Zeichen haben."); return; }
    if (pass !== pass2)  { setErr("Passwörter stimmen nicht überein."); return; }
    setBusy(true);
    try {
      await window.SBAPI.register(email, pass, name, business);
      setDone(true);
    } catch (e) {
      setErr(e.message || "Registrierung fehlgeschlagen.");
    } finally {
      setBusy(false);
    }
  };

  const resendVerification = async () => {
    try {
      await fetch("/auth/resend-verification", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email })
      });
      setResent(true);
    } catch (_) {}
  };

  if (done) return (
    <div className="login-card" style={{ textAlign: "center" }}>
      <div style={{ marginBottom: 20 }}>
        <svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
          <rect width="64" height="64" rx="16" fill="#e9f5ee"/>
          <rect x="12" y="20" width="40" height="28" rx="4" fill="#2d6a4f"/>
          <path d="M12 24l20 13 20-13" stroke="#52b788" strokeWidth="2.5" strokeLinecap="round"/>
          <circle cx="46" cy="42" r="8" fill="#52b788"/>
          <path d="M42 42l3 3 5-5" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>
      <h2 style={{ fontSize: 20, fontWeight: 700, marginBottom: 10 }}>E-Mail bestätigen</h2>
      <p style={{ color: "var(--ink-2)", marginBottom: 8, lineHeight: 1.6 }}>
        Wir haben eine Bestätigungsmail an<br /><strong>{email}</strong> gesendet.
      </p>
      <p style={{ color: "var(--muted)", fontSize: 13, marginBottom: 20 }}>
        Bitte klicke auf den Link in der E-Mail.<br />
        Nicht gefunden? Schau auch im <strong>Spam-Ordner</strong> nach.
      </p>
      {resent
        ? <p style={{ color: "var(--st-green)", fontWeight: 600, marginBottom: 16 }}>✓ E-Mail erneut gesendet.</p>
        : <button type="button" className="btn btn-ghost" style={{ marginBottom: 12, width: "100%" }}
            onClick={resendVerification}>
            <Icon name="bell" style={{ width: 15, height: 15 }} /> E-Mail erneut senden
          </button>
      }
      <button type="button" className="login-forgot" onClick={onSwitch}>Zurück zum Login</button>
    </div>
  );

  return (
    <form className="login-card" onSubmit={submit}>
      <h1 className="display login-h1">Konto erstellen</h1>
      <p className="login-p">Starte deinen kostenlosen Test</p>
      <div className="field" style={{ marginTop: 18 }}>
        <label>E-Mail</label>
        <input type="email" value={email} onChange={(e) => { setEmail(e.target.value); setErr(""); }} autoFocus required autoComplete="username" />
      </div>
      <div className="field" style={{ marginTop: 12 }}>
        <label>Dein Name</label>
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} autoComplete="name" />
      </div>
      <div className="field" style={{ marginTop: 12 }}>
        <label>Name deines Betriebs</label>
        <input type="text" value={business} onChange={(e) => setBusiness(e.target.value)} placeholder="z.B. Café Marlene" />
      </div>
      <div className="field" style={{ marginTop: 12 }}>
        <label>Passwort</label>
        <input type="password" value={pass} onChange={(e) => { setPass(e.target.value); setErr(""); }} required minLength={8} autoComplete="new-password" />
      </div>
      <div className="field" style={{ marginTop: 12 }}>
        <label>Passwort bestätigen</label>
        <input type="password" value={pass2} onChange={(e) => { setPass2(e.target.value); setErr(""); }} required autoComplete="new-password" />
      </div>
      {err && <div className="login-err"><Icon name="alert" style={{ width: 15, height: 15 }} />{err}</div>}
      <button type="submit" className="btn btn-primary login-btn" disabled={busy}>
        {busy ? "…" : <><Icon name="userplus" />Registrieren</>}
      </button>
      <div style={{ textAlign: "center", marginTop: 14, fontSize: 13, color: "var(--ink-2)" }}>
        Bereits ein Konto?{" "}
        <button type="button" className="login-forgot" onClick={onSwitch}>Anmelden</button>
      </div>
    </form>
  );
}
const ShiftBudIcon = ({ size = 40, style }) => (
  <svg width={size} height={size} viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg" style={style}>
    <rect width="48" height="48" rx="12" fill="#1b4332"/>
    <rect x="16.75" y="8.5" width="3.5" height="6.5" rx="1.75" fill="#52b788"/>
    <rect x="27.75" y="8.5" width="3.5" height="6.5" rx="1.75" fill="#52b788"/>
    <rect x="10.5" y="12.5" width="27" height="26" rx="6" fill="#52b788"/>
    <path d="M10.5 18.5 a6 6 0 0 1 6 -6 h15 a6 6 0 0 1 6 6 v0.5 h-27 z" fill="#3a9d70"/>
    <path d="M16.5 27.5 L21.5 32.5 L31.5 22" stroke="#ffffff" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

function LoginPage({ store }) {
  const [mode, setMode] = uS("login");
  // Editorial hero — neutral slate bg with shift-bars flying left→right
  const bars = [
  { top: "10%", dur: 13, delay: 0, w: 30, tone: "g" },
  { top: "22%", dur: 17, delay: 2, w: 22, tone: "o" },
  { top: "33%", dur: 11, delay: 1, w: 36, tone: "g" },
  { top: "44%", dur: 19, delay: 4, w: 26, tone: "d" },
  { top: "55%", dur: 14, delay: 0.5, w: 32, tone: "g" },
  { top: "60%", dur: 23, delay: 8, w: 24, tone: "r" },
  { top: "66%", dur: 16, delay: 3, w: 24, tone: "o" },
  { top: "77%", dur: 12, delay: 1.5, w: 38, tone: "g" },
  { top: "84%", dur: 26, delay: 13, w: 20, tone: "r" },
  { top: "90%", dur: 20, delay: 2.5, w: 18, tone: "d" }];

  return (
    <div className="login-root">
      <div className="login-ed">
        <div className="login-ed-hero">
          <div className="login-ed-bars" aria-hidden="true" style={{ color: "rgb(167, 135, 91)" }}>
            {bars.map((b, i) =>
            <span key={i} className={"led-bar t-" + b.tone} style={{ top: b.top, width: b.w + "%", animationDuration: b.dur + "s", animationDelay: "-" + b.delay + "s" }} />
            )}
          </div>
          <div className="login-ed-brand">
            <ShiftBudIcon size={64} style={{ borderRadius: 16 }} />
            <span className="login-ed-name display">ShiftBud</span>
          </div>
          <h2 className="display login-ed-h">{T("login_tag")}</h2>
        </div>
        <div className="login-ed-panel">
          {mode === "login"
            ? <LoginForm store={store} onSwitch={() => setMode("register")} />
            : <RegisterForm store={store} onSwitch={() => setMode("login")} />}
        </div>
      </div>
    </div>);

}

/* ---------- Delete shift confirmation ---------- */
function DeleteShiftModal({ store, shift, onClose }) {
  const me = SB.staffById(shift.staffId);
  const day = SB.WEEK[shift.day];
  const [notify, setNotify] = uS(false);
  const doDelete = () => { store.deleteShiftSilent(shift.id, notify); onClose(); };
  return (
    <Modal title={T("del_title")} onClose={onClose}
    foot={<>
        <button className="btn btn-ghost" onClick={onClose}>{T("cancel")}</button>
        <button className="btn btn-danger" onClick={doDelete}><Icon name="trash" />{T("del_confirm")}</button>
      </>}>
      <div className="modal-body">
        <div className="del-warn">
          <span className="del-warn-ico"><Icon name="trash" /></span>
          <div>{T("del_body", { name: me.name, day: DOW(day.dow) + " " + day.num + " " + MONTH(), time: SB.fmtRange(shift.start, shift.end) })}</div>
        </div>
        <label className="ap-check del-check">
          <input type="checkbox" checked={notify} onChange={(e) => setNotify(e.target.checked)} />
          <span className="ap-check-box"><Icon name="check" /></span>
          <span>{T("del_notify", { name: me.name.split(" ")[0] })}</span>
        </label>
      </div>
    </Modal>);

}

/* ---------- Member detail / availability ---------- */
function MemberModal({ store, memberId, onClose, onDeleted }) {
  const m = SB.staffById(memberId);
  if (!m) {onClose();return null;}
  const [edit, setEdit] = uS(false);
  const [name, setName] = uS(m.name);
  const [role, setRole] = uS(m.role);
  const [phone, setPhone] = uS(m.phone);
  const [wk, setWk] = uS(store.weekOffset);
  const [addingUn, setAddingUn] = uS(false);
  const [unDay, setUnDay] = uS(0);
  const [unStart, setUnStart] = uS(8);
  const [unEnd, setUnEnd] = uS(24);
  const [unReason, setUnReason] = uS("");
  const [confirmDelete, setConfirmDelete] = uS(false);
  const [inviting, setInviting] = uS(false);
  const open = SB.RESTAURANT.openHour,close = SB.RESTAURANT.closeHour,span = close - open;
  const hourMarks = [];for (let h = open; h <= close; h += 4) hourMarks.push(h);
  const toPct = (h) => (h - open) / span * 100;
  const myShifts = store.shifts.filter((s) => s.staffId === memberId && s.week === wk && s.status !== "cancelled");
  const myUnavail = store.unavail.filter((u) => u.staffId === memberId);
  const weekDays = SB.weekMeta(wk);
  const totalH = myShifts.reduce((a, s) => a + (s.end - s.start), 0);
  const now = SB.realNow();
  const MN = (i) => window.SBI.monthName(i);
  const weekLabel = `${weekDays[0].num}–${weekDays[6].num} ${MN(weekDays[6].monthIdx)}`;
  const save = () => {m.name = name.trim() || m.name;m.role = role.trim() || m.role;m.phone = phone.trim() || m.phone;store.pushToast(T("t_member_saved"), "user");setEdit(false);};
  const remove = () => { store.removeStaff(memberId); onDeleted(); };
  const addUn = () => {
    if (unEnd <= unStart) return;
    store.addUnavail({ staffId: memberId, day: +unDay, start: +unStart, end: +unEnd, reason: unReason.trim() || T("mem_unavail") });
    store.pushToast(T("t_unavail_added"), "calendar");
    setAddingUn(false);setUnReason("");
  };
  return (
    <Modal title={T("mem_title")} onClose={onClose}
    foot={confirmDelete
      ? <>
          <span style={{ fontSize: 13, color: "var(--st-red)", flex: 1 }}>{T("mem_remove_q", { name: m.name.split(" ")[0], n: myShifts.length })}</span>
          <button className="btn btn-ghost" onClick={() => setConfirmDelete(false)}>{T("cancel")}</button>
          <button className="btn btn-danger" onClick={remove}><Icon name="trash" />{T("mem_remove")}</button>
        </>
      : <>
          <button className="btn btn-ghost sd-del" onClick={() => setConfirmDelete(true)}><Icon name="trash" />{T("mem_remove")}</button>
          <div style={{ flex: 1 }} />
          {!edit && !m.whatsappInvited && (
            <button className="btn btn-primary" disabled={inviting} onClick={async () => {
              setInviting(true);
              const ok = await store.inviteStaff(m.id);
              if (ok) m.whatsappInvited = true;
              setInviting(false);
            }}>
              <Icon name="chat" />{inviting ? "…" : "Einladen"}
            </button>
          )}
          {edit ? <button className="btn btn-primary" onClick={save}><Icon name="check" />{T("mem_save")}</button> :
          <button className="btn btn-ghost" onClick={() => setEdit(true)}><Icon name="user" />{T("mem_edit")}</button>}
        </>
    }>
      <div className="modal-body">
        {/* WhatsApp-Einladungsstatus */}
        {m.whatsappInvited
          ? <div style={{ display:"flex", alignItems:"center", gap:7, fontSize:12.5, fontWeight:600,
              color:"var(--st-green)", background:"var(--green-mist)", borderRadius:9, padding:"7px 12px", marginBottom:4 }}>
              <Icon name="chat" style={{ width:14, height:14 }} /> WhatsApp aktiv
            </div>
          : <div style={{ display:"flex", alignItems:"center", gap:7, fontSize:12.5, fontWeight:600,
              color:"#92610a", background:"#fdf3e0", border:"1px solid #e9c46a", borderRadius:9, padding:"7px 12px", marginBottom:4 }}>
              <span>📵</span> Noch nicht eingeladen — WhatsApp-Nachrichten werden nicht gesendet
            </div>
        }
        <div className="mem-head">
          <Avatar staff={{ ...m, name }} size={56} mono />
          {edit ?
          <div className="mem-edit-fields">
              <input className="ap-input" value={name} onChange={(e) => setName(e.target.value)} />
              <input className="ap-input" value={role} onChange={(e) => setRole(e.target.value)} list="sb-roles" />
              <input className="ap-input" value={phone} onChange={(e) => setPhone(e.target.value)} />
            </div> :

          <div style={{ minWidth: 0 }}>
              <div className="mem-name">{m.name}</div>
              <div className="role-tag">{m.role}</div>
              <div className="row gap6 mono mem-phone"><Icon name="phone" style={{ width: 13, height: 13, color: "var(--faint)" }} />{m.phone}</div>
            </div>
          }
        </div>

        <div className="mem-stats">
          <div className="mem-stat"><div className="mem-stat-v display">{totalH}h</div><div className="mem-stat-l">{T("mem_thisweek")}</div></div>
          <div className="mem-stat"><div className="mem-stat-v display">{myShifts.length}</div><div className="mem-stat-l">{T("mem_shifts_n", { n: myShifts.length }).replace(/^\d+\s/, "")}</div></div>
          <div className="mem-stat"><div className="mem-stat-v display">{m.role}</div><div className="mem-stat-l">{T("pf_role")}</div></div>
        </div>

        <div className="mem-avail">
          <div className="row between" style={{ marginBottom: 8 }}>
            <span className="ap-set-t">{T("mem_avail")}</span>
            <div className="mem-weeknav">
              <button className="mem-wbtn" onClick={() => setWk(Math.max(0, wk - 1))} disabled={wk === 0}><Icon name="arrowR" style={{ transform: "rotate(180deg)" }} /></button>
              <span className="mem-wlabel mono">{weekLabel}{wk === 0 ? " · " + T("today") : ""}</span>
              <button className="mem-wbtn" onClick={() => setWk(wk + 1)}><Icon name="arrowR" /></button>
            </div>
          </div>
          <div className="mem-legend" style={{ marginBottom: 6 }}><i className="mem-leg-w" />{T("mem_working")} <i className="mem-leg-f" />{T("mem_free")} <i className="mem-leg-u" />{T("mem_unavail")}</div>
          <div className="mem-axis mono">{hourMarks.map((h) => <span key={h} style={{ left: toPct(h) + "%" }}>{SB.fmtHour(h)}</span>)}</div>
          {weekDays.map((d) => {
            const ds = myShifts.filter((s) => s.day === d.index).sort((a, b) => a.start - b.start);
            const us = myUnavail.filter((u) => u.day === d.index);
            const isToday = wk === 0 && d.index === now.dayIndex;
            return (
              <div key={d.index} className={"mem-day" + (isToday ? " is-today" : "")}>
                <span className="mem-day-lab">{DOW(d.dow)} {d.num}</span>
                <div className="mem-track">
                  {ds.length === 0 && us.length === 0 && <span className="mem-off">{T("mem_off")}</span>}
                  {us.map((u) =>
                  <div key={"u" + u.id} className="mem-unblock" style={{ left: toPct(u.start) + "%", width: toPct(u.end) - toPct(u.start) + "%" }} title={u.reason}
                  onClick={() => store.removeUnavail(u.id)}>
                      <span className="mem-unblock-lab">{u.reason}</span>
                    </div>
                  )}
                  {ds.map((s) => {
                    const cat = (store.categories.find((c) => c.id === s.category) || {}).label;
                    return <div key={s.id} className="mem-block" style={{ left: toPct(s.start) + "%", width: toPct(s.end) - toPct(s.start) + "%" }} title={SB.fmtRange(s.start, s.end) + (cat ? " · " + cat : "")}>{SB.fmtRange(s.start, s.end)}</div>;
                  })}
                </div>
              </div>);

          })}

          {!addingUn ?
          <button className="mem-addun" onClick={() => setAddingUn(true)}><Icon name="plus" />{T("mem_add_unavail")}</button> :

          <div className="mem-unform fade-in">
              <div className="mem-unform-row">
                <select className="ap-input sm" value={unDay} onChange={(e) => setUnDay(e.target.value)}>
                  {SB.DOW_KEYS.map((dow, i) => <option key={i} value={i}>{DOW(dow)}</option>)}
                </select>
                <select className="ap-input sm" value={unStart} onChange={(e) => setUnStart(+e.target.value)}>
                  {Array.from({ length: 25 }, (_, i) => i).map((h) => <option key={h} value={h}>{String(h).padStart(2, "0")}:00</option>)}
                </select>
                <span className="muted">–</span>
                <select className="ap-input sm" value={unEnd} onChange={(e) => setUnEnd(+e.target.value)}>
                  {Array.from({ length: 25 }, (_, i) => i).map((h) => <option key={h} value={h}>{String(h).padStart(2, "0")}:00</option>)}
                </select>
                <input className="ap-input" style={{ flex: 1 }} value={unReason} onChange={(e) => setUnReason(e.target.value)} placeholder={T("un_reason_ph")} />
              </div>
              <div className="row gap8" style={{ justifyContent: "flex-end" }}>
                <button className="btn btn-ghost btn-sm" onClick={() => setAddingUn(false)}>{T("cancel")}</button>
                <button className="btn btn-primary btn-sm" onClick={addUn}><Icon name="plus" />{T("un_add")}</button>
              </div>
            </div>
          }
        </div>
      </div>
    </Modal>);

}

/* ---------- Billing / Pricing ---------- */
const PLANS = [
  { id: "basic",      name: "Basic",      price: "24 €", per: "/Monat", staff: 10 },
  { id: "pro",        name: "Pro",        price: "59 €", per: "/Monat", staff: 30, highlight: true },
  { id: "enterprise", name: "Enterprise", price: "99 €", per: "/Monat", staff: 80 },
];

function BillingView({ store }) {
  const billing = store.billing || {};
  const [busy, setBusy] = uS(null);

  const upgrade = async (plan) => {
    setBusy(plan);
    try {
      const r = await fetch("/api/billing/checkout", {
        method: "POST", credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ plan }),
      });
      const data = await r.json();
      if (data.mock) {
        // Dev-Modus: direkt mock-checkout aufrufen
        const r2 = await fetch(data.url, { credentials: "include" });
        const d2 = await r2.json();
        store.pushToast(d2.message || "Plan aktualisiert", "check");
        store.loadBilling();
      } else if (data.url) {
        window.location.href = data.url;
      }
    } catch (e) {
      store.pushToast("Fehler beim Upgrade", "alert");
    } finally { setBusy(null); }
  };

  const openPortal = async () => {
    setBusy("portal");
    try {
      const r = await fetch("/api/billing/portal", { method: "POST", credentials: "include" });
      const d = await r.json();
      if (d.url) window.location.href = d.url;
    } finally { setBusy(null); }
  };

  const hasActivePlan = billing.plan && billing.plan !== "trial";
  const currentPlan = PLANS.find((p) => p.id === billing.plan);

  return (
    <div className="ap-card">
      <div className="ap-cardhead"><h3 className="display">{T("nav_billing")}</h3></div>
      <div className="ap-setbody">
        {hasActivePlan ? (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12 }}>
            <div>
              <div style={{ fontSize: 13, color: "var(--muted)", marginBottom: 2 }}>{T("billing_current")}</div>
              <div style={{ fontSize: 20, fontWeight: 800, color: "var(--green-deep)" }}>{billing.plan_name}</div>
              {currentPlan && <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 2 }}>{T("billing_staff_price", { n: currentPlan.staff, price: currentPlan.price, per: currentPlan.per })}</div>}
            </div>
            <div style={{ display: "flex", gap: 8 }}>
              {true && <>
              <button className="btn btn-ghost btn-sm" onClick={openPortal} disabled={busy === "portal"}>
                {busy === "portal" ? "…" : T("billing_manage")}
              </button>
              <button className="btn btn-ghost btn-sm" onClick={openPortal} disabled={busy === "portal"}>
                {T("billing_invoice")}
              </button>
              </>}
            </div>
          </div>
        ) : (
          <>
            {billing.plan === "trial" && billing.trial_days_remaining != null && (
              <p style={{ color: "var(--st-orange)", marginBottom: 12, fontWeight: 600 }}>
                {T("billing_trial", { n: billing.trial_days_remaining, s: billing.trial_days_remaining !== 1 ? (window.SBI.lang === "en" ? "s" : "e") : "" })}
              </p>
            )}
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              {PLANS.map((p) => (
                <div key={p.id} style={{ position: "relative", flex: "1 1 140px", minWidth: 130, background: "var(--surface-2)", border: "1px solid " + (p.highlight ? "var(--green)" : "var(--border)"), borderRadius: 12, padding: "14px 14px 12px", display: "flex", flexDirection: "column", gap: 4 }}>
                  {p.highlight && <div className="billing-badge">{T("billing_popular")}</div>}
                  <div style={{ fontSize: 13, fontWeight: 700 }}>{p.name}</div>
                  <div style={{ fontSize: 22, fontWeight: 800, color: "var(--green-deep)", lineHeight: 1 }}>{p.price}<span style={{ fontSize: 12, fontWeight: 400, color: "var(--muted)" }}>{p.per}</span></div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-2)", marginBottom: 6 }}>{T("billing_staff", { n: p.staff })}</div>
                  <button
                    className={"btn btn-sm " + (p.highlight ? "btn-primary" : "btn-ghost")}
                    style={{ width: "100%", justifyContent: "center" }}
                    disabled={!!busy}
                    onClick={() => upgrade(p.id)}>
                    {busy === p.id ? "…" : T("billing_choose")}
                  </button>
                </div>
              ))}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

/* ---------- App ---------- */
function App() {
  // Show password-reset page when navigated via the reset link
  if (window.location.pathname === "/reset-password") return <ResetPasswordPage />;

  const store = useShiftBud();
  const [view, setView] = uS("calendar");
  const [trialExpired, setTrialExpired] = uS(false);
  const [trialDeleteConfirm, setTrialDeleteConfirm] = uS(false);
  const [lang, setLangState] = uS(window.SBI.lang);
  const [adding, setAdding] = uS(false);
  const [detail, setDetail] = uS(null);
  const [account, setAccount] = uS(false);
  const [deleteAccountOpen, setDeleteAccountOpen] = uS(false);
  const [profileOpen, setProfileOpen] = uS(false);
  const [pwOpen, setPwOpen] = uS(false);
  const [delShift, setDelShift] = uS(null);
  const [member, setMember] = uS(null);
  const closeAllModals = () => {
    setAdding(false); setDetail(null); setAccount(false);
    setDeleteAccountOpen(false); setProfileOpen(false);
    setPwOpen(false); setDelShift(null); setMember(null);
  };
  const changeLang = (l) => {window.SBI.setLang(l);setLangState(l);};
  const now = SB.realNow();
  React.useEffect(() => {
    window.__SB_reqDelete = (s) => {
      if (s.draft || s.status === "draft") { store.deleteShiftSilent(s.id, false); }
      else setDelShift(s);
    };
    window.__SB_openMember = (id) => setMember(id);
    window.__SB_reqOpen = (shiftId) => {
      const s = store.shifts.find(x => x.id === shiftId);
      if (s) { setDetail(s); setView("calendar"); }
    };
    window.__SB_loadShifts = () => store.loadShifts(store.weekOffset);
    window.__SB_trialExpired = () => setTrialExpired(true);
    return () => { window.__SB_reqDelete = null; window.__SB_openMember = null; window.__SB_reqOpen = null; window.__SB_loadShifts = null; window.__SB_trialExpired = null; };
  });

  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const billing = params.get("billing");
    if (billing === "success") {
      store.loadBilling();
      store.pushToast(T("t_billing_activated"), "check");
      setView("settings");
      window.history.replaceState({}, "", "/");
    } else if (billing === "cancelled") {
      store.pushToast("Zahlung abgebrochen.", "alert");
      window.history.replaceState({}, "", "/");
    }
  }, []);

  const MN = (i) => window.SBI.monthName(i);
  const weekDays = SB.weekMeta(store.weekOffset);
  const fd = weekDays[0],ld = weekDays[6];
  const weekLabel = fd.monthIdx === ld.monthIdx ?
  `${fd.num}–${ld.num} ${MN(ld.monthIdx)} ${ld.year}` :
  `${fd.num} ${MN(fd.monthIdx)} – ${ld.num} ${MN(ld.monthIdx)} ${ld.year}`;

  const weekSub = T("nav_calendar") + (store.weekOffset === 0 ? " · " + T("this_week_tag") : "");
  const titles = {
    calendar: [weekLabel, weekSub],
    coverage: [weekLabel, T("cov_title")],
    team: [T("team_title"), T("team_sub", { n: SB.STAFF.length })],
    inbox: [T("inbox_title"), T("inbox_sub")],
    settings: [T("set_title"), T("set_sub")],
    billing: [T("nav_billing"), ""],
    help: [T("help_title"), T("help_sub")]
  };
  const [title, sub] = titles[view] || [T("set_title"), ""];
  const weekly = view === "calendar" || view === "coverage";

  // Wait for initial auth check before showing anything
  if (!store.authChecked) return (
    <div className="sb-splash">
      <div className="sb-splash-inner">
        <div className="sb-splash-logo" style={{ background: "none", boxShadow: "none" }}>
          <ShiftBudIcon size={56} />
        </div>
        <div className="sb-splash-word">ShiftBud</div>
        <div className="sb-bars">
          <div className="sb-bar" /><div className="sb-bar" /><div className="sb-bar" />
          <div className="sb-bar" /><div className="sb-bar" />
        </div>
      </div>
    </div>
  );

  if (!store.authed) return <LoginPage store={store} />; // eslint-disable-line

  return (
    <div className="ap-app">
      <Sidebar view={view} setView={setView} conflicts={store.alerts.length + (store.generalMsgs || []).length} onAccount={() => setAccount(true)} restaurantName={store.restaurantName} ownerName={store.ownerName} />
      <div className="ap-main">
        {store.billing && store.billing.plan === "trial" && store.billing.trial_days_remaining <= 7 && (
          <div className="trial-banner">
            <Icon name="clock" style={{ width: 15, height: 15 }} />
            {store.billing.trial_days_remaining === 0
              ? "Dein Testzeitraum ist abgelaufen. Wähle jetzt einen Plan."
              : `Noch ${store.billing.trial_days_remaining} Tag${store.billing.trial_days_remaining !== 1 ? "e" : ""} im Testzeitraum.`}
            <button className="btn btn-primary btn-sm" style={{ marginLeft: 12 }} onClick={() => setView("billing")}>
              Jetzt upgraden
            </button>
          </div>
        )}
        <Topbar title={title} sub={sub} covStatus={coverageStatus(store.shifts, store.weekdayHours)} conflicts={store.alerts.length}
        onAdd={() => setAdding(true)} weekly={weekly} thisWeek={store.weekOffset === 0}
        onPrev={() => store.gotoWeek(store.weekOffset - 1)} onNext={() => store.gotoWeek(store.weekOffset + 1)} onToday={() => store.gotoWeek(0)} />
        <div className="ap-content">
          {view === "calendar" && <CalendarView store={store} openShift={setDetail} weekDays={weekDays} now={now} weekLabel={weekLabel} />}
          {view === "coverage" && <CoverageView store={store} weekDays={weekDays} />}
          {view === "team" && <TeamView store={store} />}
          {view === "inbox" && <InboxView store={store} />}
          {view === "settings" && <SettingsView store={{...store, openDeleteAccount: () => setDeleteAccountOpen(true)}} lang={lang} onLang={changeLang} />}
          {view === "help" && <HelpView store={store} />}
          {view === "billing" && <BillingView store={store} />}
        </div>
      </div>
      {adding && <AddShiftModal onClose={() => setAdding(false)} onAdd={store.addShift} categories={store.categories} weekDays={weekDays} weekOffset={store.weekOffset} weekLabel={weekLabel} isBlocked={store.isBlocked} hasOverlap={store.hasOverlap} unavail={store.unavail} weekdayHours={store.weekdayHours} />}
      {detail && <ShiftDetailModal shift={store.shifts.find((s) => s.id === detail.id) || detail} store={store} onClose={() => setDetail(null)} />}
      {account && <AccountMenu store={store} lang={lang} onLang={changeLang} onClose={() => setAccount(false)} onProfile={() => setProfileOpen(true)} onPassword={() => setPwOpen(true)} onDeleteAccount={() => setDeleteAccountOpen(true)} />}
      {deleteAccountOpen && <DeleteAccountModal store={store} onClose={() => setDeleteAccountOpen(false)} onDeleteSuccess={closeAllModals} />}
      {profileOpen && <ProfileModal store={store} onClose={() => setProfileOpen(false)} />}
      {pwOpen && <PasswordModal store={store} onClose={() => setPwOpen(false)} />}
      {delShift && <DeleteShiftModal store={store} shift={store.shifts.find((s) => s.id === delShift.id) || delShift} onClose={() => setDelShift(null)} />}
      {member != null && <MemberModal store={store} memberId={member} onClose={() => setMember(null)} onDeleted={() => setMember(null)} />}
      <Toasts toasts={store.toasts} />
      {trialExpired && (
        <div style={{
          position: "fixed", inset: 0, zIndex: 79,
          background: "rgba(10,20,15,.82)", backdropFilter: "blur(6px)",
          display: "flex", alignItems: "center", justifyContent: "center", padding: 24,
        }}>
          <div style={{
            background: "var(--surface)", borderRadius: 20, padding: "36px 36px 28px",
            maxWidth: 480, width: "100%", boxShadow: "0 32px 80px rgba(0,0,0,.5)",
            display: "flex", flexDirection: "column", gap: 20,
          }}>
            {/* Header */}
            <div style={{ textAlign: "center" }}>
              {/* Icon: Kalender mit abgelaufenem Zeitstempel */}
              <div style={{ display: "flex", justifyContent: "center", marginBottom: 14 }}>
                <div style={{ position: "relative", width: 64, height: 64 }}>
                  <svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect width="64" height="64" rx="16" fill="#fdf3e0"/>
                    <rect x="14" y="18" width="36" height="32" rx="5" fill="#e9c46a" opacity=".35"/>
                    <rect x="14" y="18" width="36" height="32" rx="5" stroke="#c9850a" strokeWidth="2"/>
                    <rect x="14" y="18" width="36" height="10" rx="5" fill="#c9850a"/>
                    <rect x="14" y="23" width="36" height="5" fill="#c9850a"/>
                    <rect x="22" y="13" width="4" height="8" rx="2" fill="#c9850a"/>
                    <rect x="38" y="13" width="4" height="8" rx="2" fill="#c9850a"/>
                    <circle cx="40" cy="42" r="9" fill="#fff" stroke="#c9850a" strokeWidth="2"/>
                    <path d="M40 38v5l3 2" stroke="#c9850a" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </div>
              </div>
              <h2 style={{ fontSize: 22, fontWeight: 800, color: "var(--ink)", marginBottom: 6 }}>
                Dein Testzeitraum ist abgelaufen
              </h2>
              <p style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.6 }}>
                Wähle einen Plan um ShiftBud weiter zu nutzen.<br />
                Deine Daten bleiben gespeichert.
              </p>
            </div>

            {/* Pläne */}
            <div style={{ display: "flex", gap: 10 }}>
              {[
                { id: "basic",      name: "Basic",  price: "24 €", staff: "10 MA" },
                { id: "pro",        name: "Pro",     price: "59 €", staff: "30 MA", highlight: true },
                { id: "enterprise", name: "Business",price: "99 €", staff: "80 MA" },
              ].map(p => (
                <button key={p.id}
                  onClick={async () => {
                    try {
                      const r = await fetch("/api/billing/checkout", {
                        method: "POST", credentials: "include",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ plan: p.id }),
                      });
                      const d = await r.json();
                      if (d.mock) {
                        await fetch(d.url, { credentials: "include" });
                        setTrialExpired(false);
                        store.loadBilling();
                        store.pushToast("Plan aktiviert!", "check");
                      } else if (d.url) { window.location.href = d.url; }
                    } catch (e) { store.pushToast("Fehler beim Upgrade", "alert"); }
                  }}
                  style={{
                    flex: 1, padding: "14px 8px", borderRadius: 12, cursor: "pointer",
                    border: p.highlight ? "2px solid var(--green)" : "1px solid var(--border-2)",
                    background: p.highlight ? "var(--green-mist)" : "var(--surface-2)",
                    display: "flex", flexDirection: "column", gap: 4, alignItems: "center",
                    transition: "all .14s",
                  }}>
                  {p.highlight && <span style={{ fontSize: 10, fontWeight: 700, color: "var(--green)", textTransform: "uppercase", letterSpacing: ".06em" }}>Beliebt</span>}
                  <span style={{ fontWeight: 700, fontSize: 14, color: "var(--ink)" }}>{p.name}</span>
                  <span style={{ fontWeight: 800, fontSize: 20, color: "var(--green-deep)" }}>{p.price}</span>
                  <span style={{ fontSize: 11, color: "var(--muted)" }}>{p.staff} · /Monat</span>
                </button>
              ))}
            </div>

            {/* Footer-Aktionen */}
            <div style={{ borderTop: "1px solid var(--border)", paddingTop: 14, display: "flex", flexDirection: "column", gap: 10 }}>
              {!trialDeleteConfirm ? (
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <button className="btn btn-ghost btn-sm" style={{ color: "var(--st-red)" }}
                    onClick={() => store.logout()}>
                    <Icon name="logout" /> Abmelden
                  </button>
                  <button style={{ background: "none", border: "none", cursor: "pointer",
                    fontSize: 11, color: "var(--faint)", display: "flex", alignItems: "center", gap: 4 }}
                    onClick={() => setTrialDeleteConfirm(true)}>
                    <Icon name="trash" style={{ width: 11, height: 11 }} /> Konto löschen
                  </button>
                </div>
              ) : (
                <div style={{ background: "var(--terra-bg)", borderRadius: 10, padding: "12px 14px",
                  display: "flex", flexDirection: "column", gap: 10 }}>
                  <div style={{ display: "flex", alignItems: "flex-start", gap: 8 }}>
                    <Icon name="alert" style={{ width: 15, height: 15, color: "var(--st-red)", flexShrink: 0, marginTop: 1 }} />
                    <span style={{ fontSize: 13, color: "#93331f", lineHeight: 1.45 }}>
                      Konto und alle Daten werden <strong>unwiderruflich gelöscht</strong>. Diese Aktion kann nicht rückgängig gemacht werden.
                    </span>
                  </div>
                  <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
                    <button className="btn btn-ghost btn-sm" onClick={() => setTrialDeleteConfirm(false)}>
                      Abbrechen
                    </button>
                    <button className="btn btn-danger btn-sm" onClick={async () => {
                      try {
                        await fetch("/auth/account", { method: "DELETE", credentials: "include" });
                        await store.logout();
                      } catch (e) { store.pushToast("Fehler beim Löschen", "alert"); }
                    }}>
                      <Icon name="trash" /> Endgültig löschen
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>);

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