// Per-host profile: workshops, aggregated reviews, ownership/editing
const { useMemo, useState: useHostState, useEffect: useHostEffect } = React;

function hostSlug(name) {
  if (!name) return "";
  return name
    .normalize("NFD")
    .replace(/[̀-ͯ]/g, "")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "") || "izvajalec";
}

function readHostSlugFromHash() {
  const m = window.location.hash.match(/^#\/izvajalec\/([^/#?]+)\/?$/);
  return m ? m[1] : null;
}

function gatherHostReviews(hostWorkshops, userReviews) {
  const seed = window.WORKSHOP_SEED_REVIEWS || {};
  const items = [];
  for (const w of hostWorkshops) {
    const users = userReviews[w.id] || [];
    const seeds = seed[w.id] || [];
    for (const r of [...users, ...seeds]) {
      items.push({ ...r, workshopTitle: w.title, workshopId: w.id });
    }
  }
  return items;
}

function InfoBlock({ label, children }) {
  return (
    <div className="host-info-block">
      <div className="host-info-block-label mono tiny">{label}</div>
      <div className="host-info-block-body">{children}</div>
    </div>
  );
}

const HOST_SOCIAL_DEF = [
  { key: "website",   short: "www", label: { en: "Website",  sl: "Splet" } },
  { key: "instagram", short: "IG",  label: { en: "Instagram", sl: "Instagram" } },
  { key: "facebook",  short: "FB",  label: { en: "Facebook",  sl: "Facebook" } },
  { key: "youtube",   short: "YT",  label: { en: "YouTube",   sl: "YouTube" } },
  { key: "tiktok",    short: "TT",  label: { en: "TikTok",    sl: "TikTok" } },
  { key: "linkedin",  short: "in",  label: { en: "LinkedIn",  sl: "LinkedIn" } },
];

function hostSocialHref(raw) {
  if (raw == null || typeof raw !== "string") return null;
  const t = raw.trim();
  if (!t) return null;
  const withProto = /^https?:\/\//i.test(t) ? t : `https://${t.replace(/^\/+/, "")}`;
  try {
    const u = new URL(withProto);
    if (u.protocol === "http:" || u.protocol === "https:") return u.href;
  } catch (e) { /* ignore */ }
  return null;
}

function emptyHostSocials() {
  return { website: "", instagram: "", facebook: "", youtube: "", tiktok: "", linkedin: "" };
}

function mergeHostSocials(raw) {
  const b = emptyHostSocials();
  if (raw && typeof raw === "object")
    for (const k of Object.keys(b)) if (raw[k] != null) b[k] = String(raw[k]);
  return b;
}

function packHostSocialsForApi(obj) {
  const out = {};
  for (const k of Object.keys(emptyHostSocials())) {
    const v = (obj[k] || "").trim();
    if (v) out[k] = v;
  }
  return out;
}

function ownerActorPayload(user) {
  if (!user) return { user_name: "", user_email: "" };
  return {
    user_name: user.name || "",
    user_email: (user.email != null ? String(user.email) : "").trim(),
  };
}

const SCHEDULE_OPTIONS = ["recurring", "weekly", "monthly", "one-time"];
const LEVEL_OPTIONS    = ["Začetniki", "Srednji", "Napredno", "Vsi"];

function WorkshopEditPanel({ workshop, user, onSave, onCancel, onDeactivate }) {
  const t = useT();
  const [form, setForm] = useHostState(() => ({
    title:           workshop.title || "",
    subtitle:        workshop.subtitle || "",
    blurb:           workshop.blurb || "",
    price:           workshop.price ?? "",
    duration:        workshop.duration || "",
    capacity:        workshop.capacity > 0 ? String(workshop.capacity) : "",
    level:           workshop.level || "",
    schedule_type:   workshop.scheduleType || "recurring",
    next_date:       workshop.nextDate || "",
    image_url:       workshop.imageUrl || "",
    booking_enabled: workshop.bookingEnabled ? 1 : 0,
    team_building:   workshop.teamBuilding ? 1 : 0,
    for_kids:        workshop.forKids ? 1 : 0,
    tags:            Array.isArray(workshop.tags) ? workshop.tags.join(", ") : "",
    source_url:      workshop.sourceUrl || "",
  }));
  const [saving, setSaving] = useHostState(false);

  const field = (key, val) => setForm(f => ({ ...f, [key]: val }));

  const handleSave = () => {
    setSaving(true);
    const capStr = String(form.capacity || "").trim();
    const capacity = !capStr ? null : (() => {
      const n = parseInt(capStr, 10);
      return Number.isFinite(n) && n > 0 ? n : null;
    })();
    const payload = {
      ...form,
      price: parseFloat(form.price) || 0,
      capacity,
      booking_enabled: form.booking_enabled ? 1 : 0,
      team_building:   form.team_building   ? 1 : 0,
      for_kids:        form.for_kids        ? 1 : 0,
      tags: form.tags.split(",").map(t => t.trim()).filter(Boolean),
      ...ownerActorPayload(user),
    };
    fetch(`${window.getApiBase()}/workshops/${workshop.id}/owner`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    })
      .then(() => onSave())
      .catch(() => setSaving(false))
      .finally(() => setSaving(false));
  };

  const handleDeactivate = () => {
    if (!confirm("Skrij to delavnico s strani?")) return;
    fetch(`${window.getApiBase()}/workshops/${workshop.id}/owner`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ active: 0, ...ownerActorPayload(user) }),
    }).then(() => onDeactivate());
  };

  return (
    <div className="workshop-edit-panel">
      <div className="workshop-edit-panel-header">
        <span className="mono tiny">UREDI: {workshop.title}</span>
        <button type="button" className="workshop-edit-close" onClick={onCancel}>✕</button>
      </div>
      <div className="workshop-edit-grid">
        <label className="edit-field">
          <span className="mono tiny">Naslov</span>
          <input value={form.title} onChange={e => field("title", e.target.value)} />
        </label>
        <label className="edit-field">
          <span className="mono tiny">Podnaslov</span>
          <input value={form.subtitle} onChange={e => field("subtitle", e.target.value)} />
        </label>
        <label className="edit-field edit-field-wide">
          <span className="mono tiny">Opis</span>
          <textarea rows={3} value={form.blurb} onChange={e => field("blurb", e.target.value)} />
        </label>
        <label className="edit-field">
          <span className="mono tiny">Cena (€)</span>
          <input type="number" min="0" value={form.price} onChange={e => field("price", e.target.value)} />
        </label>
        <label className="edit-field">
          <span className="mono tiny">Trajanje</span>
          <input value={form.duration} onChange={e => field("duration", e.target.value)} placeholder="npr. 3h" />
        </label>
        <label className="edit-field">
          <span className="mono tiny">{t.fieldCapacity}</span>
          <input
            type="number"
            min="1"
            value={form.capacity}
            onChange={e => field("capacity", e.target.value)}
            placeholder="—"
          />
        </label>
        <label className="edit-field">
          <span className="mono tiny">Nivo</span>
          <select value={form.level} onChange={e => field("level", e.target.value)}>
            <option value="">—</option>
            {LEVEL_OPTIONS.map(l => <option key={l} value={l}>{l}</option>)}
          </select>
        </label>
        <label className="edit-field">
          <span className="mono tiny">Vrsta delavnice</span>
          <select value={form.schedule_type} onChange={e => field("schedule_type", e.target.value)}>
            {SCHEDULE_OPTIONS.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </label>
        <label className="edit-field">
          <span className="mono tiny">Naslednji termin</span>
          <input type="date" value={form.next_date} onChange={e => field("next_date", e.target.value)} />
        </label>
        <label className="edit-field edit-field-wide">
          <span className="mono tiny">URL fotografije</span>
          <input value={form.image_url} onChange={e => field("image_url", e.target.value)} placeholder="https://…" />
        </label>
        <label className="edit-field edit-field-wide">
          <span className="mono tiny">Spletna stran</span>
          <input value={form.source_url} onChange={e => field("source_url", e.target.value)} placeholder="https://…" />
        </label>
        <label className="edit-field edit-field-wide">
          <span className="mono tiny">Oznake (ločene z vejico)</span>
          <input value={form.tags} onChange={e => field("tags", e.target.value)} placeholder="keramika, vikend, glina" />
        </label>
        <div className="edit-checkboxes">
          <label className="edit-check">
            <input type="checkbox" checked={!!form.booking_enabled} onChange={e => field("booking_enabled", e.target.checked ? 1 : 0)} />
            <span>Omogoči rezervacije</span>
          </label>
          <label className="edit-check">
            <input type="checkbox" checked={!!form.team_building} onChange={e => field("team_building", e.target.checked ? 1 : 0)} />
            <span>Team building</span>
          </label>
          <label className="edit-check">
            <input type="checkbox" checked={!!form.for_kids} onChange={e => field("for_kids", e.target.checked ? 1 : 0)} />
            <span>Za otroke</span>
          </label>
        </div>
      </div>
      <div className="workshop-edit-footer">
        <button type="button" className="btn-danger-sm" onClick={handleDeactivate}>Skrij delavnico</button>
        <div style={{ display: "flex", gap: "8px" }}>
          <button type="button" className="btn-secondary-sm" onClick={onCancel}>Prekliči</button>
          <button type="button" className="btn-primary-sm" onClick={handleSave} disabled={saving}>
            {saving ? "Shranjujem…" : "Shrani →"}
          </button>
        </div>
      </div>
    </div>
  );
}

function AddWorkshopForm({ hostName, user, onSuccess, lang }) {
  const t = useT();
  const CATEGORIES = window.CATEGORIES || [];
  const cities     = window.SLOVENIAN_CITIES || [];
  const [form, setForm] = useHostState({
    title: "", subtitle: "", city: "Ljubljana", category: "pottery",
    price: "", blurb: "", duration: "2h", capacity: "", level: "Vsi", image_url: "", schedule_type: "recurring", for_kids: 0,
  });
  const [submitting, setSubmitting] = useHostState(false);
  const field = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = e => {
    e.preventDefault();
    const title = form.title.trim();
    if (!title || !form.city || !form.category || form.price === "") return;
    setSubmitting(true);
    const capStr = String(form.capacity || "").trim();
    const capacity = !capStr ? null : (() => {
      const n = parseInt(capStr, 10);
      return Number.isFinite(n) && n > 0 ? n : null;
    })();
    fetch(`${window.getApiBase()}/host/add-workshop`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ...ownerActorPayload(user),
        host_name: hostName,
        title,
        subtitle: form.subtitle,
        city: form.city,
        category: form.category,
        price: parseFloat(form.price) || 0,
        blurb: form.blurb,
        duration: form.duration,
        capacity,
        level: form.level,
        image_url: form.image_url,
        schedule_type: form.schedule_type,
        for_kids: form.for_kids ? 1 : 0,
        tags: [],
      }),
    })
      .then(r => { if (r.ok) { setForm({ title: "", subtitle: "", city: "Ljubljana", category: "pottery", price: "", blurb: "", duration: "2h", capacity: "", level: "Vsi", image_url: "", schedule_type: "recurring", for_kids: 0 }); onSuccess && onSuccess(); } })
      .finally(() => setSubmitting(false));
  };

  return (
    <form className="host-add-workshop" onSubmit={submit}>
      <div className="host-add-workshop-title mono tiny">{lang === "en" ? "ADD NEW WORKSHOP" : "NOVA DELAVNICA"}</div>
      <div className="workshop-edit-grid">
        <label className="edit-field">
          <span className="mono tiny">{lang === "en" ? "Title" : "Naslov"} *</span>
          <input value={form.title} onChange={e => field("title", e.target.value)} required />
        </label>
        <label className="edit-field">
          <span className="mono tiny">{lang === "en" ? "Subtitle" : "Podnaslov"}</span>
          <input value={form.subtitle} onChange={e => field("subtitle", e.target.value)} />
        </label>
        <label className="edit-field">
          <span className="mono tiny">{lang === "en" ? "City" : "Mesto"} *</span>
          <select value={form.city} onChange={e => field("city", e.target.value)}>
            {cities.map(c => <option key={c.name} value={c.name}>{c.name}</option>)}
          </select>
        </label>
        <label className="edit-field">
          <span className="mono tiny">{lang === "en" ? "Category" : "Kategorija"} *</span>
          <select value={form.category} onChange={e => field("category", e.target.value)}>
            {CATEGORIES.map(c => <option key={c.id} value={c.id}>{lang === "en" ? c.en : c.label}</option>)}
          </select>
        </label>
        <label className="edit-field">
          <span className="mono tiny">{lang === "en" ? "Price (€)" : "Cena (€)"} *</span>
          <input type="number" min="0" step="0.5" value={form.price} onChange={e => field("price", e.target.value)} required />
        </label>
        <label className="edit-field">
          <span className="mono tiny">{lang === "en" ? "Duration" : "Trajanje"}</span>
          <input value={form.duration} onChange={e => field("duration", e.target.value)} placeholder="2h" />
        </label>
        <label className="edit-field">
          <span className="mono tiny">{t.fieldCapacity}</span>
          <input
            type="number"
            min="1"
            value={form.capacity}
            onChange={e => field("capacity", e.target.value)}
            placeholder="—"
          />
        </label>
        <label className="edit-field">
          <span className="mono tiny">{lang === "en" ? "Level" : "Nivo"}</span>
          <select value={form.level} onChange={e => field("level", e.target.value)}>
            {LEVEL_OPTIONS.map(l => <option key={l} value={l}>{l}</option>)}
          </select>
        </label>
        <label className="edit-field">
          <span className="mono tiny">{lang === "en" ? "Workshop type" : "Vrsta delavnice"}</span>
          <select value={form.schedule_type} onChange={e => field("schedule_type", e.target.value)}>
            {SCHEDULE_OPTIONS.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </label>
        <label className="edit-field edit-field-wide">
          <span className="mono tiny">{lang === "en" ? "Description" : "Opis"}</span>
          <textarea rows={2} value={form.blurb} onChange={e => field("blurb", e.target.value)} />
        </label>
        <label className="edit-field edit-field-wide">
          <span className="mono tiny">URL {lang === "en" ? "of image" : "fotografije"}</span>
          <input value={form.image_url} onChange={e => field("image_url", e.target.value)} placeholder="https://…" />
        </label>
        <div className="edit-checkboxes">
          <label className="edit-check">
            <input type="checkbox" checked={!!form.for_kids} onChange={e => field("for_kids", e.target.checked ? 1 : 0)} />
            <span>{lang === "en" ? "For children" : "Za otroke"}</span>
          </label>
        </div>
      </div>
      <button type="submit" className="btn-primary-sm" disabled={submitting}>
        {submitting ? "…" : (lang === "en" ? "Add workshop" : "Dodaj delavnico →")}
      </button>
    </form>
  );
}

function HostPage({ lang, hostWorkshops, allWorkshops, reviews, onOpenWorkshop, favs, toggleFav, density, user, onRequestLogin, refreshWorkshops }) {
  const t           = useT();
  const GridCardCmp = window.GridCard;
  const accentForFn = window.accentFor;
  const catLabelFn  = window.catLabel;

  // — all hooks before early return —
  const [lightbox,       setLightbox]       = useHostState(null);
  const [hostMeta,        setHostMeta]        = useHostState({
    loading: true, owner: null, ownerEmail: null, cover: null, socials: mergeHostSocials({}),
  });
  const [editMode,       setEditMode]       = useHostState(false);
  const [editBio,        setEditBio]        = useHostState("");
  const [editCover,      setEditCover]      = useHostState("");
  const [editSocials,     setEditSocials]     = useHostState(() => mergeHostSocials({}));
  const [workshopEditId, setWorkshopEditId] = useHostState(null);
  const [saving,         setSaving]         = useHostState(false);

  const sortedWorkshops = useMemo(
    () => [...hostWorkshops].sort(
      (a, b) => (b.featured ? 1 : 0) - (a.featured ? 1 : 0) || a.title.localeCompare(b.title, "sl")
    ),
    [hostWorkshops]
  );

  const fallbackCover = useMemo(
    () => (hostWorkshops.find(w => w.imageUrl) || {}).imageUrl || null,
    [hostWorkshops]
  );

  const displayCover = (hostMeta.cover && String(hostMeta.cover).trim()) || fallbackCover;

  const photos = useMemo(() => {
    const seen = new Set();
    return hostWorkshops
      .map(w => ({ id: w.id, url: w.imageUrl, title: w.title }))
      .filter(p => p.url && p.url !== displayCover && !seen.has(p.url) && seen.add(p.url));
  }, [hostWorkshops, displayCover]);

  // Similar hosts: same city or same category, different host, grouped by host name
  const similarHosts = useMemo(() => {
    if (!allWorkshops || !hostWorkshops.length) return [];
    const currentHost = hostWorkshops[0].host;
    const currentCities = new Set(hostWorkshops.map(w => w.city));
    const currentCats   = new Set(hostWorkshops.map(w => w.category));
    const scored = {};
    for (const w of allWorkshops) {
      if (w.host === currentHost) continue;
      if (!w.imageUrl) continue;
      const cityMatch = currentCities.has(w.city);
      const catMatch  = currentCats.has(w.category);
      if (!cityMatch && !catMatch) continue;
      if (!scored[w.host]) scored[w.host] = { score: 0, workshop: w };
      scored[w.host].score += (cityMatch ? 2 : 0) + (catMatch ? 1 : 0);
    }
    return Object.values(scored)
      .sort((a, b) => b.score - a.score)
      .slice(0, 4)
      .map(s => s.workshop);
  }, [allWorkshops, hostWorkshops]);

  // keyboard nav for lightbox
  useHostEffect(() => {
    if (lightbox === null) return;
    const onKey = e => {
      if (e.key === "Escape")      setLightbox(null);
      if (e.key === "ArrowRight")  setLightbox(i => (i + 1) % photos.length);
      if (e.key === "ArrowLeft")   setLightbox(i => (i - 1 + photos.length) % photos.length);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [lightbox, photos.length]);

  const firstHostName = hostWorkshops.length ? hostWorkshops[0].host : null;
  useHostEffect(() => {
    if (!firstHostName) return;
    setHostMeta({ loading: true, owner: null, ownerEmail: null, cover: null, socials: mergeHostSocials({}) });
    fetch(`${window.getApiBase()}/host/owner/${encodeURIComponent(firstHostName)}`)
      .then(r => r.json())
      .then(d => setHostMeta({
        loading: false,
        owner:   d.owner || null,
        ownerEmail: d.owner_email != null && String(d.owner_email).trim() !== "" ? String(d.owner_email).trim() : null,
        cover:   d.cover_url != null && String(d.cover_url).trim() !== "" ? String(d.cover_url).trim() : null,
        socials: mergeHostSocials(d.socials),
      }))
      .catch(() => setHostMeta({ loading: false, owner: null, ownerEmail: null, cover: null, socials: mergeHostSocials({}) }));
  }, [firstHostName]);

  // ——— early return ———
  if (!hostWorkshops.length) {
    return (
      <div className="host-page">
        <div className="host-page-inner">
          <button type="button" className="host-back mono tiny" onClick={() => { window.location.hash = ""; }}>
            ← {t.hostBackHome}
          </button>
          <p className="host-not-found">{t.hostNotFound}</p>
        </div>
      </div>
    );
  }

  const hostName = hostWorkshops[0].host;
  const bio = hostWorkshops.reduce(
    (best, w) => ((w.hostBio || "").length > best.length ? w.hostBio || "" : best),
    hostWorkshops[0].hostBio || ""
  );

  const userEmailNorm = user && user.email ? String(user.email).trim().toLowerCase() : "";
  const ownerEmailNorm = hostMeta.ownerEmail
    ? String(hostMeta.ownerEmail).trim().toLowerCase() : "";
  const isOwner = !!(
    user
    && !hostMeta.loading
    && (
      (ownerEmailNorm && userEmailNorm && ownerEmailNorm === userEmailNorm)
      || (hostMeta.owner && user.name === hostMeta.owner)
    )
  );

  // Aggregates
  const cities     = [...new Set(hostWorkshops.map(w => w.city))].sort((a, b) => a.localeCompare(b, "sl"));
  const categories = [...new Set(hostWorkshops.map(w => w.category))];
  const totalRev   = hostWorkshops.reduce((s, w) => s + (w.reviews || 0), 0);
  const aggRating  = totalRev > 0
    ? hostWorkshops.reduce((s, w) => s + w.rating * (w.reviews || 0), 0) / totalRev : 0;
  const allReviews    = gatherHostReviews(hostWorkshops, reviews);
  const primaryAccent = accentForFn ? accentForFn(hostWorkshops[0].category) : "ink";

  const pricesWithVal  = hostWorkshops.map(w => w.price).filter(p => p > 0);
  const minPrice       = pricesWithVal.length ? Math.min(...pricesWithVal) : null;
  const maxPrice       = pricesWithVal.length ? Math.max(...pricesWithVal) : null;
  const hasRange       = minPrice !== null && minPrice !== maxPrice;
  const priceDisplay   = minPrice === null ? null : hasRange ? `od ${minPrice}€` : `${minPrice}€`;
  const priceSub       = hasRange
    ? (lang === "en" ? `up to ${maxPrice}€ / person` : `do ${maxPrice}€ / oseba`)
    : (lang === "en" ? "per person" : "/ oseba");

  const forKids   = hostWorkshops.some(w => w.forKids);
  const forAdults = hostWorkshops.some(w => w.forAdults);

  const scheduleTypes = [...new Set(hostWorkshops.map(w => w.scheduleType || "recurring"))];
  const scheduleMap   = {
    "recurring": lang === "en" ? "On demand"      : "Po dogovoru",
    "weekly":    lang === "en" ? "Weekly"          : "Vsak teden",
    "monthly":   lang === "en" ? "Monthly"         : "Vsak mesec",
    "one-time":  lang === "en" ? "One-time events" : "Enkratni termini",
  };

  const levels    = [...new Set(hostWorkshops.map(w => w.level).filter(l => l && !/^vsi$/i.test(l.trim())))];
  const durations = [...new Set(hostWorkshops.map(w => w.duration).filter(Boolean))];
  const offersTeamBuilding = hostWorkshops.some(w => w.teamBuilding);

  const sourceUrl = hostWorkshops.find(w => w.sourceUrl)?.sourceUrl || hostWorkshops.find(w => w.source)?.source;
  const linkUrl   = sourceUrl ? (/^https?:\/\//i.test(sourceUrl) ? sourceUrl : "https://" + sourceUrl.replace(/^\/+/, "")) : null;
  const linkLabel = hostWorkshops.find(w => w.source)?.source || linkUrl;

  const openEditMode = () => {
    setEditMode(true);
    setEditBio(bio);
    setEditCover((hostMeta.cover && String(hostMeta.cover).trim()) || displayCover || "");
    setEditSocials(mergeHostSocials(hostMeta.socials));
    setWorkshopEditId(null);
  };
  const cancelEdit   = () => { setEditMode(false); setWorkshopEditId(null); };

  const saveEdits = () => {
    if (!user) return;
    setSaving(true);
    const headers = { "Content-Type": "application/json" };
    const actor = ownerActorPayload(user);
    const bioP = fetch(`${window.getApiBase()}/host/update-bio`, {
      method: "POST", headers, body: JSON.stringify({ host_name: hostName, ...actor, bio: editBio }),
    });
    const covP = fetch(`${window.getApiBase()}/host/update-cover`, {
      method: "POST", headers, body: JSON.stringify({ host_name: hostName, ...actor, cover_url: editCover.trim() }),
    });
    const socP = fetch(`${window.getApiBase()}/host/update-socials`, {
      method: "POST",
      headers,
      body: JSON.stringify({
        host_name: hostName,
        ...actor,
        socials:   packHostSocialsForApi(editSocials),
      }),
    });
    Promise.all([bioP, covP, socP])
      .then(() => {
        const packed = packHostSocialsForApi(editSocials);
        setHostMeta(m => ({ ...m, cover: editCover.trim() || null, socials: mergeHostSocials(packed) }));
        if (refreshWorkshops) refreshWorkshops();
        setEditMode(false);
      })
      .finally(() => setSaving(false));
  };

  const openOtherHost = (name) => {
    const s = hostSlug(name);
    if (s && s !== readHostSlugFromHash()) window.location.hash = `#/izvajalec/${s}`;
  };

  const editingWorkshop = workshopEditId ? sortedWorkshops.find(w => w.id === workshopEditId) : null;

  return (
    <div className="host-page">
      <div className="host-page-inner">

        <div className="host-top-row">
          <button type="button" className="host-back mono tiny" onClick={() => { window.location.hash = ""; }}>
            ← {t.hostBackHome}
          </button>

          {/* Ownership controls */}
          <div className="host-ownership-bar">
            {isOwner && !editMode && (
              <button type="button" className="btn-edit-host" onClick={openEditMode}>
                ✎ {lang === "en" ? "Edit page" : "Uredi stran"}
              </button>
            )}
            {isOwner && editMode && (
              <>
                <button type="button" className="btn-secondary-sm" onClick={cancelEdit}>
                  {lang === "en" ? "Cancel" : "Prekliči"}
                </button>
                <button type="button" className="btn-primary-sm" onClick={saveEdits} disabled={saving}>
                  {saving ? "…" : (lang === "en" ? "Save" : "Shrani")}
                </button>
              </>
            )}
            {!isOwner && !hostMeta.loading && (hostMeta.owner || hostMeta.ownerEmail) && (
              <span className="host-claimed-badge mono tiny">
                {lang === "en" ? "Managed by owner" : "Stran je v upravljanju"}
              </span>
            )}
          </div>
        </div>

        {/* Cover */}
        {(displayCover || (isOwner && editMode)) && (
          <div className="host-page-cover">
            {displayCover && (
              <img src={displayCover} alt={hostName} onError={e => { e.currentTarget.style.display = "none"; }} />
            )}
            {isOwner && editMode && (
              <div className="host-cover-edit">
                <label>
                  <span className="mono tiny">{lang === "en" ? "Cover image URL" : "URL naslovne slike"}</span>
                  <input
                    value={editCover}
                    onChange={e => setEditCover(e.target.value)}
                    placeholder="https://…"
                  />
                </label>
                <p className="mono tiny muted" style={{ marginTop: 6 }}>{lang === "en" ? "Leave empty to use the first workshop photo." : "Pusti prazno, če želiš prvo sliko z delavnic."}</p>
              </div>
            )}
          </div>
        )}

        {/* Header */}
        <header className={`host-page-header accent-${primaryAccent}`}>
          <div className="host-page-header-body">
            <div className={`avatar big avatar-${primaryAccent}`}>{hostName[0]}</div>
            <div className="host-page-header-text">
              <h1 className="host-page-title">{hostName}</h1>
              {editMode ? (
                <textarea
                  className="host-bio-edit"
                  value={editBio}
                  onChange={e => setEditBio(e.target.value)}
                  rows={4}
                  placeholder={lang === "en" ? "Describe your studio or practice…" : "Opiši svoj atelje ali ustvarjalni prostor…"}
                />
              ) : (
                bio && <p className="host-page-bio">{bio}</p>
              )}
              <div className="host-page-meta mono tiny">
                {linkUrl && (
                  <a className="host-page-link" href={linkUrl} target="_blank" rel="noopener noreferrer">
                    → {linkLabel}
                  </a>
                )}
              </div>
              {isOwner && editMode && (
                <div className="host-socials-edit">
                  <div className="host-socials-label mono tiny">{t.hostSocials}</div>
                  <div className="host-socials-edit-grid">
                    {HOST_SOCIAL_DEF.map(({ key, label: lab }) => (
                      <label key={key} className="host-social-field">
                        <span className="mono tiny">{lang === "en" ? lab.en : lab.sl}</span>
                        <input
                          value={editSocials[key] || ""}
                          onChange={e => setEditSocials(s => ({ ...s, [key]: e.target.value }))}
                          placeholder="https://…"
                          autoComplete="off"
                        />
                      </label>
                    ))}
                  </div>
                </div>
              )}
              {!editMode && HOST_SOCIAL_DEF.some(d => hostSocialHref(hostMeta.socials[d.key])) && (
                <div className="host-socials" aria-label={t.hostSocials}>
                  <div className="host-socials-label mono tiny">{t.hostSocials}</div>
                  <div className="host-socials-row">
                    {HOST_SOCIAL_DEF.map(({ key, short }) => {
                      const href = hostSocialHref(hostMeta.socials[key]);
                      if (!href) return null;
                      return (
                        <a
                          key={key}
                          className="host-social-pill"
                          href={href}
                          target="_blank"
                          rel="noopener noreferrer"
                          title={key}
                        >
                          {short}
                        </a>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Stat bar */}
          <div className="host-stat-bar">
            <div className="host-stat">
              <span className="host-stat-n">{hostWorkshops.length}</span>
              <span className="host-stat-l mono tiny">{hostWorkshops.length === 1 ? t.hostWorkshopCountOne : t.hostWorkshopCountMany}</span>
            </div>
            <div className="host-stat">
              <span className="host-stat-n">{cities.length}</span>
              <span className="host-stat-l mono tiny">{lang === "en" ? "cities" : "mest"}</span>
            </div>
            {totalRev > 0 && (
              <div className="host-stat">
                <span className="host-stat-n">{aggRating.toFixed(1)}</span>
                <span className="host-stat-l mono tiny">★ ({totalRev})</span>
              </div>
            )}
            {priceDisplay && (
              <div className="host-stat">
                <span className="host-stat-n">{priceDisplay}</span>
                <span className="host-stat-l mono tiny">{priceSub}</span>
              </div>
            )}
          </div>
        </header>

        {/* Info grid */}
        <div className="host-info-grid">
          <InfoBlock label={lang === "en" ? "FOR WHOM" : "ZA KOGA"}>
            {forKids   && <div className="host-info-value host-info-kids">{lang === "en" ? "Children" : "Otroci"}</div>}
            {forAdults && <div className="host-info-value host-info-adults">{lang === "en" ? "Adults" : "Odrasli"}</div>}
            {levels.map(l => <div key={l} className="host-info-value">{l}</div>)}
          </InfoBlock>

          <InfoBlock label={lang === "en" ? "WHERE" : "KJE"}>
            {cities.map(c => <div key={c} className="host-info-value">{c}</div>)}
          </InfoBlock>

          <InfoBlock label={lang === "en" ? "DISCIPLINES" : "PODROČJA"}>
            {categories.map(cat => (
              <div key={cat} className="host-info-value">
                {catLabelFn ? catLabelFn(cat, lang) : cat}
              </div>
            ))}
          </InfoBlock>

          <InfoBlock label={lang === "en" ? "SCHEDULE" : "KDAJ"}>
            {scheduleTypes.map(s => <div key={s} className="host-info-value">{scheduleMap[s] || s}</div>)}
            {durations.map(d => <div key={d} className="host-info-value host-info-muted">{d}</div>)}
          </InfoBlock>

          {levels.length > 0 && (
            <InfoBlock label={lang === "en" ? "LEVEL" : "NIVO"}>
              {levels.map(l => {
                const cls = /začetn/i.test(l) ? "host-info-level-beginner"
                  : /napred/i.test(l) ? "host-info-level-advanced"
                  : /sredn/i.test(l) ? "host-info-level-intermediate" : "";
                return <div key={l} className={`host-info-value ${cls}`}>{l}</div>;
              })}
            </InfoBlock>
          )}

          {offersTeamBuilding && (
            <InfoBlock label={lang === "en" ? "GROUPS" : "SKUPINSKO"}>
              <div className="host-info-value host-info-teambuild">Team building</div>
              <div className="host-info-value host-info-muted">
                {lang === "en" ? "Group events available" : "Skupinske dejavnosti"}
              </div>
            </InfoBlock>
          )}
        </div>

        {/* Workshops */}
        <section className="host-page-section">
          <div className="section-label mono tiny">{t.hostWorkshopsSection}</div>
          <div className={`host-page-grid feed-grid density-${density}`}>
            {GridCardCmp && sortedWorkshops.map(w => (
              <div key={w.id} className={`host-workshop-wrap${editMode ? " edit-mode" : ""}`}>
                <GridCardCmp
                  workshop={w}
                  fav={favs.includes(w.id)}
                  toggleFav={() => toggleFav(w.id)}
                  onOpen={() => { if (!editMode) onOpenWorkshop(w.id); }}
                  density={density}
                  lang={lang}
                  onOpenHost={openOtherHost}
                />
                {isOwner && editMode && (
                  <button
                    type="button"
                    className={`workshop-edit-btn${workshopEditId === w.id ? " active" : ""}`}
                    onClick={() => setWorkshopEditId(workshopEditId === w.id ? null : w.id)}
                  >
                    ✎ {lang === "en" ? "Edit" : "Uredi"}
                  </button>
                )}
              </div>
            ))}
          </div>

          {/* Workshop edit panel */}
          {isOwner && editMode && editingWorkshop && (
            <WorkshopEditPanel
              key={editingWorkshop.id}
              workshop={editingWorkshop}
              user={user}
              onSave={() => { setWorkshopEditId(null); if (refreshWorkshops) refreshWorkshops(); }}
              onCancel={() => setWorkshopEditId(null)}
              onDeactivate={() => { setWorkshopEditId(null); if (refreshWorkshops) refreshWorkshops(); }}
            />
          )}

          {isOwner && editMode && user && (
            <AddWorkshopForm
              hostName={hostName}
              user={user}
              lang={lang}
              onSuccess={() => { if (refreshWorkshops) refreshWorkshops(); }}
            />
          )}
        </section>

        {/* Reviews */}
        <section className="host-page-section host-reviews-section">
          <div className="section-label mono tiny">{t.hostReviewsSection}</div>
          {allReviews.length === 0 ? (
            <p className="mono tiny muted">{t.hostNoReviews}</p>
          ) : (
            <div className="reviews-list host-page-reviews">
              {allReviews.map(r => (
                <div key={`${r.workshopId}-${r.id}`} className={`review-item ${r.mine ? "mine" : ""}`}>
                  <div className={`avatar avatar-${r.color}`}>{r.initial}</div>
                  <div className="review-body">
                    <div className="review-meta">
                      <span className="review-name">
                        {r.name}
                        {r.mine && <span className="mono tiny" style={{ marginLeft: "6px", color: "var(--accent-tomato)" }}>{t.mineLabel}</span>}
                      </span>
                      <span className="mono tiny muted">· {r.when}</span>
                    </div>
                    <div className="mono tiny muted host-review-workshop">{r.workshopTitle}</div>
                    <div className="review-stars mono tiny">
                      {"★".repeat(r.rating)}<span className="muted">{"★".repeat(5 - r.rating)}</span>
                    </div>
                    <div className="review-text">{r.text}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </section>

        {/* Gallery */}
        {photos.length > 0 && (
          <section className="host-gallery-section">
            <div className="section-label mono tiny">{lang === "en" ? "GALLERY" : "GALERIJA"}</div>
            <div className="host-gallery">
              {photos.map((p, i) => (
                <button
                  key={p.id}
                  type="button"
                  className={`host-gallery-item${i === 0 ? " host-gallery-feature" : ""}`}
                  onClick={() => setLightbox(i)}
                  aria-label={p.title}
                >
                  <img src={p.url} alt={p.title} loading="lazy" onError={e => { e.currentTarget.parentElement.style.display = "none"; }} />
                  <div className="host-gallery-caption mono tiny">{p.title}</div>
                </button>
              ))}
            </div>
          </section>
        )}

        {/* Similar places */}
        {similarHosts.length > 0 && (
          <section className="host-similar-section">
            <div className="section-label mono tiny">
              {lang === "en" ? "SIMILAR PLACES" : "PODOBNI IZVAJALCI"}
            </div>
            <div className="host-similar-grid">
              {similarHosts.map(w => (
                <button
                  key={w.host}
                  type="button"
                  className="host-similar-card"
                  onClick={() => openOtherHost(w.host)}
                >
                  <div className="host-similar-img">
                    <img src={w.imageUrl} alt={w.host}
                      onError={e => { e.currentTarget.closest(".host-similar-card").style.display = "none"; }} />
                  </div>
                  <div className="host-similar-body">
                    <div className="host-similar-name">{w.host}</div>
                    <div className="mono tiny muted">{w.city}</div>
                    {catLabelFn && (
                      <div className="mono tiny muted">{catLabelFn(w.category, lang)}</div>
                    )}
                  </div>
                  <div className="host-similar-arrow mono tiny">→</div>
                </button>
              ))}
            </div>
          </section>
        )}

        {/* Lightbox */}
        {lightbox !== null && photos[lightbox] && (
          <div className="host-lightbox" onClick={() => setLightbox(null)}>
            <button type="button" className="host-lightbox-close" onClick={() => setLightbox(null)} aria-label="Zapri">✕</button>
            {photos.length > 1 && (
              <button type="button" className="host-lightbox-prev" onClick={e => { e.stopPropagation(); setLightbox(i => (i - 1 + photos.length) % photos.length); }} aria-label="Prejšnja">‹</button>
            )}
            <div className="host-lightbox-img-wrap" onClick={e => e.stopPropagation()}>
              <img src={photos[lightbox].url} alt={photos[lightbox].title} />
              <div className="host-lightbox-title mono tiny">{photos[lightbox].title}</div>
              {photos.length > 1 && (
                <div className="host-lightbox-counter mono tiny">{lightbox + 1} / {photos.length}</div>
              )}
            </div>
            {photos.length > 1 && (
              <button type="button" className="host-lightbox-next" onClick={e => { e.stopPropagation(); setLightbox(i => (i + 1) % photos.length); }} aria-label="Naslednja">›</button>
            )}
          </div>
        )}

      </div>
    </div>
  );
}

Object.assign(window, { HostPage, hostSlug, readHostSlugFromHash, gatherHostReviews });
