// views.jsx — internal pages: Bookings / Event Types / Availability / Teams / Integrations / Billing / Settings

// ──────────────────────────────────────────────────────────────────────────
// Booking Edit Modal (admin reschedule / cancel)
// ──────────────────────────────────────────────────────────────────────────
function BookingEditModal({ booking, data, onClose, onSave }) {
  const event = data.events.find(e => e.id === booking.eventId);
  const [date,   setDate]   = React.useState(booking.date);
  const [time,   setTime]   = React.useState(booking.time);
  const [status, setStatus] = React.useState(booking.status);
  const [notes,  setNotes]  = React.useState(booking.notes || "");
  const [saving, setSaving] = React.useState(false);

  // Exclude current booking so its slot shows as free
  const dataWithout = React.useMemo(() => ({
    ...data, bookings: data.bookings.filter(b => b.id !== booking.id),
  }), [data, booking.id]);

  const slots = React.useMemo(() => {
    if (!event || !date) return [];
    return getAvailableTimes({ data: dataWithout, event, dateIso: date });
  }, [event, date, dataWithout]);

  const handleSave = async () => {
    setSaving(true);
    await onSave(booking.id, { date, time, status, notes });
    setSaving(false);
    onClose();
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-card" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h3 style={{margin:0}}>{booking.guestName}</h3>
            <span className="sub" style={{fontSize:12}}>{booking.eventName}</span>
          </div>
          <button className="modal-close" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body">
          <div className="field-grid">
            <div className="bk-field">
              <label>Date</label>
              <input type="date" className="bk-input" value={date}
                onChange={e => { setDate(e.target.value); setTime(""); }}/>
            </div>
            <div className="bk-field">
              <label>Time</label>
              <select className="bk-input" value={time} onChange={e => setTime(e.target.value)}>
                {time && !slots.includes(time) && <option value={time}>{time} (current)</option>}
                {slots.map(s => <option key={s} value={s}>{s}</option>)}
                {slots.length === 0 && !time && <option value="">No slots available</option>}
              </select>
            </div>
            <div className="bk-field" style={{gridColumn:"1 / -1"}}>
              <label>Status</label>
              <select className="bk-input" value={status} onChange={e => setStatus(e.target.value)}>
                <option>Confirmed</option>
                <option>Pending</option>
                <option>Rescheduled</option>
                <option>Cancelled</option>
                <option>No-show</option>
              </select>
            </div>
            <div className="bk-field" style={{gridColumn:"1 / -1"}}>
              <label>Notes</label>
              <textarea className="bk-textarea" rows={3} value={notes}
                onChange={e => setNotes(e.target.value)} placeholder="Internal notes…"/>
            </div>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={handleSave} disabled={saving || !date || !time}>
            {saving ? "Saving…" : "Save changes"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Bookings
// ──────────────────────────────────────────────────────────────────────────
function ViewBookings({ industry, data, actions, onOpenBooking }) {
  const [filter, setFilter] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const [editingBooking, setEditingBooking] = React.useState(null);

  const all = data.bookings;

  const counts = {
    all: all.length,
    confirmed: all.filter(b => b.status === "Confirmed").length,
    pending: all.filter(b => b.status === "Pending").length,
    cancelled: all.filter(b => b.status === "Cancelled").length,
  };

  const filtered = all.filter(b => {
    if (filter !== "all" && b.status.toLowerCase() !== filter) return false;
    if (search && !(b.guestName + b.eventName + b.guestEmail).toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  const FILTERS = [
    { id: "all", label: "All" },
    { id: "confirmed", label: "Confirmed" },
    { id: "pending", label: "Pending" },
    { id: "cancelled", label: "Cancelled" },
  ];

  return (
    <>
      <div className="view-h">
        <div>
          <h1>Bookings</h1>
          <div className="sub">Every appointment across your services.</div>
        </div>
        <div className="view-actions">
          <button className="btn ghost" onClick={() => downloadCsv("nexus-bookings.csv", [["Date", "Time", "Service", "Guest", "Email", "Status"], ...all.map((b) => [b.date, b.time, b.eventName, b.guestName, b.guestEmail, b.status])])}><I.arrow size={13}/> Export</button>
          <button className="btn primary" onClick={onOpenBooking}><I.cal size={13}/> New booking</button>
        </div>
      </div>

      <div className="toolbar">
        <div className="search">
          <I.show size={14}/>
          <input placeholder="Search guest or service…" value={search} onChange={e => setSearch(e.target.value)}/>
        </div>
        <div className="chips">
          {FILTERS.map(f => (
            <button key={f.id}
              className={"chip " + (filter === f.id ? "is-active" : "")}
              onClick={() => setFilter(f.id)}>
              {f.label} <span className="count">{counts[f.id]}</span>
            </button>
          ))}
        </div>
        <div style={{marginLeft: "auto"}}>
          <button className="btn ghost"><I.cal size={13}/> May 1 – 31, 2026</button>
        </div>
      </div>

      <div className="card">
        <table className="table">
          <thead>
            <tr>
              <th>Date & Time</th>
              <th>{industry.serviceLabel}</th>
              <th>Guest</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 && (
              <tr><td colSpan="5" style={{padding:"40px 20px", textAlign:"center", color:"var(--text-muted)"}}>
                No bookings match your filters.
              </td></tr>
            )}
            {filtered.map((r, i) => (
              <tr key={i}>
                <td><span className="cell-date"><I.cal size={13}/>{bookingDateTimeLabel(r)}</span></td>
                <td>{r.eventName}</td>
                <td>{r.guestName}</td>
                <td><span className={"pill " + r.status.toLowerCase()}>{r.status}</span></td>
                <td style={{textAlign:"right", display:"flex", gap:6, alignItems:"center", justifyContent:"flex-end"}}>
                  <select className="status-select" value={r.status} onChange={(e) => actions.updateBookingStatus(r.id, e.target.value)}>
                    <option>Confirmed</option>
                    <option>Pending</option>
                    <option>Rescheduled</option>
                    <option>Cancelled</option>
                    <option>No-show</option>
                  </select>
                  <button className="btn ghost" style={{padding:"4px 8px", fontSize:12}} onClick={() => setEditingBooking(r)}>Edit</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="pagination">
          <span>Showing {filtered.length} of {all.length}</span>
          <div className="nums">
            <button disabled><I.chevL size={12}/></button>
            <button className="is-active">1</button>
            <button>2</button>
            <button>3</button>
            <button><I.chev size={12}/></button>
          </div>
        </div>
      </div>
      {editingBooking && (
        <BookingEditModal
          booking={editingBooking}
          data={data}
          onClose={() => setEditingBooking(null)}
          onSave={(id, patch) => actions.rescheduleBooking(id, patch)}
        />
      )}
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Event Types
// ──────────────────────────────────────────────────────────────────────────
// ──────────────────────────────────────────────────────────────────────────
// Share Modal
// ──────────────────────────────────────────────────────────────────────────
function ShareModal({ event, profile, onClose }) {
  const [copied, setCopied] = React.useState(null); // null | "link" | "instagram" | "website"

  const bookingUrl = `${window.location.origin}/?book=${profile.bookingUrl}`;
  const caption = `📅 ${event.name}${event.duration ? ` — ${event.duration} mins` : ""}${event.price ? ` · £${event.price}` : ""}${event.maxSpaces ? ` · ${event.maxSpaces} spaces` : ""}\n\n${profile.bio || "Book your spot now — spaces are limited."}\n\n🔗 ${bookingUrl}`;

  const copy = (text, key) => {
    navigator.clipboard?.writeText(text).catch(() => {});
    setCopied(key);
    setTimeout(() => setCopied(null), 2200);
  };

  const shareToFacebook = () => {
    window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(bookingUrl)}&quote=${encodeURIComponent(caption)}`, "_blank", "width=600,height=500");
  };

  return (
    <div className="modal-backdrop" role="dialog" aria-modal="true">
      <div className="modal share-modal">
        <div className="modal-h">
          <div>
            <h3>Share class</h3>
            <div className="sub" style={{marginTop:2}}>{event.name}</div>
          </div>
          <button className="row-actions" onClick={onClose}><I.more size={16}/></button>
        </div>

        {/* Preview caption */}
        <div className="share-preview">
          <div className="share-preview-label">Caption preview</div>
          <div className="share-preview-text">{caption}</div>
        </div>

        {/* Platform buttons */}
        <div className="share-platforms">

          {/* Facebook */}
          <button className="share-platform-btn" style={{"--platform-color":"#1877F2"}} onClick={shareToFacebook}>
            <span className="share-platform-icon" style={{background:"#1877F2"}}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="white"><path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/></svg>
            </span>
            <div className="share-platform-info">
              <div className="share-platform-name">Facebook</div>
              <div className="share-platform-desc">Open share dialog</div>
            </div>
            <I.arrow size={14} className="share-platform-arrow"/>
          </button>

          {/* Instagram */}
          <button className="share-platform-btn" style={{"--platform-color":"#E1306C"}}
            onClick={() => copy(caption, "instagram")}>
            <span className="share-platform-icon" style={{background:"linear-gradient(135deg,#f09433,#e6683c,#dc2743,#cc2366,#bc1888)"}}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="20" rx="5"/><circle cx="12" cy="12" r="4.5"/><circle cx="17.5" cy="6.5" r="1" fill="white" stroke="none"/></svg>
            </span>
            <div className="share-platform-info">
              <div className="share-platform-name">Instagram</div>
              <div className="share-platform-desc">Copy caption &amp; link to paste</div>
            </div>
            {copied === "instagram"
              ? <span className="share-copied"><I.check size={13}/> Copied</span>
              : <I.copy size={14} className="share-platform-arrow"/>}
          </button>

          {/* Website / direct link */}
          <button className="share-platform-btn" style={{"--platform-color":"var(--accent)"}}
            onClick={() => copy(bookingUrl, "website")}>
            <span className="share-platform-icon" style={{background:"var(--accent)"}}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M3.5 12h17M12 3.5c2.5 3 2.5 14 0 17M12 3.5c-2.5 3-2.5 14 0 17"/></svg>
            </span>
            <div className="share-platform-info">
              <div className="share-platform-name">Website</div>
              <div className="share-platform-desc">{bookingUrl}</div>
            </div>
            {copied === "website"
              ? <span className="share-copied"><I.check size={13}/> Copied</span>
              : <I.copy size={14} className="share-platform-arrow"/>}
          </button>

        </div>

        <div className="modal-actions">
          <button className="btn ghost" onClick={onClose}>Close</button>
        </div>
      </div>
    </div>
  );
}

function ViewEventTypes({ industry, data, actions }) {
  const [editing, setEditing] = React.useState(null);
  const [sharing, setSharing] = React.useState(null);
  const currency = getCurrency(data.profile.currency);
  const bookingCounts = data.bookings.reduce((acc, b) => {
    acc[b.eventName] = (acc[b.eventName] || 0) + 1;
    return acc;
  }, {});
  const blankEvent = { name: "", duration: 30, slotInterval: 30, color: "#efa403", price: 0, location: "Google Meet", description: "", questions: [], requireTerms: false, termsText: "", paymentMode: "none", depositAmount: "", useCustomAvailability: false, customAvailability: [], enabled: true };

  return (
    <>
      <div className="view-h">
        <div>
          <h1>Event Types</h1>
          <div className="sub">Configure the services you offer and share booking links.</div>
        </div>
        <div className="view-actions">
          <button className="btn primary" onClick={() => setEditing(blankEvent)}><I.tag size={13}/> New service</button>
        </div>
      </div>

      <div className="events-grid">
        {data.events.map((e) => (
          <div key={e.id} className={"evt-card " + (e.enabled ? "" : "is-off")}>
            <div className="evt-card-h">
              <div className="evt-card-title">
                <div className="swatch-lg" style={{background: e.color}}/>
                <div>
                  <h3>{e.name}</h3>
                  <div className="duration"><I.clock size={11} style={{verticalAlign:"-1px", marginRight:4}}/>{e.duration} minutes · every {e.slotInterval || 30}</div>
                </div>
              </div>
              <label className="switch">
                <input type="checkbox" checked={e.enabled}
                  onChange={() => actions.toggleEvent(e.id)}/>
                <span className="track"><span className="knob"/></span>
              </label>
            </div>
            <div className="desc">{e.description}</div>
            <div className="evt-location"><I.location size={12}/>{e.location || "No location set"}</div>
            <div className="evt-card-meta">
              <div className="price">{e.price ? formatMoney(e.price, data.profile.currency) : "Free"}</div>
              {e.useCustomAvailability && <span className="bookings-count">Custom hours</span>}
              {Number(e.maxSpaces || 0) > 0 && <span className="bookings-count"><I.users size={11} style={{verticalAlign:"-1px", marginRight:3}}/>{e.maxSpaces} spaces</span>}
              {e.paymentMode === "term" && Number(e.termWeeks || 0) > 0 && <span className="bookings-count"><I.cal size={11} style={{verticalAlign:"-1px", marginRight:3}}/>{e.termWeeks}-wk term</span>}
              {e.paymentMode === "deposit" && <span className="bookings-count">Deposit</span>}
              {e.paymentMode === "term" && Number(e.classPrice || 0) > 0 && Number(e.termWeeks || 0) > 0 && (() => {
                const saving = (Number(e.classPrice) * Number(e.termWeeks)) - Number(e.price || 0);
                return saving > 0 ? <span className="bookings-count saving-badge">Save {formatMoney(saving, data.profile.currency)}</span> : null;
              })()}
              <span className="bookings-count">{bookingCounts[e.name] || 0} bookings</span>
            </div>
            <div className="evt-card-actions">
              <button title="Share" onClick={() => setSharing(e)}><I.share size={13}/></button>
              <button title="Edit" onClick={() => setEditing(e)}><I.cog size={13}/></button>
              <button title="Delete" onClick={() => actions.deleteEvent(e.id)}><I.more size={13}/></button>
            </div>
          </div>
        ))}
        <button className="add-card" onClick={() => setEditing(blankEvent)}>
          <span className="plus"><I.tag size={16}/></span>
          New service
        </button>
      </div>
      {editing && (
        <EventEditor
          event={editing}
          currency={currency.symbol}
          onClose={() => setEditing(null)}
          onSave={(event) => { actions.saveEvent(event); setEditing(null); }}
        />
      )}
      {sharing && (
        <ShareModal
          event={sharing}
          profile={data.profile}
          onClose={() => setSharing(null)}
        />
      )}
    </>
  );
}

function EventEditor({ event, currency, onClose, onSave }) {
  const [draft, setDraft] = React.useState(() => normalizeEvent ? normalizeEvent(event) : event);
  const set = (key, value) => setDraft((d) => ({ ...d, [key]: value }));
  const customDays = draft.customAvailability?.length ? draft.customAvailability : makeAvailability();
  const setCustomDay = (index, patch) => setDraft((d) => {
    const next = (d.customAvailability?.length ? d.customAvailability : makeAvailability()).map((day, i) => i === index ? { ...day, ...patch } : day);
    return { ...d, customAvailability: next };
  });
  const valid = draft.name.trim().length > 1 && Number(draft.duration) > 0;
  const addQuestion = () => setDraft((d) => ({
    ...d,
    questions: [...(d.questions || []), { id: uid("q"), label: "", type: "text", required: false }],
  }));
  const updateQuestion = (id, patch) => setDraft((d) => ({
    ...d,
    questions: (d.questions || []).map((q) => q.id === id ? { ...q, ...patch } : q),
  }));
  const removeQuestion = (id) => setDraft((d) => ({
    ...d,
    questions: (d.questions || []).filter((q) => q.id !== id),
  }));
  return (
    <div className="modal-backdrop" role="dialog" aria-modal="true">
      <div className="modal">
        <div className="modal-h">
          <h3>{event.id ? "Edit service" : "New service"}</h3>
          <button className="row-actions" onClick={onClose}><I.more size={16}/></button>
        </div>
        <div className="field-grid">
          <div className="bk-field"><label>Name</label><input className="bk-input" value={draft.name} onChange={(e) => set("name", e.target.value)}/></div>
          <div className="bk-field">
            <label>Duration</label>
            <select className="bk-input" value={draft.duration} onChange={(e) => set("duration", e.target.value)}>
              <option value="15">15 minutes</option>
              <option value="30">30 minutes</option>
              <option value="45">45 minutes</option>
              <option value="60">60 minutes</option>
            </select>
          </div>
          <div className="bk-field">
            <label>Slot starts every</label>
            <select className="bk-input" value={draft.slotInterval || 30} onChange={(e) => set("slotInterval", e.target.value)}>
              <option value="15">15 minutes</option>
              <option value="30">30 minutes</option>
              <option value="45">45 minutes</option>
              <option value="60">60 minutes</option>
            </select>
          </div>
          <div className="bk-field">
            <label>Max spaces <span className="opt">(0 = unlimited)</span></label>
            <input className="bk-input" type="text" inputMode="numeric" placeholder="0" value={draft.maxSpaces || ""} onChange={(e) => set("maxSpaces", e.target.value)}/>
          </div>
          <div className="bk-field"><label>Location</label><input className="bk-input" value={draft.location} onChange={(e) => set("location", e.target.value)}/></div>
        </div>
        <div className="bk-field" style={{marginTop:16}}>
          <label>Description</label>
          <textarea className="bk-textarea" value={draft.description} onChange={(e) => set("description", e.target.value)}/>
        </div>
        <div className="color-picker-row" style={{marginTop:16}}>
          {["#efa403", "#7aa7ff", "#a78bfa", "#6ee7a3", "#f59e9e"].map((color) => (
            <button key={color} className={"color-swatch " + (draft.color === color ? "is-selected" : "")} style={{background: color}} onClick={() => set("color", color)}/>
          ))}
        </div>
        <div className="event-editor-section">
          <div className="card-h" style={{padding:0, border:0, marginBottom:10}}>
            <h3>Payments</h3>
            <span className="sub">Stripe and PayPal can be offered at checkout.</span>
          </div>
          <div className="field-grid">
            <div className="bk-field">
              <label>Payment at booking</label>
              <select className="bk-input" value={draft.paymentMode || "none"} onChange={(e) => set("paymentMode", e.target.value)}>
                <option value="none">No payment required</option>
                <option value="full">Pay per class (full price)</option>
                <option value="deposit">Pay per class (deposit)</option>
                <option value="term">Pay by term (full term upfront)</option>
              </select>
            </div>
            {(draft.paymentMode === "none" || draft.paymentMode === "full") && (
              <div className="bk-field">
                <label>Price per class ({currency})</label>
                <input className="bk-input" type="text" inputMode="numeric" value={draft.price} onChange={(e) => set("price", e.target.value)}/>
              </div>
            )}
            {draft.paymentMode === "deposit" && (
              <div className="bk-field">
                <label>Deposit amount ({currency})</label>
                <input className="bk-input" type="text" inputMode="numeric" value={draft.depositAmount || ""} onChange={(e) => set("depositAmount", e.target.value)}/>
              </div>
            )}
            {draft.paymentMode === "term" && (
              <>
                <div className="bk-field">
                  <label>Term price ({currency})</label>
                  <input className="bk-input" type="text" inputMode="numeric" value={draft.price} onChange={(e) => set("price", e.target.value)}/>
                </div>
                <div className="bk-field">
                  <label>Price per individual class ({currency})</label>
                  <input className="bk-input" type="text" inputMode="numeric" value={draft.classPrice || ""} placeholder="0.00" onChange={(e) => set("classPrice", e.target.value)}/>
                </div>
                <div className="bk-field" style={{gridColumn:"1 / -1"}}>
                  <label>Term length</label>
                  <select className="bk-input" value={draft.termWeeks || 4} onChange={(e) => set("termWeeks", Number(e.target.value))}>
                    <option value={4}>4 weeks</option>
                    <option value={6}>6 weeks</option>
                    <option value={8}>8 weeks</option>
                    <option value={10}>10 weeks</option>
                    <option value={12}>12 weeks</option>
                  </select>
                </div>
                {(() => {
                  const saving = (Number(draft.classPrice || 0) * Number(draft.termWeeks || 0)) - Number(draft.price || 0);
                  if (saving <= 0 || !Number(draft.classPrice) || !Number(draft.price)) return null;
                  return (
                    <div className="term-saving-preview" style={{gridColumn:"1 / -1"}}>
                      <I.tag size={13}/> Saves {formatMoney(saving, currency)} vs booking per class
                    </div>
                  );
                })()}
              </>
            )}
          </div>
        </div>
        <div className="event-editor-section">
          <div className="card-h" style={{padding:0, border:0, marginBottom:10}}>
            <h3>Service-specific hours</h3>
            <span className="sub">Useful for different pool locations and lesson types.</span>
          </div>
          <label className="mini-check">
            <input type="checkbox" checked={!!draft.useCustomAvailability} onChange={() => {
              setDraft((d) => ({
                ...d,
                useCustomAvailability: !d.useCustomAvailability,
                customAvailability: d.customAvailability?.length ? d.customAvailability : makeAvailability(),
              }));
            }}/>
            Use different hours for this service
          </label>
          {draft.useCustomAvailability && (
            <div className="service-hours-editor">
              {customDays.map((day, index) => (
                <div className="service-hours-row" key={day.name}>
                  <label className="switch">
                    <input type="checkbox" checked={!!day.on} onChange={() => setCustomDay(index, { on: !day.on })}/>
                    <span className="track"><span className="knob"/></span>
                  </label>
                  <span>{day.name}</span>
                  {day.on ? (
                    <>
                      <input className="time-input" type="time" value={day.start} onChange={(e) => setCustomDay(index, { start: e.target.value })}/>
                      <input className="time-input" type="time" value={day.end} onChange={(e) => setCustomDay(index, { end: e.target.value })}/>
                    </>
                  ) : (
                    <span className="unavail-tag">Unavailable</span>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
        <div className="event-editor-section">
          <div className="card-h" style={{padding:0, border:0, marginBottom:10}}>
            <h3>Booking questions</h3>
            <button className="card-link" onClick={addQuestion}>+ Add question</button>
          </div>
          <div className="question-list">
            {(draft.questions || []).map((question) => (
              <div className="question-row" key={question.id}>
                <input className="bk-input" placeholder="Question shown to guest" value={question.label} onChange={(e) => updateQuestion(question.id, { label: e.target.value })}/>
                <select className="bk-input" value={question.type || "text"} onChange={(e) => updateQuestion(question.id, { type: e.target.value })}>
                  <option value="text">Short answer</option>
                  <option value="textarea">Long answer</option>
                </select>
                <label className="mini-check"><input type="checkbox" checked={!!question.required} onChange={() => updateQuestion(question.id, { required: !question.required })}/> Required</label>
                <button className="row-actions" onClick={() => removeQuestion(question.id)}><I.more size={14}/></button>
              </div>
            ))}
            {(draft.questions || []).length === 0 && <div className="empty-inline">No extra questions yet.</div>}
          </div>
        </div>
        <div className="event-editor-section">
          <label className="mini-check">
            <input type="checkbox" checked={!!draft.requireTerms} onChange={() => set("requireTerms", !draft.requireTerms)}/>
            Require guest to accept terms
          </label>
          {draft.requireTerms && (
            <textarea className="bk-textarea" style={{marginTop:10}} value={draft.termsText || ""} onChange={(e) => set("termsText", e.target.value)} placeholder="Terms text shown beside the checkbox"/>
          )}
        </div>
        <div className="modal-actions">
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} onClick={() => onSave(draft)}>Save service</button>
        </div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Availability
// ──────────────────────────────────────────────────────────────────────────
function ViewAvailability({ data, actions }) {
  const [days, setDays] = React.useState(data.availability);
  const [blockDate, setBlockDate] = React.useState(todayIso());
  const [blockReason, setBlockReason] = React.useState("");
  const [timeBlock, setTimeBlock] = React.useState({ date: todayIso(), start: "12:00", end: "13:00", reason: "" });
  React.useEffect(() => setDays(data.availability), [data.availability]);

  return (
    <>
      <div className="view-h">
        <div>
          <h1>Availability</h1>
          <div className="sub">Set when you're open. Blocked dates override your weekly hours.</div>
        </div>
        <div className="view-actions">
          <button className="btn ghost"><I.copy size={13}/> Copy from another team member</button>
          <button className="btn primary" onClick={() => actions.saveAvailability(days)}>Save changes</button>
        </div>
      </div>

      <div className="avail-grid">
        <div className="card">
          <div className="card-h">
            <h3>Weekly hours <span className="sub">(GMT-4 Eastern Time)</span></h3>
          </div>
          <div className="avail-editor">
            {days.map((d, i) => (
              <div key={d.name} className="avail-edit-row">
                <div className="day-toggle">
                  <label className="switch">
                    <input type="checkbox" checked={d.on}
                      onChange={() => setDays(s => s.map((x, j) => j === i ? {...x, on: !x.on} : x))}/>
                    <span className="track"><span className="knob"/></span>
                  </label>
                  <span className="day-name">{d.name}</span>
                </div>
                {d.on ? (
                  <div className="time-pickers">
                    <input className="time-input" type="time" value={d.start}
                      onChange={e => setDays(s => s.map((x, j) => j === i ? {...x, start: e.target.value} : x))}/>
                    <span className="dash">—</span>
                    <input className="time-input" type="time" value={d.end}
                      onChange={e => setDays(s => s.map((x, j) => j === i ? {...x, end: e.target.value} : x))}/>
                    <button className="add-slot"><I.bolt size={11}/> Add slot</button>
                  </div>
                ) : (
                  <span className="unavail-tag">Unavailable</span>
                )}
                <button className="row-actions" title="Duplicate to all"><I.copy size={14}/></button>
              </div>
            ))}
          </div>
        </div>

        <div style={{display:"flex", flexDirection:"column", gap:20}}>
          <div className="card">
            <div className="card-h">
              <h3>Blocked dates</h3>
              <button className="card-link">+ Add</button>
            </div>
            <div className="blocked-list">
              {data.blockedDates.map((b) => (
                <div className="blocked-row" key={b.id}>
                  <div>
                    <div style={{fontWeight:500}}>{formatIsoDate(b.date, { year: true })}</div>
                    <div className="reason">{b.reason}</div>
                  </div>
                  <button className="row-actions" onClick={() => actions.removeBlockedDate(b.id)}><I.more size={14}/></button>
                </div>
              ))}
              <div className="blocked-add">
                <input className="bk-input" type="text" placeholder="YYYY-MM-DD" value={blockDate} onChange={(e) => setBlockDate(e.target.value)}/>
                <input className="bk-input" placeholder="Reason" value={blockReason} onChange={(e) => setBlockReason(e.target.value)}/>
                <button className="btn primary" onClick={() => { if (blockDate) actions.addBlockedDate(blockDate, blockReason || "Blocked"); setBlockReason(""); }}>Add</button>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-h">
              <h3>Blocked time slots</h3>
              <span className="sub">Hide specific times on a date</span>
            </div>
            <div className="blocked-list">
              {(data.blockedTimes || []).map((b) => (
                <div className="blocked-row" key={b.id}>
                  <div>
                    <div style={{fontWeight:500}}>{formatIsoDate(b.date, { year: true })} · {b.start} – {b.end}</div>
                    <div className="reason">{b.reason}</div>
                  </div>
                  <button className="row-actions" onClick={() => actions.removeBlockedTime(b.id)}><I.more size={14}/></button>
                </div>
              ))}
              <div className="blocked-add time-exception-add">
                <input className="bk-input" type="text" placeholder="YYYY-MM-DD" value={timeBlock.date} onChange={(e) => setTimeBlock({...timeBlock, date: e.target.value})}/>
                <input className="bk-input" type="time" value={timeBlock.start} onChange={(e) => setTimeBlock({...timeBlock, start: e.target.value})}/>
                <input className="bk-input" type="time" value={timeBlock.end} onChange={(e) => setTimeBlock({...timeBlock, end: e.target.value})}/>
                <input className="bk-input" placeholder="Reason" value={timeBlock.reason} onChange={(e) => setTimeBlock({...timeBlock, reason: e.target.value})}/>
                <button className="btn primary" onClick={() => {
                  if (timeBlock.date && timeBlock.start && timeBlock.end) {
                    actions.addBlockedTime({...timeBlock, reason: timeBlock.reason || "Blocked time"});
                    setTimeBlock({...timeBlock, reason: ""});
                  }
                }}>Add</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Teams
// ──────────────────────────────────────────────────────────────────────────
function ViewTeams() {
  const members = [
    { name: "Nora Singh",   role: "Owner",      initials: "NS", status: "online", booked: 28, services: 4 },
    { name: "Maya Reyes",   role: "Senior",     initials: "MR", status: "online", booked: 22, services: 3 },
    { name: "Jordan Park",  role: "Stylist",    initials: "JP", status: "away",   booked: 14, services: 2 },
    { name: "Cameron Lee",  role: "Stylist",    initials: "CL", status: "off",    booked: 9,  services: 2 },
    { name: "Aisha Bello",  role: "Apprentice", initials: "AB", status: "online", booked: 6,  services: 1 },
  ];

  return (
    <>
      <div className="view-h">
        <div>
          <h1>Teams</h1>
          <div className="sub">5 members · 3 online now</div>
        </div>
        <div className="view-actions">
          <button className="btn ghost">Manage roles</button>
          <button className="btn primary"><I.users size={13}/> Invite member</button>
        </div>
      </div>

      <div className="team-grid">
        {members.map((m, i) => (
          <div className="team-card" key={i}>
            <span className={"status-dot " + m.status}/>
            <div className="avatar lg">{m.initials}</div>
            <h4>{m.name}</h4>
            <div className="role">{m.role}</div>
            <div className="stats">
              <div className="stat"><div className="num">{m.booked}</div><div className="lbl">Booked</div></div>
              <div className="stat"><div className="num">{m.services}</div><div className="lbl">Services</div></div>
            </div>
          </div>
        ))}
        <button className="add-card">
          <span className="plus"><I.users size={16}/></span>
          Invite member
        </button>
      </div>
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Integrations
// ──────────────────────────────────────────────────────────────────────────
function ViewIntegrations({ data, actions }) {
  const catalog = [
    { name: "Google Calendar", desc: "Two-way sync of all appointments.", logo: "G", bg: "linear-gradient(135deg,#4285F4,#34A853)" },
    { name: "Stripe",          desc: "Take deposits and full payments at booking.", logo: "S", bg: "#635BFF" },
    { name: "PayPal",          desc: "Offer PayPal as a guest checkout option.", logo: "P", bg: "#0070BA" },
    { name: "Apple Calendar",  desc: "Sync your iCloud calendar both ways.", logo: "🍎", bg: "var(--surface-2)" },
    { name: "WhatsApp",        desc: "Send booking confirmations via WhatsApp.", logo: "W", bg: "#25D366" },
    { name: "Square",          desc: "Sync inventory and accept payments.", logo: "□", bg: "#000" },
  ];
  const connected = catalog.filter((c) => data.integrations[c.name]?.connected);
  const available = catalog.filter((c) => !data.integrations[c.name]?.connected);

  return (
    <>
      <div className="view-h">
        <div>
          <h1>Integrations</h1>
          <div className="sub">Connect the tools you use to power your business.</div>
        </div>
        <div className="view-actions">
          <button className="btn ghost">Browse all</button>
        </div>
      </div>

      <h3 style={{margin:"4px 0 14px", fontSize:13, fontWeight:500, color:"var(--text-muted)", textTransform:"uppercase", letterSpacing:"0.06em"}}>
        Connected · {connected.length}
      </h3>
      <div className="intg-grid" style={{marginBottom: 28}}>
        {connected.map((c, i) => (
          <div className="intg-card" key={i}>
            <div className="intg-card-h">
              <div className="intg-logo" style={{background: c.bg, color: c.color || "#fff"}}>{c.logo}</div>
              <div className="name">{c.name}</div>
            </div>
            <div className="desc">{c.desc}</div>
            <div className="actions">
              <span className="intg-status">Connected <I.check size={12}/></span>
              <button className="btn ghost" style={{padding:"5px 10px", fontSize:12}} onClick={() => actions.disconnectIntegration(c.name)}>Disconnect</button>
            </div>
          </div>
        ))}
      </div>

      <h3 style={{margin:"4px 0 14px", fontSize:13, fontWeight:500, color:"var(--text-muted)", textTransform:"uppercase", letterSpacing:"0.06em"}}>
        Available
      </h3>
      <div className="intg-grid">
        {available.map((c, i) => (
          <div className="intg-card" key={i}>
            <div className="intg-card-h">
              <div className="intg-logo" style={{background: c.bg, color: c.color || "#fff"}}>{c.logo}</div>
              <div className="name">{c.name}</div>
            </div>
            <div className="desc">{c.desc}</div>
            <div className="actions">
              <span style={{fontSize:12, color:"var(--text-muted)"}}>Free</span>
              <button className="btn primary" style={{padding:"5px 12px", fontSize:12}} onClick={() => actions.connectIntegration(c.name)}>Connect</button>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Billing
// ──────────────────────────────────────────────────────────────────────────
function ViewBilling({ industry, data }) {
  const currency = getCurrency(data.profile.currency);
  const invoices = [
    { id: "INV-2026-005", date: "May 1, 2026",  amount: `${currency.symbol}29.00`, status: "Paid" },
    { id: "INV-2026-004", date: "Apr 1, 2026",  amount: `${currency.symbol}29.00`, status: "Paid" },
    { id: "INV-2026-003", date: "Mar 1, 2026",  amount: `${currency.symbol}29.00`, status: "Paid" },
    { id: "INV-2026-002", date: "Feb 1, 2026",  amount: `${currency.symbol}29.00`, status: "Paid" },
    { id: "INV-2026-001", date: "Jan 1, 2026",  amount: `${currency.symbol}29.00`, status: "Paid" },
  ];

  return (
    <>
      <div className="view-h">
        <div>
          <h1>Billing</h1>
          <div className="sub">Plan, payment, and invoice history.</div>
        </div>
      </div>

      <div className="billing-top">
        <div className="plan-card">
          <span className="badge">Current plan</span>
          <h2>Professional</h2>
          <div className="desc">Unlimited bookings, custom branding, and priority support.</div>
          <div className="price">{currency.symbol}29<small>/month</small></div>
          <div className="actions" style={{marginTop:18}}>
            <button className="btn primary">Upgrade to Business</button>
            <button className="btn ghost">Cancel plan</button>
          </div>
        </div>

        <div className="card usage-card">
          <h3>Usage this month</h3>
          <div className="usage-row">
            <div className="usage-h"><span className="label">Bookings</span><span className="val">428 / Unlimited</span></div>
            <div className="usage-bar"><div className="fill" style={{width:"28%"}}/></div>
          </div>
          <div className="usage-row">
            <div className="usage-h"><span className="label">Team members</span><span className="val">5 / 10</span></div>
            <div className="usage-bar"><div className="fill" style={{width:"50%"}}/></div>
          </div>
          <div className="usage-row">
            <div className="usage-h"><span className="label">SMS reminders</span><span className="val">86 / 100</span></div>
            <div className="usage-bar"><div className="fill warn" style={{width:"86%"}}/></div>
          </div>
          <div className="usage-row">
            <div className="usage-h"><span className="label">Storage</span><span className="val">1.2 / 5 GB</span></div>
            <div className="usage-bar"><div className="fill" style={{width:"24%"}}/></div>
          </div>
        </div>
      </div>

      <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:20, marginBottom:24}}>
        <div>
          <h3 style={{margin:"0 0 12px", fontSize:13, fontWeight:500, color:"var(--text-muted)", textTransform:"uppercase", letterSpacing:"0.06em"}}>
            Payment method
          </h3>
          <div className="payment-card">
            <div className="card-art">VISA</div>
            <div style={{flex:1}}>
              <div className="num">•••• •••• •••• 4242</div>
              <div className="exp">Expires 08/2028 · Nora Singh</div>
            </div>
            <button className="btn ghost">Update</button>
          </div>
        </div>
        <div>
          <h3 style={{margin:"0 0 12px", fontSize:13, fontWeight:500, color:"var(--text-muted)", textTransform:"uppercase", letterSpacing:"0.06em"}}>
            Billing email
          </h3>
          <div className="payment-card">
            <div className="card-art" style={{background:"var(--surface-2)"}}><I.bell size={14}/></div>
            <div style={{flex:1}}>
              <div className="num" style={{fontSize:13}}>nora@apexadvisors.com</div>
              <div className="exp">Receipts & renewal notices</div>
            </div>
            <button className="btn ghost">Edit</button>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-h">
          <h3>Invoices</h3>
          <button className="card-link">Download all</button>
        </div>
        <table className="table">
          <thead>
            <tr><th>Invoice</th><th>Date</th><th>Amount</th><th>Status</th><th></th></tr>
          </thead>
          <tbody>
            {invoices.map((inv, i) => (
              <tr key={inv.id}>
                <td style={{fontVariantNumeric:"tabular-nums"}}>{inv.id}</td>
                <td>{inv.date}</td>
                <td style={{fontVariantNumeric:"tabular-nums"}}>{inv.amount}</td>
                <td><span className="pill confirmed">{inv.status}</span></td>
                <td style={{textAlign:"right"}}>
                  <button className="row-actions" title="Download"><I.arrow size={14} style={{transform:"rotate(90deg)"}}/></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Settings
// ──────────────────────────────────────────────────────────────────────────
const COUNTRIES = [
  { code: "GB", name: "United Kingdom" }, { code: "US", name: "United States" },
  { code: "IE", name: "Ireland" },        { code: "AU", name: "Australia" },
  { code: "CA", name: "Canada" },         { code: "NZ", name: "New Zealand" },
  { code: "DE", name: "Germany" },        { code: "FR", name: "France" },
  { code: "ES", name: "Spain" },          { code: "IT", name: "Italy" },
  { code: "NL", name: "Netherlands" },    { code: "BE", name: "Belgium" },
  { code: "SE", name: "Sweden" },         { code: "NO", name: "Norway" },
  { code: "DK", name: "Denmark" },        { code: "FI", name: "Finland" },
  { code: "PT", name: "Portugal" },       { code: "CH", name: "Switzerland" },
  { code: "AT", name: "Austria" },        { code: "PL", name: "Poland" },
];

function ViewSettings({ data, actions }) {
  const [tab, setTab] = React.useState("profile");
  const [profileDraft, setProfileDraft] = React.useState(data.profile);
  const [notifs, setNotifs] = React.useState(data.notifications || {});
  React.useEffect(() => setProfileDraft(data.profile), [data.profile]);
  React.useEffect(() => setNotifs(data.notifications || {}), [data.notifications]);
  const setProfile = (key, value) => setProfileDraft((p) => ({ ...p, [key]: value }));
  const swatches = ["#efa403", "#0070BA", "#635BFF", "#10b981", "#f59e9e", "#111827"];

  // ── Company info state ────────────────────────────────────
  const companyFields = ["vatNumber","companyName","address1","address2","city","postcode","country","companyEmail","companyPhone","website","whatsapp","facebook","instagram","twitter","linkedin","hideEmail","hideAddress","companyLat","companyLon"];
  const [company, setCompanyDraft] = React.useState(() => {
    const c = {};
    companyFields.forEach(k => { c[k] = data.profile[k] ?? ""; });
    c.country = c.country || "GB";
    c.hideEmail = !!data.profile.hideEmail;
    c.hideAddress = !!data.profile.hideAddress;
    return c;
  });
  const setComp = (key, value) => setCompanyDraft(d => ({ ...d, [key]: value }));
  const saveCompany = () => actions.updateProfile({ ...data.profile, ...company });

  // ── Map state ─────────────────────────────────────────────
  const DEFAULT_MAP = "https://www.openstreetmap.org/export/embed.html?bbox=-5.5,49.8,2.1,58.7&layer=mapnik";
  const [mapQuery, setMapQuery] = React.useState("");
  const [mapSrc, setMapSrc] = React.useState(() => {
    const lat = data.profile.companyLat, lon = data.profile.companyLon;
    if (lat && lon) {
      const d = 0.02;
      return `https://www.openstreetmap.org/export/embed.html?bbox=${lon-d},${lat-d},${lon+d},${lat+d}&layer=mapnik&marker=${lat},${lon}`;
    }
    return DEFAULT_MAP;
  });
  const [mapBusy, setMapBusy] = React.useState(false);
  const [mapErr, setMapErr]   = React.useState("");

  const searchMap = async () => {
    const q = mapQuery.trim();
    if (!q) return;
    setMapBusy(true); setMapErr("");
    try {
      const res = await fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q)}&format=json&limit=1`);
      const results = await res.json();
      if (!results.length) { setMapErr("Address not found — try adding a city or postcode."); return; }
      const { lat, lon, boundingbox } = results[0];
      const [s, n, w, e] = (boundingbox || []).map(Number);
      const bbox = boundingbox ? `${w},${s},${e},${n}` : `${lon-0.01},${lat-0.01},${lon+0.01},${lat+0.01}`;
      setMapSrc(`https://www.openstreetmap.org/export/embed.html?bbox=${bbox}&layer=mapnik&marker=${lat},${lon}`);
      setComp("companyLat", Number(lat));
      setComp("companyLon", Number(lon));
    } catch { setMapErr("Search failed — please try again."); }
    finally { setMapBusy(false); }
  };

  const sections = [
    { id: "profile",      label: "Profile" },
    { id: "branding",     label: "Branding" },
    { id: "company",      label: "Company" },
    { id: "notifications",label: "Notifications" },
    { id: "security",     label: "Security" },
  ];

  return (
    <>
      <div className="view-h">
        <div>
          <h1>Settings</h1>
          <div className="sub">Profile, branding, notifications, and account preferences.</div>
        </div>
      </div>

      <div className="settings-layout">
        <nav className="settings-nav">
          {sections.map(s => (
            <button key={s.id}
              className={tab === s.id ? "is-active" : ""}
              onClick={() => setTab(s.id)}>{s.label}</button>
          ))}
        </nav>

        <div>
          {tab === "profile" && (
            <div className="settings-section">
              <h3 className="section-h">Profile</h3>
              <p className="section-sub">How you appear to guests on your booking page.</p>
              <div className="card settings-card">
                <div style={{display:"flex", gap:18, alignItems:"center", marginBottom:24}}>
                  <div className="avatar lg">{profileDraft.initials}</div>
                  <div style={{display:"flex", gap:8}}>
                    <button className="btn">Upload photo</button>
                    <button className="btn ghost">Remove</button>
                  </div>
                </div>
                <div className="field-grid">
                  <div className="bk-field"><label>Full name</label><input className="bk-input" value={profileDraft.name} onChange={(e) => setProfile("name", e.target.value)}/></div>
                  <div className="bk-field"><label>Display title</label><input className="bk-input" value={profileDraft.title} onChange={(e) => setProfile("title", e.target.value)}/></div>
                  <div className="bk-field"><label>Email</label><input className="bk-input" value={profileDraft.email} onChange={(e) => setProfile("email", e.target.value)}/></div>
                  <div className="bk-field"><label>Phone</label><input className="bk-input" value={profileDraft.phone} onChange={(e) => setProfile("phone", e.target.value)}/></div>
                  <div className="bk-field">
                    <label>Currency</label>
                    <select className="bk-input" value={profileDraft.currency || "GBP"} onChange={(e) => setProfile("currency", e.target.value)}>
                      {CURRENCIES.map((currency) => (
                        <option key={currency.code} value={currency.code}>
                          {currency.symbol} {currency.code} · {currency.label}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>
                <div className="field-grid single" style={{marginTop:16}}>
                  <div className="bk-field">
                    <label>Public bio <span className="opt">(shown on booking page)</span></label>
                    <textarea className="bk-textarea" value={profileDraft.bio} onChange={(e) => setProfile("bio", e.target.value)}/>
                  </div>
                </div>
                <div style={{display:"flex", justifyContent:"flex-end", gap:8, marginTop:18}}>
                  <button className="btn ghost" onClick={() => setProfileDraft(data.profile)}>Cancel</button>
                  <button className="btn primary" onClick={() => actions.updateProfile({ ...profileDraft, initials: (profileDraft.name || "").split(" ").map((p) => p[0] || "").join("").slice(0, 2).toUpperCase() || getLogoText(profileDraft) })}>Save changes</button>
                </div>
              </div>
            </div>
          )}

          {tab === "branding" && (
            <div className="settings-section">
              <h3 className="section-h">Branding</h3>
              <p className="section-sub">Make the booking page feel like yours.</p>
              <div className="card settings-card">
                <div className="field-grid">
                  <div className="bk-field"><label>Brand name</label><input className="bk-input" value={profileDraft.brandName} onChange={(e) => setProfile("brandName", e.target.value)}/></div>
                  <div className="bk-field"><label>Booking URL</label><input className="bk-input" value={profileDraft.bookingUrl} onChange={(e) => setProfile("bookingUrl", e.target.value)}/></div>
                  <div className="bk-field"><label>Logo text</label><input className="bk-input" maxLength="3" value={profileDraft.logoText || getLogoText(profileDraft)} onChange={(e) => setProfile("logoText", e.target.value.toUpperCase())}/></div>
                  <div className="bk-field"><label>Logo background</label><input className="bk-input" value={profileDraft.logoBg || profileDraft.accent} onChange={(e) => setProfile("logoBg", e.target.value)}/></div>
                  <div className="bk-field" style={{gridColumn:"1 / -1"}}><label>Logo image URL <span className="opt">(optional)</span></label><input className="bk-input" value={profileDraft.logoUrl || ""} placeholder="https://example.com/logo.png" onChange={(e) => setProfile("logoUrl", e.target.value)}/></div>
                </div>
                <div style={{marginTop:18}}>
                  <label style={{fontSize:12, color:"var(--text-muted)", display:"block", marginBottom:8}}>Brand accent color</label>
                  <div className="color-picker-row">
                    {swatches.map(s => (
                      <button key={s} className={"color-swatch " + (profileDraft.accent === s ? "is-selected" : "")}
                        style={{background: s}} onClick={() => setProfileDraft((p) => ({ ...p, accent: s, logoBg: p.logoBg || s }))} aria-label={s}/>
                    ))}
                    <input className="bk-input" style={{maxWidth:120, marginLeft:8}}
                      value={profileDraft.accent} onChange={e => setProfile("accent", e.target.value)}/>
                  </div>
                </div>
                <div style={{marginTop:18}}>
                  <label style={{fontSize:12, color:"var(--text-muted)", display:"block", marginBottom:8}}>Brand preview</label>
                  <div className="brand-preview" style={getBrandStyle(profileDraft)}>
                    <div className="sb-mark" style={{width:48, height:48, fontSize:18}}>{profileDraft.logoUrl ? <img src={profileDraft.logoUrl} alt=""/> : getLogoText(profileDraft)}</div>
                    <div>
                      <div className="brand-preview-name">{profileDraft.brandName}</div>
                      <div className="brand-preview-url">{profileDraft.bookingUrl}</div>
                    </div>
                    <button className="btn primary" style={{marginLeft:"auto"}}>Book now</button>
                  </div>
                </div>
                <div className="notif-row" style={{marginTop:18}}>
                  <div>
                    <div className="title">White-label public booking page</div>
                    <div className="desc">Hide Nexus Booking branding from guest booking and confirmation pages.</div>
                  </div>
                  <label className="switch">
                    <input type="checkbox" checked={!!profileDraft.whiteLabel}
                      onChange={() => setProfile("whiteLabel", !profileDraft.whiteLabel)}/>
                    <span className="track"><span className="knob"/></span>
                  </label>
                </div>
                <div style={{display:"flex", justifyContent:"flex-end", gap:8, marginTop:24}}>
                  <button className="btn primary" onClick={() => actions.updateProfile(profileDraft)}>Save changes</button>
                </div>
              </div>
            </div>
          )}

          {tab === "company" && (
            <div className="settings-section">
              <h3 className="section-h">Company Information</h3>
              <p className="section-sub">Business details shown on your booking page and in confirmation emails.</p>
              <div className="company-grid">

                {/* ── Left column ── */}
                <div style={{display:"flex", flexDirection:"column", gap:20}}>
                  <div className="card settings-card">
                    <h4 className="company-section-h">General information</h4>
                    <div className="field-grid single">
                      <div className="bk-field"><label>VAT / Tax number</label><input className="bk-input" value={company.vatNumber} onChange={e => setComp("vatNumber", e.target.value)} placeholder="GB123456789"/></div>
                      <div className="bk-field"><label>Business name <span className="req">*</span></label><input className="bk-input" value={company.companyName} onChange={e => setComp("companyName", e.target.value)}/></div>
                      <div className="bk-field"><label>Address line 1</label><input className="bk-input" value={company.address1} onChange={e => setComp("address1", e.target.value)}/></div>
                      <div className="bk-field"><label>Address line 2</label><input className="bk-input" value={company.address2} onChange={e => setComp("address2", e.target.value)}/></div>
                      <div className="bk-field"><label>City</label><input className="bk-input" value={company.city} onChange={e => setComp("city", e.target.value)}/></div>
                      <div className="bk-field"><label>Postcode</label><input className="bk-input" value={company.postcode} onChange={e => setComp("postcode", e.target.value)}/></div>
                      <div className="bk-field">
                        <label>Country</label>
                        <select className="bk-input" value={company.country} onChange={e => setComp("country", e.target.value)}>
                          {COUNTRIES.map(c => <option key={c.code} value={c.code}>{c.name}</option>)}
                        </select>
                      </div>
                      <div className="bk-field"><label>Business email <span className="req">*</span></label><input className="bk-input" type="email" value={company.companyEmail} onChange={e => setComp("companyEmail", e.target.value)}/></div>
                      <div className="bk-field"><label>Phone</label><input className="bk-input" type="tel" value={company.companyPhone} onChange={e => setComp("companyPhone", e.target.value)}/></div>
                      <div className="bk-field"><label>Website</label><input className="bk-input" type="url" value={company.website} onChange={e => setComp("website", e.target.value)} placeholder="https://"/></div>
                    </div>
                  </div>

                  <div className="card settings-card">
                    <h4 className="company-section-h">Social &amp; messaging</h4>
                    <div className="field-grid single">
                      <div className="bk-field">
                        <label><span className="company-social-icon" style={{background:"#25D366"}}>W</span> WhatsApp</label>
                        <input className="bk-input" type="tel" value={company.whatsapp} onChange={e => setComp("whatsapp", e.target.value)} placeholder="+44 7700 000000"/>
                      </div>
                      <div className="bk-field">
                        <label><span className="company-social-icon" style={{background:"#1877F2"}}>f</span> Facebook</label>
                        <input className="bk-input" value={company.facebook} onChange={e => setComp("facebook", e.target.value)} placeholder="https://facebook.com/yourpage"/>
                      </div>
                      <div className="bk-field">
                        <label><span className="company-social-icon" style={{background:"linear-gradient(135deg,#f09433,#dc2743,#bc1888)"}}>Ig</span> Instagram</label>
                        <input className="bk-input" value={company.instagram} onChange={e => setComp("instagram", e.target.value)} placeholder="https://instagram.com/yourhandle"/>
                      </div>
                      <div className="bk-field">
                        <label><span className="company-social-icon" style={{background:"#000"}}>X</span> X (Twitter)</label>
                        <input className="bk-input" value={company.twitter} onChange={e => setComp("twitter", e.target.value)} placeholder="https://x.com/yourhandle"/>
                      </div>
                      <div className="bk-field">
                        <label><span className="company-social-icon" style={{background:"#0A66C2"}}>in</span> LinkedIn</label>
                        <input className="bk-input" value={company.linkedin} onChange={e => setComp("linkedin", e.target.value)} placeholder="https://linkedin.com/company/..."/>
                      </div>
                    </div>
                  </div>
                </div>

                {/* ── Right column ── */}
                <div style={{display:"flex", flexDirection:"column", gap:20}}>
                  <div className="card settings-card">
                    <h4 className="company-section-h">Address visibility</h4>
                    <div style={{display:"flex", flexDirection:"column", gap:12}}>
                      <label className="mini-check">
                        <input type="checkbox" checked={!!company.hideEmail} onChange={() => setComp("hideEmail", !company.hideEmail)}/>
                        Don't show email on booking page
                      </label>
                      <label className="mini-check">
                        <input type="checkbox" checked={!!company.hideAddress} onChange={() => setComp("hideAddress", !company.hideAddress)}/>
                        Don't show address on booking page or in emails
                      </label>
                    </div>
                  </div>

                  <div className="card settings-card">
                    <h4 className="company-section-h">Location on map</h4>
                    <p className="section-sub" style={{marginTop:0, marginBottom:12}}>Search your address to pin your location for guests.</p>
                    <div className="map-search-row">
                      <input className="bk-input" placeholder="Search address…" value={mapQuery}
                        onChange={e => setMapQuery(e.target.value)}
                        onKeyDown={e => e.key === "Enter" && searchMap()}/>
                      <button className="btn primary" onClick={searchMap} disabled={mapBusy}>
                        {mapBusy ? "…" : <><I.location size={13}/> Search</>}
                      </button>
                    </div>
                    {mapErr && <div className="login-msg is-error" style={{marginTop:8, marginBottom:0}}>{mapErr}</div>}
                    <div className="map-frame-wrap">
                      <iframe className="map-frame" title="Location map" src={mapSrc} frameBorder="0" scrolling="no"/>
                    </div>
                    {company.companyLat && (
                      <div style={{fontSize:11, color:"var(--text-muted)", marginTop:8}}>
                        <I.check size={11}/> Location pinned · {Number(company.companyLat).toFixed(5)}, {Number(company.companyLon).toFixed(5)}
                      </div>
                    )}
                  </div>

                  <div style={{display:"flex", justifyContent:"flex-end"}}>
                    <button className="btn primary" onClick={saveCompany}>Save company information</button>
                  </div>
                </div>

              </div>
            </div>
          )}

          {tab === "notifications" && (
            <div className="settings-section">
              <h3 className="section-h">Notifications</h3>
              <p className="section-sub">Decide what reaches you and your guests.</p>
              <div className="card settings-card">
                {[
                  ["bookEmail",   "Email me on new bookings",      "Get an email the moment a guest books."],
                  ["bookSms",     "SMS me on new bookings",        "Quick alerts to your phone for each booking."],
                  ["cancelEmail", "Email me on cancellations",     "Know when a guest cancels or reschedules."],
                  ["reminders",   "Send reminder to guests",       "Auto-send 24h and 1h before each appointment."],
                  ["reviews",     "Ask guests for a review",       "Send a follow-up email after the appointment."],
                  ["marketing",   "Marketing tips & product news", "Occasional updates from Nexus Booking."],
                ].map(([k, t, d]) => (
                  <div key={k} className="notif-row">
                    <div>
                      <div className="title">{t}</div>
                      <div className="desc">{d}</div>
                    </div>
                    <label className="switch">
                      <input type="checkbox" checked={notifs[k]}
                        onChange={() => {
                          const next = {...notifs, [k]: !notifs[k]};
                          setNotifs(next);
                          actions.updateNotifications(next);
                        }}/>
                      <span className="track"><span className="knob"/></span>
                    </label>
                  </div>
                ))}
              </div>
            </div>
          )}

          {tab === "security" && (
            <div className="settings-section">
              <h3 className="section-h">Security</h3>
              <p className="section-sub">Password, sessions, and two-factor authentication.</p>
              <div className="card settings-card">
                <div className="field-grid single">
                  <div className="bk-field"><label>Current password</label><input className="bk-input" type="password" defaultValue="••••••••••"/></div>
                  <div className="bk-field"><label>New password</label><input className="bk-input" type="password" placeholder="At least 12 characters"/></div>
                </div>
                <div className="notif-row" style={{marginTop:8}}>
                  <div>
                    <div className="title">Two-factor authentication</div>
                    <div className="desc">Add a second step when signing in from a new device.</div>
                  </div>
                  <button className="btn primary">Enable</button>
                </div>
                <div className="notif-row">
                  <div>
                    <div className="title">Active sessions</div>
                    <div className="desc">2 devices currently signed in.</div>
                  </div>
                  <button className="btn danger" onClick={actions.resetDemoData}>Reset demo data</button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Calendar
// ──────────────────────────────────────────────────────────────────────────
function ViewCalendar({ data }) {
  const today = todayIso();
  const [current, setCurrent] = React.useState(() => {
    const d = new Date();
    return { year: d.getFullYear(), month: d.getMonth() };
  });
  const [selected, setSelected] = React.useState(today);

  const firstDay   = new Date(current.year, current.month, 1);
  const daysInMonth = new Date(current.year, current.month + 1, 0).getDate();
  const startDow   = (firstDay.getDay() + 6) % 7; // 0 = Monday

  const bookingsByDate = React.useMemo(() => {
    const map = {};
    data.bookings.forEach(b => {
      if (!b.date) return;
      if (!map[b.date]) map[b.date] = [];
      map[b.date].push(b);
    });
    return map;
  }, [data.bookings]);

  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) {
    cells.push(`${current.year}-${String(current.month + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`);
  }

  const monthLabel = new Date(current.year, current.month).toLocaleDateString("en-GB", { month: "long", year: "numeric" });
  const prev = () => setCurrent(c => c.month === 0  ? { year: c.year - 1, month: 11 } : { ...c, month: c.month - 1 });
  const next = () => setCurrent(c => c.month === 11 ? { year: c.year + 1, month: 0  } : { ...c, month: c.month + 1 });
  const goToday = () => { const d = new Date(); setCurrent({ year: d.getFullYear(), month: d.getMonth() }); setSelected(today); };

  const selectedBookings = (bookingsByDate[selected] || [])
    .filter(b => b.status !== "Cancelled")
    .sort((a, b) => a.time.localeCompare(b.time));

  const getEventColor = (bk) => {
    const ev = data.events.find(e => e.id === bk.eventId || e.name === bk.eventName);
    return ev?.color || "var(--accent)";
  };

  return (
    <>
      <div className="view-h">
        <div>
          <h1>Calendar</h1>
          <div className="sub">All classes and bookings by day.</div>
        </div>
        <div className="view-actions">
          <button className="btn ghost" onClick={goToday}>Today</button>
        </div>
      </div>

      <div className="cal-layout">
        {/* ── Month grid ── */}
        <div className="card cal-card">
          <div className="cal-nav">
            <button className="icon-btn" onClick={prev}><I.chevL size={14}/></button>
            <h3 className="cal-month-label">{monthLabel}</h3>
            <button className="icon-btn" onClick={next}><I.chev size={14}/></button>
          </div>
          <div className="cal-dow">
            {["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map(d => <div key={d}>{d}</div>)}
          </div>
          <div className="cal-grid">
            {cells.map((iso, i) => {
              if (!iso) return <div key={i} className="cal-cell is-empty"/>;
              const bks = (bookingsByDate[iso] || []).filter(b => b.status !== "Cancelled");
              // Collect unique event colors (up to 3 dots)
              const seen = {};
              const dots = [];
              bks.forEach(b => {
                const ev = data.events.find(e => e.id === b.eventId || e.name === b.eventName);
                const key = ev?.id || b.eventName;
                if (!seen[key]) { seen[key] = true; dots.push(ev?.color || "var(--accent)"); }
              });
              return (
                <button
                  key={iso}
                  className={["cal-cell", iso === today ? "is-today" : "", iso === selected ? "is-selected" : "", bks.length ? "has-bookings" : ""].filter(Boolean).join(" ")}
                  onClick={() => setSelected(iso)}>
                  <span className="cal-day-num">{Number(iso.slice(8))}</span>
                  {dots.length > 0 && (
                    <div className="cal-dots">
                      {dots.slice(0, 3).map((color, ci) => (
                        <span key={ci} className="cal-dot" style={{background: color}}/>
                      ))}
                      {dots.length > 3 && <span className="cal-dot-extra">+{dots.length - 3}</span>}
                    </div>
                  )}
                </button>
              );
            })}
          </div>
        </div>

        {/* ── Day detail ── */}
        <div className="card cal-detail">
          <div className="cal-detail-h">
            <div>
              <div className="cal-detail-date">{selected ? formatIsoDate(selected, { weekday: "long", year: true }) : "Select a day"}</div>
              <div className="sub">{selectedBookings.length === 0 ? "No bookings" : `${selectedBookings.length} booking${selectedBookings.length !== 1 ? "s" : ""}`}</div>
            </div>
          </div>
          {selectedBookings.length === 0 ? (
            <div className="cal-empty">
              <I.cal size={28}/>
              <p>No bookings on this day</p>
            </div>
          ) : (
            <div className="cal-booking-list">
              {selectedBookings.map(bk => (
                <div key={bk.id} className="cal-booking-row">
                  <div className="cal-booking-bar" style={{background: getEventColor(bk)}}/>
                  <div className="cal-booking-body">
                    <div className="cal-booking-time">{bk.time}</div>
                    <div className="cal-booking-name">{bk.guestName}</div>
                    <div className="cal-booking-event">{bk.eventName}</div>
                  </div>
                  <span className={"pill " + bk.status.toLowerCase()}>{bk.status}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Router
// ──────────────────────────────────────────────────────────────────────────
// ──────────────────────────────────────────────────────────────────────────
// Platform (super admin) — tabbed: Accounts / Coupons / Announcements / Activity
// ──────────────────────────────────────────────────────────────────────────

const PLAN_OPTIONS = ["free","starter","pro","business"];
const PLAN_COLORS  = { free:"var(--text-muted)", starter:"#7aa7ff", pro:"var(--accent)", business:"#6ee7a3" };

function PlanBadge({ plan }) {
  const p = plan || "free";
  return (
    <span className="plan-badge" style={{color: PLAN_COLORS[p] || "var(--text-muted)", borderColor: PLAN_COLORS[p] || "var(--border)"}}>
      {p.charAt(0).toUpperCase() + p.slice(1)}
    </span>
  );
}

// ── Notes modal ───────────────────────────────────────────────
function NotesModal({ accountId, accountName, onClose }) {
  const [notes, setNotes]   = React.useState(null);
  const [draft, setDraft]   = React.useState("");
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    fetchPlatformNotes(accountId).then(setNotes);
  }, [accountId]);

  const handleAdd = async () => {
    if (!draft.trim()) return;
    setSaving(true);
    const row = await addPlatformNote(accountId, draft.trim());
    setNotes(n => [{ id: row.id, note: row.note, createdAt: row.created_at || new Date().toISOString() }, ...(n || [])]);
    setDraft("");
    setSaving(false);
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-card" style={{maxWidth:520}} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h3 style={{margin:0}}>Internal notes</h3>
            <span className="sub" style={{fontSize:12}}>{accountName}</span>
          </div>
          <button className="modal-close" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body">
          <div style={{display:"flex", gap:8, marginBottom:16}}>
            <textarea className="bk-textarea" rows={2} style={{flex:1, marginTop:0}}
              value={draft} onChange={e => setDraft(e.target.value)}
              placeholder="Add an internal note about this account…"/>
            <button className="btn primary" style={{alignSelf:"flex-end"}} onClick={handleAdd} disabled={saving || !draft.trim()}>
              {saving ? "…" : "Add"}
            </button>
          </div>
          <div className="platform-notes-list">
            {notes === null && <div style={{color:"var(--text-muted)",fontSize:13}}>Loading…</div>}
            {notes && notes.length === 0 && <div style={{color:"var(--text-muted)",fontSize:13}}>No notes yet.</div>}
            {(notes || []).map(n => (
              <div key={n.id} className="platform-note-row">
                <div className="platform-note-text">{n.note}</div>
                <div className="platform-note-date">{n.createdAt ? new Date(n.createdAt).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}) : ""}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Accounts tab ──────────────────────────────────────────────
function PlatformAccounts({ onViewAccount }) {
  const [accounts, setAccounts] = React.useState(null);
  const [notesFor, setNotesFor] = React.useState(null); // { id, name }

  React.useEffect(() => { fetchAllProfiles().then(setAccounts); }, []);

  const handlePlan = async (id, plan) => {
    setAccounts(a => a.map(x => x.id === id ? { ...x, plan } : x));
    await updateAccountPlan(id, plan);
  };

  const handleSuspend = async (id, suspended) => {
    setAccounts(a => a.map(x => x.id === id ? { ...x, suspended } : x));
    await updateAccountSuspended(id, suspended);
  };

  if (!accounts) return <div style={{display:"flex",alignItems:"center",justifyContent:"center",height:300}}><div className="loading-dots"><span/><span/><span/></div></div>;

  const totalBookings = accounts.reduce((s, a) => s + a.bookingCount, 0);
  const totalEvents   = accounts.reduce((s, a) => s + a.eventCount, 0);
  const active        = accounts.filter(a => a.setupComplete).length;
  const suspended     = accounts.filter(a => a.suspended).length;

  return (
    <>
      <div className="platform-stats">
        <div className="platform-stat"><div className="platform-stat-n">{accounts.length}</div><div className="platform-stat-l">Businesses</div></div>
        <div className="platform-stat"><div className="platform-stat-n">{active}</div><div className="platform-stat-l">Active setups</div></div>
        <div className="platform-stat"><div className="platform-stat-n">{totalEvents}</div><div className="platform-stat-l">Total services</div></div>
        <div className="platform-stat"><div className="platform-stat-n">{totalBookings}</div><div className="platform-stat-l">Total bookings</div></div>
        <div className="platform-stat"><div className="platform-stat-n" style={{color:suspended?"var(--danger)":"inherit"}}>{suspended}</div><div className="platform-stat-l">Suspended</div></div>
      </div>

      <div className="card">
        <table className="table">
          <thead>
            <tr>
              <th>Business</th>
              <th>Plan</th>
              <th>Booking URL</th>
              <th>Services</th>
              <th>Bookings</th>
              <th>Joined</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {accounts.length === 0 && (
              <tr><td colSpan="8" style={{padding:"40px 20px",textAlign:"center",color:"var(--text-muted)"}}>No accounts yet.</td></tr>
            )}
            {accounts.map(a => (
              <tr key={a.id} style={{opacity: a.suspended ? 0.6 : 1}}>
                <td>
                  <div style={{fontWeight:600}}>{a.brandName || "—"}</div>
                  <div style={{fontSize:12,color:"var(--text-muted)"}}>{a.email}</div>
                </td>
                <td>
                  <select className="status-select"
                    value={a.plan || "free"}
                    onChange={e => handlePlan(a.id, e.target.value)}
                    style={{color: PLAN_COLORS[a.plan || "free"]}}>
                    {PLAN_OPTIONS.map(p => <option key={p} value={p}>{p.charAt(0).toUpperCase()+p.slice(1)}</option>)}
                  </select>
                </td>
                <td><span style={{fontSize:12,color:"var(--text-muted)"}}>{a.bookingUrl || "—"}</span></td>
                <td>{a.eventCount}</td>
                <td>{a.bookingCount}</td>
                <td style={{fontSize:12,color:"var(--text-muted)"}}>{a.createdAt ? new Date(a.createdAt).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}) : "—"}</td>
                <td>
                  <label className="switch" title={a.suspended ? "Suspended — click to restore" : "Active — click to suspend"}>
                    <input type="checkbox" checked={!a.suspended} onChange={e => handleSuspend(a.id, !e.target.checked)}/>
                    <span className="track"><span className="knob"/></span>
                  </label>
                </td>
                <td style={{textAlign:"right"}}>
                  <div style={{display:"flex",gap:4,justifyContent:"flex-end"}}>
                    <button className="btn ghost" style={{fontSize:11,padding:"3px 8px"}}
                      onClick={() => setNotesFor({ id: a.id, name: a.brandName || a.email || "Account" })}>
                      Notes
                    </button>
                    {a.bookingUrl && (
                      <button className="btn ghost" style={{fontSize:11,padding:"3px 8px"}}
                        onClick={() => window.open(`${window.location.origin}/?book=${a.bookingUrl}`, "_blank")}>
                        Page
                      </button>
                    )}
                    <button className="btn primary" style={{fontSize:11,padding:"3px 8px"}}
                      onClick={() => onViewAccount(a.id)}>
                      View
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {notesFor && (
        <NotesModal accountId={notesFor.id} accountName={notesFor.name} onClose={() => setNotesFor(null)}/>
      )}
    </>
  );
}

// ── Coupon modal ──────────────────────────────────────────────
function CouponModal({ coupon, onClose, onSave }) {
  const blank = { code:"", description:"", discountType:"percent", discountValue:"", trialDays:"", maxUses:"", timesUsed:0, active:true, expiresAt:"" };
  const [draft, setDraft] = React.useState(coupon || blank);
  const [saving, setSaving] = React.useState(false);
  const set = (k, v) => setDraft(d => ({ ...d, [k]: v }));

  const genCode = () => {
    const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    let code = "";
    for (let i = 0; i < 8; i++) code += chars[Math.floor(Math.random() * chars.length)];
    set("code", code);
  };

  const handleSave = async () => {
    setSaving(true);
    await onSave(draft);
    setSaving(false);
    onClose();
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-card" style={{maxWidth:500}} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <h3 style={{margin:0}}>{coupon?.id ? "Edit coupon" : "New coupon"}</h3>
          <button className="modal-close" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body">
          <div className="field-grid">
            <div className="bk-field" style={{gridColumn:"1 / -1"}}>
              <label>Coupon code</label>
              <div style={{display:"flex",gap:8}}>
                <input className="bk-input" style={{flex:1,textTransform:"uppercase",letterSpacing:"0.1em",fontWeight:600}}
                  value={draft.code} onChange={e => set("code", e.target.value.toUpperCase())}
                  placeholder="e.g. SUMMER25"/>
                <button className="btn ghost" onClick={genCode} title="Generate random code">Generate</button>
              </div>
            </div>
            <div className="bk-field" style={{gridColumn:"1 / -1"}}>
              <label>Description <span className="opt">(internal)</span></label>
              <input className="bk-input" value={draft.description} onChange={e => set("description", e.target.value)} placeholder="e.g. Summer campaign 2026"/>
            </div>
            <div className="bk-field">
              <label>Discount type</label>
              <select className="bk-input" value={draft.discountType} onChange={e => set("discountType", e.target.value)}>
                <option value="percent">% off</option>
                <option value="fixed">Fixed amount off</option>
                <option value="trial">Free trial (days)</option>
                <option value="free">Free plan access</option>
              </select>
            </div>
            {(draft.discountType === "percent" || draft.discountType === "fixed") && (
              <div className="bk-field">
                <label>{draft.discountType === "percent" ? "Discount %" : "Amount off"}</label>
                <input className="bk-input" type="number" min="0" value={draft.discountValue}
                  onChange={e => set("discountValue", e.target.value)} placeholder={draft.discountType === "percent" ? "25" : "10.00"}/>
              </div>
            )}
            {draft.discountType === "trial" && (
              <div className="bk-field">
                <label>Trial days</label>
                <input className="bk-input" type="number" min="0" value={draft.trialDays}
                  onChange={e => set("trialDays", e.target.value)} placeholder="30"/>
              </div>
            )}
            <div className="bk-field">
              <label>Max uses <span className="opt">(0 = unlimited)</span></label>
              <input className="bk-input" type="number" min="0" value={draft.maxUses}
                onChange={e => set("maxUses", e.target.value)} placeholder="0"/>
            </div>
            <div className="bk-field">
              <label>Expires on <span className="opt">(optional)</span></label>
              <input className="bk-input" type="date" value={draft.expiresAt}
                onChange={e => set("expiresAt", e.target.value)}/>
            </div>
            <div className="bk-field" style={{gridColumn:"1 / -1", display:"flex", alignItems:"center", gap:10}}>
              <label className="switch">
                <input type="checkbox" checked={draft.active} onChange={e => set("active", e.target.checked)}/>
                <span className="track"><span className="knob"/></span>
              </label>
              <span style={{fontSize:13}}>Coupon is active</span>
            </div>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={handleSave} disabled={saving || !draft.code.trim()}>
            {saving ? "Saving…" : "Save coupon"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Coupons tab ───────────────────────────────────────────────
function PlatformCoupons() {
  const [coupons, setCoupons] = React.useState(null);
  const [editing, setEditing] = React.useState(null); // null | {} (new) | coupon obj

  React.useEffect(() => { fetchCoupons().then(setCoupons); }, []);

  const handleSave = async (draft) => {
    const id = await saveCoupon(draft);
    fetchCoupons().then(setCoupons);
  };

  const handleDelete = async (id) => {
    if (!confirm("Delete this coupon?")) return;
    await deleteCoupon(id);
    setCoupons(c => c.filter(x => x.id !== id));
  };

  const discountLabel = (c) => {
    if (c.discountType === "percent") return `${c.discountValue}% off`;
    if (c.discountType === "fixed")   return `£${c.discountValue} off`;
    if (c.discountType === "trial")   return `${c.trialDays}-day trial`;
    if (c.discountType === "free")    return "Free plan";
    return "—";
  };

  if (!coupons) return <div style={{display:"flex",alignItems:"center",justifyContent:"center",height:300}}><div className="loading-dots"><span/><span/><span/></div></div>;

  return (
    <>
      <div style={{display:"flex", justifyContent:"flex-end", marginBottom:16}}>
        <button className="btn primary" onClick={() => setEditing({})}>+ New coupon</button>
      </div>
      <div className="card">
        <table className="table">
          <thead>
            <tr>
              <th>Code</th>
              <th>Description</th>
              <th>Discount</th>
              <th>Uses</th>
              <th>Expires</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {coupons.length === 0 && (
              <tr><td colSpan="7" style={{padding:"40px 20px",textAlign:"center",color:"var(--text-muted)"}}>No coupons yet. Create one above.</td></tr>
            )}
            {coupons.map(c => (
              <tr key={c.id}>
                <td>
                  <code className="coupon-code">{c.code}</code>
                </td>
                <td style={{color:"var(--text-muted)",fontSize:13}}>{c.description || "—"}</td>
                <td><span className="coupon-discount">{discountLabel(c)}</span></td>
                <td>
                  <span style={{fontSize:13}}>
                    {c.timesUsed}
                    {c.maxUses > 0 ? ` / ${c.maxUses}` : " / ∞"}
                  </span>
                </td>
                <td style={{fontSize:12,color:"var(--text-muted)"}}>
                  {c.expiresAt ? new Date(c.expiresAt).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}) : "Never"}
                </td>
                <td>
                  <span className={"pill " + (c.active ? "confirmed" : "cancelled")}>{c.active ? "Active" : "Inactive"}</span>
                </td>
                <td style={{textAlign:"right"}}>
                  <div style={{display:"flex",gap:4,justifyContent:"flex-end"}}>
                    <button className="btn ghost" style={{fontSize:11,padding:"3px 8px"}} onClick={() => setEditing(c)}>Edit</button>
                    <button className="btn ghost" style={{fontSize:11,padding:"3px 8px",color:"var(--danger)"}} onClick={() => handleDelete(c.id)}>Delete</button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {editing !== null && (
        <CouponModal
          coupon={Object.keys(editing).length === 0 ? null : editing}
          onClose={() => setEditing(null)}
          onSave={handleSave}
        />
      )}
    </>
  );
}

// ── Announcement modal ────────────────────────────────────────
function AnnouncementModal({ ann, onClose, onSave }) {
  const blank = { title:"", message:"", type:"info", active:true, expiresAt:"" };
  const [draft, setDraft] = React.useState(ann || blank);
  const [saving, setSaving] = React.useState(false);
  const set = (k, v) => setDraft(d => ({ ...d, [k]: v }));

  const handleSave = async () => {
    setSaving(true);
    await onSave(draft);
    setSaving(false);
    onClose();
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-card" style={{maxWidth:500}} onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <h3 style={{margin:0}}>{ann?.id ? "Edit announcement" : "New announcement"}</h3>
          <button className="modal-close" onClick={onClose}>✕</button>
        </div>
        <div className="modal-body">
          <div className="field-grid">
            <div className="bk-field" style={{gridColumn:"1 / -1"}}>
              <label>Title</label>
              <input className="bk-input" value={draft.title} onChange={e => set("title", e.target.value)} placeholder="e.g. Scheduled maintenance"/>
            </div>
            <div className="bk-field" style={{gridColumn:"1 / -1"}}>
              <label>Message</label>
              <textarea className="bk-textarea" rows={3} value={draft.message}
                onChange={e => set("message", e.target.value)} placeholder="Shown to all users in their dashboard…"/>
            </div>
            <div className="bk-field">
              <label>Type</label>
              <select className="bk-input" value={draft.type} onChange={e => set("type", e.target.value)}>
                <option value="info">ℹ Info</option>
                <option value="warning">⚠️ Warning</option>
                <option value="success">✅ Success</option>
              </select>
            </div>
            <div className="bk-field">
              <label>Expires on <span className="opt">(optional)</span></label>
              <input className="bk-input" type="date" value={draft.expiresAt}
                onChange={e => set("expiresAt", e.target.value)}/>
            </div>
            <div className="bk-field" style={{gridColumn:"1 / -1", display:"flex", alignItems:"center", gap:10}}>
              <label className="switch">
                <input type="checkbox" checked={draft.active} onChange={e => set("active", e.target.checked)}/>
                <span className="track"><span className="knob"/></span>
              </label>
              <span style={{fontSize:13}}>Announcement is live</span>
            </div>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={handleSave} disabled={saving || !draft.title.trim() || !draft.message.trim()}>
            {saving ? "Saving…" : "Save announcement"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Announcements tab ─────────────────────────────────────────
function PlatformAnnouncements() {
  const [anns, setAnns]     = React.useState(null);
  const [editing, setEditing] = React.useState(null);

  React.useEffect(() => { fetchAnnouncements().then(setAnns); }, []);

  const handleSave = async (draft) => {
    await saveAnnouncement(draft);
    fetchAnnouncements().then(setAnns);
  };

  const handleDelete = async (id) => {
    if (!confirm("Delete this announcement?")) return;
    await deleteAnnouncement(id);
    setAnns(a => a.filter(x => x.id !== id));
  };

  const TYPE_LABELS = { info:"ℹ Info", warning:"⚠️ Warning", success:"✅ Success" };
  const TYPE_COLORS = { info:"#7aa7ff", warning:"var(--accent)", success:"#6ee7a3" };

  if (!anns) return <div style={{display:"flex",alignItems:"center",justifyContent:"center",height:300}}><div className="loading-dots"><span/><span/><span/></div></div>;

  return (
    <>
      <div style={{display:"flex", justifyContent:"flex-end", marginBottom:16}}>
        <button className="btn primary" onClick={() => setEditing({})}>+ New announcement</button>
      </div>
      <div className="card">
        <table className="table">
          <thead>
            <tr>
              <th>Title</th>
              <th>Type</th>
              <th>Expires</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {anns.length === 0 && (
              <tr><td colSpan="5" style={{padding:"40px 20px",textAlign:"center",color:"var(--text-muted)"}}>No announcements. Create one above.</td></tr>
            )}
            {anns.map(a => (
              <tr key={a.id}>
                <td>
                  <div style={{fontWeight:600}}>{a.title}</div>
                  <div style={{fontSize:12,color:"var(--text-muted)",maxWidth:300,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{a.message}</div>
                </td>
                <td>
                  <span style={{fontSize:12,fontWeight:500,color:TYPE_COLORS[a.type]||"var(--text-muted)"}}>
                    {TYPE_LABELS[a.type]||a.type}
                  </span>
                </td>
                <td style={{fontSize:12,color:"var(--text-muted)"}}>
                  {a.expiresAt ? new Date(a.expiresAt).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}) : "Never"}
                </td>
                <td>
                  <span className={"pill " + (a.active ? "confirmed" : "cancelled")}>{a.active ? "Live" : "Inactive"}</span>
                </td>
                <td style={{textAlign:"right"}}>
                  <div style={{display:"flex",gap:4,justifyContent:"flex-end"}}>
                    <button className="btn ghost" style={{fontSize:11,padding:"3px 8px"}} onClick={() => setEditing(a)}>Edit</button>
                    <button className="btn ghost" style={{fontSize:11,padding:"3px 8px",color:"var(--danger)"}} onClick={() => handleDelete(a.id)}>Delete</button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {editing !== null && (
        <AnnouncementModal
          ann={Object.keys(editing).length === 0 ? null : editing}
          onClose={() => setEditing(null)}
          onSave={handleSave}
        />
      )}
    </>
  );
}

// ── Activity tab ──────────────────────────────────────────────
function PlatformActivity() {
  const [items, setItems] = React.useState(null);

  React.useEffect(() => { fetchPlatformActivity().then(setItems); }, []);

  if (!items) return <div style={{display:"flex",alignItems:"center",justifyContent:"center",height:300}}><div className="loading-dots"><span/><span/><span/></div></div>;

  return (
    <div className="card">
      <div className="card-h">
        <h3>Platform Activity Log</h3>
        <span className="sub">Last 100 events across all accounts</span>
      </div>
      <div className="platform-activity-list">
        {items.length === 0 && <div style={{padding:"40px 20px",textAlign:"center",color:"var(--text-muted)"}}>No activity recorded yet.</div>}
        {items.map(item => (
          <div key={item.id} className="platform-activity-row">
            <div className="platform-activity-dot"/>
            <div className="platform-activity-text">{item.text}</div>
            <div className="platform-activity-meta">
              <span className="platform-activity-id">{(item.userId || "").slice(0, 8)}</span>
              <span className="platform-activity-time">
                {item.createdAt ? new Date(item.createdAt).toLocaleDateString("en-GB",{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}) : ""}
              </span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── ViewPlatform (tabbed shell) ───────────────────────────────
function ViewPlatform({ onViewAccount }) {
  const [tab, setTab] = React.useState("accounts");

  const TABS = [
    { id: "accounts",      label: "Accounts" },
    { id: "coupons",       label: "Coupons" },
    { id: "announcements", label: "Announcements" },
    { id: "activity",      label: "Activity" },
  ];

  return (
    <>
      <div className="view-h">
        <div>
          <h1>Platform</h1>
          <div className="sub">Super admin — manage all accounts, coupons, and announcements.</div>
        </div>
      </div>

      <div className="platform-tabs">
        {TABS.map(t => (
          <button key={t.id}
            className={"platform-tab " + (tab === t.id ? "is-active" : "")}
            onClick={() => setTab(t.id)}>
            {t.label}
          </button>
        ))}
      </div>

      {tab === "accounts"      && <PlatformAccounts onViewAccount={onViewAccount}/>}
      {tab === "coupons"       && <PlatformCoupons/>}
      {tab === "announcements" && <PlatformAnnouncements/>}
      {tab === "activity"      && <PlatformActivity/>}
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Analytics
// ──────────────────────────────────────────────────────────────────────────
function MiniBarChart({ bars, color, showMoney, currency }) {
  const max = Math.max(...bars.map(b => b.value), 1);
  return (
    <div className="mini-bar-chart">
      {bars.map((b, i) => {
        const pct = Math.round((b.value / max) * 100);
        return (
          <div key={i} className="mini-bar-col">
            <div className="mini-bar-wrap">
              <div className="mini-bar" style={{ height: `${pct}%`, background: color }}/>
            </div>
            {b.value > 0 && (
              <div className="mini-bar-tip">
                {showMoney ? formatMoney(b.value, currency) : b.value}
              </div>
            )}
            <div className="mini-bar-label">{b.label}</div>
          </div>
        );
      })}
    </div>
  );
}

function ViewAnalytics({ data }) {
  const currency    = data.profile.currency;
  const allBk       = data.bookings;
  const confirmed   = allBk.filter(b => b.status !== "Cancelled");

  // ── Key metrics ──────────────────────────────────────────────
  const totalRevenue  = confirmed.reduce((s, b) => s + Number(b.paymentAmount || 0), 0);
  const totalBookings = confirmed.length;
  const avgValue      = totalBookings > 0 ? totalRevenue / totalBookings : 0;
  const showRate      = allBk.length > 0
    ? Math.round((confirmed.filter(b => b.status === "Confirmed").length / allBk.length) * 100)
    : 100;
  const totalDiscount = confirmed.reduce((s, b) => s + Number(b.discountApplied || 0), 0);

  // ── Revenue + booking count by month (last 6) ────────────────
  const now = new Date();
  const monthData = Array.from({ length: 6 }, (_, i) => {
    const d  = new Date(now.getFullYear(), now.getMonth() - (5 - i), 1);
    const yr = d.getFullYear(), mo = d.getMonth();
    const slice = confirmed.filter(b => {
      if (!b.date) return false;
      const [by, bm] = b.date.split("-").map(Number);
      return by === yr && bm - 1 === mo;
    });
    return {
      label:   d.toLocaleDateString("en-GB", { month: "short" }),
      revenue: slice.reduce((s, b) => s + Number(b.paymentAmount || 0), 0),
      count:   slice.length,
    };
  });

  // ── Bookings by service ───────────────────────────────────────
  const bySvc = {};
  confirmed.forEach(b => { bySvc[b.eventName] = (bySvc[b.eventName] || 0) + 1; });
  const svcData   = Object.entries(bySvc).sort((a, b) => b[1] - a[1]).slice(0, 7);
  const svcColors = ["var(--accent)", "#7aa7ff", "#a78bfa", "#6ee7a3", "#f59e9e", "#94a3b8", "#fbbf24"];
  const svcMax    = svcData[0]?.[1] || 1;

  // ── By day of week ────────────────────────────────────────────
  const DOW_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const byDow = Array(7).fill(0);
  confirmed.forEach(b => {
    if (!b.date) return;
    byDow[new Date(b.date + "T12:00:00").getDay()]++;
  });

  // ── By hour ───────────────────────────────────────────────────
  const byHour = {};
  confirmed.forEach(b => {
    if (!b.time) return;
    const match = b.time.match(/(\d+):\d+\s*(AM|PM)/i);
    if (!match) return;
    let h = Number(match[1]);
    const ampm = match[2].toUpperCase();
    if (ampm === "PM" && h !== 12) h += 12;
    if (ampm === "AM" && h === 12) h = 0;
    byHour[h] = (byHour[h] || 0) + 1;
  });
  const hourEntries = Object.entries(byHour).sort((a, b) => Number(b[1]) - Number(a[1])).slice(0, 3);

  const KPI_DATA = [
    { label: "Total revenue",      value: formatMoney(totalRevenue,  currency),       sub: "from confirmed bookings" },
    { label: "Confirmed bookings",  value: String(totalBookings),                      sub: `${allBk.length} total incl. cancelled` },
    { label: "Avg booking value",   value: formatMoney(avgValue,      currency),       sub: "per confirmed booking" },
    { label: "Show rate",           value: `${showRate}%`,                             sub: "confirmed vs total" },
    { label: "Coupon savings given",value: formatMoney(totalDiscount, currency),       sub: "total discount applied" },
  ];

  return (
    <>
      <div className="view-h">
        <div>
          <h1>Analytics</h1>
          <div className="sub">Performance overview derived from your booking history.</div>
        </div>
        <div className="view-actions">
          <button className="btn ghost" onClick={() => downloadCsv("nexus-analytics.csv", [
            ["Month", "Revenue", "Bookings"],
            ...monthData.map(m => [m.label, m.revenue, m.count]),
          ])}><I.arrow size={13}/> Export</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="analytics-kpi-strip">
        {KPI_DATA.map(k => (
          <div key={k.label} className="analytics-kpi">
            <div className="analytics-kpi-v">{k.value}</div>
            <div className="analytics-kpi-l">{k.label}</div>
            <div className="analytics-kpi-sub">{k.sub}</div>
          </div>
        ))}
      </div>

      {/* Revenue + count charts */}
      <div className="analytics-row">
        <div className="card analytics-card-lg">
          <div className="card-h"><h3>Revenue by month</h3><span className="sub">last 6 months</span></div>
          {totalRevenue === 0
            ? <div className="analytics-empty">No revenue data yet.</div>
            : <MiniBarChart bars={monthData.map(m => ({ label: m.label, value: m.revenue }))} color="var(--accent)" showMoney currency={currency}/>
          }
        </div>
        <div className="card analytics-card-sm">
          <div className="card-h"><h3>Bookings by month</h3></div>
          {totalBookings === 0
            ? <div className="analytics-empty">No booking data yet.</div>
            : <MiniBarChart bars={monthData.map(m => ({ label: m.label, value: m.count }))} color="#7aa7ff"/>
          }
        </div>
      </div>

      {/* Service + day breakdown */}
      <div className="analytics-row">
        <div className="card analytics-card-lg">
          <div className="card-h"><h3>Bookings by service</h3></div>
          {svcData.length === 0
            ? <div className="analytics-empty">No booking data yet.</div>
            : (
              <div className="svc-breakdown">
                {svcData.map(([name, count], i) => (
                  <div key={name} className="svc-row">
                    <div className="svc-name">{name}</div>
                    <div className="svc-bar-wrap">
                      <div className="svc-bar" style={{ width: `${Math.round((count / svcMax) * 100)}%`, background: svcColors[i % svcColors.length] }}/>
                    </div>
                    <div className="svc-count">{count}</div>
                  </div>
                ))}
              </div>
            )
          }
        </div>
        <div className="card analytics-card-sm">
          <div className="card-h"><h3>Busiest days</h3></div>
          <MiniBarChart bars={byDow.map((v, i) => ({ label: DOW_LABELS[i], value: v }))} color="#a78bfa"/>
          {hourEntries.length > 0 && (
            <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--border)" }}>
              <div style={{ fontSize: 11, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--text-muted)", marginBottom: 8 }}>
                Peak hours
              </div>
              {hourEntries.map(([h, count]) => {
                const hr = Number(h);
                const label = hr === 0 ? "12:00 AM" : hr < 12 ? `${hr}:00 AM` : hr === 12 ? "12:00 PM" : `${hr - 12}:00 PM`;
                return (
                  <div key={h} className="peak-hour-row">
                    <span className="peak-hour-label">{label}</span>
                    <span className="peak-hour-count">{count} booking{count !== 1 ? "s" : ""}</span>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </>
  );
}

function InternalView({ active, industry, data, actions, onOpenBooking, onViewAccount }) {
  switch (active) {
    case "calendar":     return <ViewCalendar data={data}/>;
    case "bookings":     return <ViewBookings industry={industry} data={data} actions={actions} onOpenBooking={onOpenBooking}/>;
    case "events":       return <ViewEventTypes industry={industry} data={data} actions={actions}/>;
    case "availability": return <ViewAvailability data={data} actions={actions}/>;
    case "teams":        return <ViewTeams/>;
    case "integrations": return <ViewIntegrations data={data} actions={actions}/>;
    case "analytics":    return <ViewAnalytics data={data}/>;
    case "billing":      return <ViewBilling industry={industry} data={data}/>;
    case "settings":     return <ViewSettings data={data} actions={actions}/>;
    case "platform":     return <ViewPlatform onViewAccount={onViewAccount}/>;
    default:             return null;
  }
}

window.InternalView = InternalView;
