/* global React */
const { useState: useStO, useEffect: useEffO, useMemo: useMemoO } = React;

const ONB_LOGO = __res("hoodLogo", "assets/hood-logo.png");
const ONB_LS_KEY = "hood-onboarding-v1";
const ONB_APP_URL = window.__HOOD_APP_URL || "https://app.hood.team";

/* ---------- data ---------- */
const ONB_CATS = [
  { id: "beauty",   emoji: "✂️", label: "Güzellik & Bakım" },
  { id: "fitness",  emoji: "🏋️", label: "Spor & Fitness" },
  { id: "health",   emoji: "🏥", label: "Sağlık & Terapi" },
  { id: "edu",      emoji: "🎨", label: "Eğitim & Atölye" },
  { id: "wellness", emoji: "💆", label: "Wellness & Masaj" },
  { id: "creative", emoji: "✨", label: "Kreatif Hizmetler" },
];
const ONB_SVC_SUGGEST = {
  beauty:   ["Kuaför", "Manikür", "Yüz Bakımı", "Epilasyon", "Kaş Bakımı"],
  fitness:  ["Pilates", "Reformer Pilates", "Yoga", "Personal Training", "Padel Dersi", "Tenis Dersi"],
  health:   ["Psikolog Seansı", "Fizik Tedavi", "Diyetisyen Görüşmesi"],
  edu:      ["Gitar Dersi", "Piyano Dersi", "Resim Atölyesi", "Dil Dersi"],
  wellness: ["Masaj", "Spa Seansı", "Meditasyon"],
  creative: ["Fotoğraf Çekimi", "Tasarım Danışmanlığı", "Stil Danışmanlığı"],
};
const ONB_AVA_COLORS = ["#FF4900", "#2E6FE8", "#7C3AED", "#0E9F6E", "#D9480F", "#0891B2", "#BE185D", "#A16207"];

/* ---------- helpers ---------- */
const onbCap = (s) => s.charAt(0).toLocaleUpperCase("tr-TR") + s.slice(1);
function onbFormatName(full){
  const parts = full.trim().replace(/\s+/g, " ").split(" ");
  if (parts.length === 1) return onbCap(parts[0]);
  const first = parts.slice(0, -1).map(onbCap).join(" ");
  const last = parts[parts.length - 1];
  return `${first} ${last.charAt(0).toLocaleUpperCase("tr-TR")}.`;
}
const onbInitials = (name) => name.split(" ").map(p => p[0]).join("").slice(0, 2).toLocaleUpperCase("tr-TR");
function onbFmtPhone(raw){
  let d = raw.replace(/\D/g, "");
  if (d.startsWith("90")) d = d.slice(2);
  if (d.startsWith("0")) d = d.slice(1);
  d = d.slice(0, 10);
  return [d.slice(0,3), d.slice(3,6), d.slice(6,8), d.slice(8,10)].filter(Boolean).join(" ");
}
const onbPhoneValid = (p) => { const d = p.replace(/\D/g, ""); return d.length === 10 && d.startsWith("5"); };
function onbSlug(s){
  const map = { ç:"c", ğ:"g", ı:"i", ö:"o", ş:"s", ü:"u" };
  return s.toLocaleLowerCase("tr-TR").replace(/[çğıöşü]/g, ch => map[ch] || ch)
    .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 30) || "isletmeniz";
}

function onbLoad(){
  try { const raw = localStorage.getItem(ONB_LS_KEY); return raw ? JSON.parse(raw) : null; } catch(e){ return null; }
}

/* UTF-8 safe base64url — the app decodes this on /provider-onboarding?prefill= */
function onbEncodePayload(obj){
  const bytes = new TextEncoder().encode(JSON.stringify(obj));
  let bin = "";
  bytes.forEach(b => { bin += String.fromCharCode(b); });
  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

/* ---------- icons ---------- */
const OnbI = {
  back: (p)=> <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M19 12H5"/><path d="m11 18-6-6 6-6"/></svg>,
  arrow: (p)=> <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>,
  check: (p)=> <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 6 9 17l-5-5"/></svg>,
  party: (p)=> <svg viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5.8 11.3 2 22l10.7-3.79"/><path d="M4 3h.01"/><path d="M22 8h.01"/><path d="M15 2h.01"/><path d="M22 20h.01"/><path d="m22 2-2.24.75a2.9 2.9 0 0 0-1.96 3.12c.1.86-.57 1.63-1.45 1.63h-.38c-.86 0-1.6.6-1.76 1.44L14 10"/><path d="m22 13-.82-.33c-.86-.34-1.82.2-1.98 1.11c-.11.7-.72 1.22-1.43 1.22H17"/><path d="m11 2 .33.82c.34.86-.2 1.82-1.11 1.98C9.52 4.9 9 5.52 9 6.23V7"/><path d="M11 13c1.93 1.93 2.83 4.17 2 5-.83.83-3.07-.07-5-2-1.93-1.93-2.83-4.17-2-5 .83-.83 3.07.07 5 2Z"/></svg>,
};

/* ---------- shell ---------- */
function OnbStep({ eyebrow, title, sub, children, screenLabel }){
  return (
    <div className="onb-step" data-screen-label={screenLabel}>
      <div className="onb-eyebrow">{eyebrow}</div>
      <h1 className="onb-h">{title}</h1>
      <p className="onb-sub">{sub}</p>
      {children}
    </div>
  );
}

function OnbApp({ embed = false }){
  const saved = useMemoO(onbLoad, []);
  const [type, setType] = useStO(saved?.type ?? null);
  const [bizName, setBizName] = useStO(saved?.bizName ?? "");
  const [cats, setCats] = useStO(saved?.cats ?? []);
  const [services, setServices] = useStO(saved?.services ?? []); // {name, cat, mode, price}
  const [team, setTeam] = useStO(saved?.team ?? []);
  const [assign, setAssign] = useStO(saved?.assign ?? {});       // name -> [memberIdx]
  const [phone, setPhone] = useStO(saved?.phone ?? "");
  const [stepIdx, setStepIdx] = useStO(saved?.stepIdx ?? 0);
  const [customSvc, setCustomSvc] = useStO("");
  const [memberInput, setMemberInput] = useStO("");

  const steps = useMemoO(() => {
    const base = ["type", "name", "cats", "services"];
    if (type === "team") base.push("team");
    base.push("prices");
    if (type === "team") base.push("match");
    base.push("phone");
    return base;
  }, [type]);
  const step = steps[Math.min(stepIdx, steps.length - 1)];

  /* persist */
  useEffO(() => {
    try { localStorage.setItem(ONB_LS_KEY, JSON.stringify({ type, bizName, cats, services, team, assign, phone, stepIdx })); } catch(e){}
  }, [type, bizName, cats, services, team, assign, phone, stepIdx]);

  /* default: all experts on all services when entering match */
  useEffO(() => {
    if (step !== "match") return;
    setAssign(prev => {
      const next = { ...prev };
      services.forEach(s => {
        if (!Array.isArray(next[s.name]) || next[s.name].some(i => i >= team.length)) {
          next[s.name] = team.map((_, i) => i);
        }
      });
      return next;
    });
  }, [step, services, team]);

  const go = (d) => setStepIdx(i => Math.max(0, Math.min(steps.length - 1, i + d)));

  /* ---------- actions ---------- */
  const toggleCat = (id) => setCats(c => c.includes(id) ? c.filter(x => x !== id) : [...c, id]);
  const toggleSvc = (name, cat) => setServices(list => {
    const has = list.find(s => s.name === name);
    return has ? list.filter(s => s.name !== name) : [...list, { name, cat, mode: "bireysel", price: "" }];
  });
  const addCustomSvc = () => {
    const name = customSvc.trim();
    if (!name || services.find(s => s.name.toLocaleLowerCase("tr-TR") === name.toLocaleLowerCase("tr-TR"))) return;
    setServices(list => [...list, { name: onbCap(name), cat: cats[0] || "beauty", mode: "bireysel", price: "" }]);
    setCustomSvc("");
  };
  const setMode = (name, mode) => setServices(list => list.map(s => s.name === name ? { ...s, mode } : s));
  const setPrice = (name, price) => setServices(list => list.map(s => s.name === name ? { ...s, price: price.replace(/[^\d]/g, "").slice(0, 6) } : s));
  const addMember = () => {
    const formatted = onbFormatName(memberInput);
    if (!memberInput.trim() || team.includes(formatted)) return;
    setTeam(t => [...t, formatted]);
    setMemberInput("");
  };
  const removeMember = (idx) => {
    setTeam(t => t.filter((_, i) => i !== idx));
    setAssign(a => {
      const next = {};
      Object.entries(a).forEach(([k, arr]) => { next[k] = arr.filter(i => i !== idx).map(i => i > idx ? i - 1 : i); });
      return next;
    });
  };
  const toggleAssign = (svcName, idx) => setAssign(a => {
    const cur = a[svcName] ?? team.map((_, i) => i);
    const next = cur.includes(idx) ? cur.filter(i => i !== idx) : [...cur, idx].sort((x, y) => x - y);
    return { ...a, [svcName]: next };
  });

  /* Hand the collected setup off to the real app: the provider onboarding
     there prefills phone auth + the registration form and offers these
     services as defaults when the provider creates them for real. */
  const goToApp = () => {
    const payload = {
      v: 1,
      type,
      bizName: bizName.trim(),
      cats,
      services: services.map(s => ({ name: s.name, mode: s.mode, price: s.price })),
      team,
      phone: phone.replace(/\D/g, ""),
    };
    window.location.href = `${ONB_APP_URL}/provider-onboarding?prefill=${onbEncodePayload(payload)}`;
  };

  /* ---------- validation ---------- */
  const canNext =
    step === "type" ? !!type :
    step === "name" ? bizName.trim().length >= 2 :
    step === "cats" ? cats.length > 0 :
    step === "services" ? services.length > 0 :
    step === "team" ? team.length > 0 :
    step === "prices" ? services.every(s => Number(s.price) > 0) :
    step === "match" ? services.every(s => (assign[s.name] ?? []).length > 0) :
    step === "phone" ? onbPhoneValid(phone) :
    true;

  const fmtPrice = (p) => Number(p).toLocaleString("tr-TR");
  const stepNo = stepIdx + 1, total = steps.length;

  return (
    <div className={embed ? "onb-scope onb-embed" : ""}>
      <header className="onb-header">
        <div className="onb-header-in">
          {!embed && <img src={ONB_LOGO} alt="Hood"/>}
          <div className="onb-progress"><div className="onb-progress-fill" style={{ width: `${(stepNo / total) * 100}%` }}/></div>
          <span className="onb-step-count">{stepNo} / {total}</span>
        </div>
      </header>

      <main className="onb-main">
        {/* STEP: account type */}
        {step === "type" && (
          <OnbStep screenLabel="Onboarding — Hesap Türü" eyebrow="Hood'a hoş geldiniz" title="Hood'u nasıl kullanacaksınız?" sub="Size en uygun kurulumu hazırlayalım.">
            <div className="onb-type-grid">
              <button className={`onb-type-card ${type === "solo" ? "sel" : ""}`} onClick={() => { setType("solo"); setStepIdx(1); }}>
                <span className="onb-type-ico">👤</span>
                <h3>Kendim için</h3>
                <p>Tek başıma hizmet veriyorum. Takvimim, randevularım ve ödemelerim tek yerde olsun.</p>
              </button>
              <button className={`onb-type-card ${type === "team" ? "sel" : ""}`} onClick={() => { setType("team"); setStepIdx(1); }}>
                <span className="onb-type-ico">🏢</span>
                <h3>Kurum — Ekibim için</h3>
                <p>Stüdyo, salon veya klinik yönetiyorum. Ekibimi ve tüm randevuları tek ekrandan yöneteyim.</p>
              </button>
            </div>
          </OnbStep>
        )}

        {/* STEP: name */}
        {step === "name" && (
          <OnbStep screenLabel="Onboarding — İsim" eyebrow={`Adım ${stepNo}`}
            title={type === "team" ? "Kurumunuzun adı ne?" : "Adınız ne?"}
            sub={type === "team" ? "Rezervasyon sayfanızda ve linkinizde bu ad görünecek." : "Müşterileriniz sizi bu adla görecek; rezervasyon linkiniz de buradan oluşur."}>
            <input className="onb-input" style={{ width: "100%", fontSize: 16.5, padding: "15px 18px" }} autoFocus
                   placeholder={type === "team" ? "örn. Studio Flow" : "örn. Emre Can"}
                   value={bizName} onChange={e => setBizName(e.target.value)}
                   onKeyDown={e => e.key === "Enter" && bizName.trim().length >= 2 && go(1)}/>
            {bizName.trim().length >= 2 && (
              <div className="onb-link-pill" style={{ marginTop: 18, marginBottom: 0 }}>
                <span className="dim">hood.team/book/</span><span className="hi">{onbSlug(bizName)}</span>
              </div>
            )}
          </OnbStep>
        )}

        {/* STEP: categories */}
        {step === "cats" && (
          <OnbStep screenLabel="Onboarding — Kategoriler" eyebrow={`Adım ${stepNo}`} title="Hangi alanlarda hizmet veriyorsunuz?" sub="Birden fazla seçebilirsiniz.">
            <div className="onb-cat-grid">
              {ONB_CATS.map(c => (
                <button key={c.id} className={`onb-cat ${cats.includes(c.id) ? "sel" : ""}`} onClick={() => toggleCat(c.id)}>
                  <span className="emoji">{c.emoji}</span>
                  <span className="lbl">{c.label}</span>
                  <span className="chk">{cats.includes(c.id) && <OnbI.check style={{ width: 11, height: 11 }}/>}</span>
                </button>
              ))}
            </div>
          </OnbStep>
        )}

        {/* STEP: services */}
        {step === "services" && (
          <OnbStep screenLabel="Onboarding — Hizmetler" eyebrow={`Adım ${stepNo}`} title="Hangi hizmetleri sunuyorsunuz?" sub="Önerilenlerden seçin veya kendi hizmetinizi ekleyin. Her hizmet için bireysel mi grup mu olduğunu belirleyin.">
            {cats.map(cid => {
              const cat = ONB_CATS.find(c => c.id === cid);
              return (
                <div className="onb-svc-group" key={cid}>
                  <div className="onb-svc-group-l"><span>{cat.emoji}</span>{cat.label}</div>
                  <div className="onb-chips">
                    {ONB_SVC_SUGGEST[cid].map(name => {
                      const sel = !!services.find(s => s.name === name);
                      return (
                        <button key={name} className={`onb-chip ${sel ? "sel" : ""}`} onClick={() => toggleSvc(name, cid)}>
                          {sel ? <OnbI.check style={{ width: 13, height: 13 }}/> : <span className="plus">+</span>}{name}
                        </button>
                      );
                    })}
                  </div>
                </div>
              );
            })}
            <div className="onb-custom-row">
              <input className="onb-input" placeholder="Başka bir hizmet ekleyin…" value={customSvc}
                     onChange={e => setCustomSvc(e.target.value)} onKeyDown={e => e.key === "Enter" && addCustomSvc()}/>
              <button className="onb-add-btn" disabled={!customSvc.trim()} onClick={addCustomSvc}>Ekle</button>
            </div>

            {services.length > 0 && (
              <div className="onb-sel-list">
                <div className="onb-sel-l">Seçilen hizmetler · {services.length}</div>
                {services.map(s => (
                  <div className="onb-sel-row" key={s.name}>
                    <span className="nm">{s.name}</span>
                    <div className="onb-mode-seg">
                      <button className={s.mode === "bireysel" ? "on" : ""} onClick={() => setMode(s.name, "bireysel")}>Bireysel</button>
                      <button className={s.mode === "grup" ? "on" : ""} onClick={() => setMode(s.name, "grup")}>Grup</button>
                    </div>
                    <button className="onb-x" aria-label={`${s.name} kaldır`} onClick={() => toggleSvc(s.name, s.cat)}>×</button>
                  </div>
                ))}
              </div>
            )}
          </OnbStep>
        )}

        {/* STEP: team */}
        {step === "team" && (
          <OnbStep screenLabel="Onboarding — Ekip" eyebrow={`Adım ${stepNo}`} title="Ekibinizi ekleyin" sub="Uzmanlarınızın adlarını girin — daha sonra davet edebilir, yetkilerini düzenleyebilirsiniz.">
            <div className="onb-custom-row">
              <input className="onb-input" placeholder="Ad Soyad — örn. Emre Can" value={memberInput}
                     onChange={e => setMemberInput(e.target.value)} onKeyDown={e => e.key === "Enter" && addMember()}/>
              <button className="onb-add-btn" disabled={!memberInput.trim()} onClick={addMember}>Ekle</button>
            </div>
            <p className="onb-hint">İsimler gizlilik için "Emre C." biçiminde görünür.</p>
            {team.length > 0 && (
              <div className="onb-team-list">
                {team.map((name, i) => (
                  <div className="onb-team-row" key={name}>
                    <span className="onb-ava" style={{ background: ONB_AVA_COLORS[i % ONB_AVA_COLORS.length] }}>{onbInitials(name)}</span>
                    <span className="nm">{name}</span>
                    <button className="onb-x" aria-label={`${name} kaldır`} onClick={() => removeMember(i)}>×</button>
                  </div>
                ))}
              </div>
            )}
          </OnbStep>
        )}

        {/* STEP: prices */}
        {step === "prices" && (
          <OnbStep screenLabel="Onboarding — Fiyatlar" eyebrow={`Adım ${stepNo}`} title="Hizmetlerinizi fiyatlandırın" sub={type === "team" ? "Seans başına fiyat girin. Grup hizmetlerinde fiyat katılımcı başınadır." : "Seans başına fiyat girin."}>
            <div className="onb-price-list">
              {services.map(s => (
                <div className="onb-price-row" key={s.name}>
                  <span className="nm">{s.name}</span>
                  <span className={`onb-mode-badge ${s.mode === "grup" ? "grp" : ""}`}>{s.mode === "grup" ? "Grup" : "Bireysel"}</span>
                  <label className="onb-price-input">
                    <span>₺</span>
                    <input inputMode="numeric" placeholder="0" value={s.price} onChange={e => setPrice(s.name, e.target.value)}/>
                  </label>
                </div>
              ))}
            </div>
          </OnbStep>
        )}

        {/* STEP: match */}
        {step === "match" && (
          <OnbStep screenLabel="Onboarding — Eşleştirme" eyebrow={`Adım ${stepNo}`} title="Hizmet — uzman eşleştirmesi" sub="Başlangıçta tüm uzmanlar tüm hizmetlere atandı. Bir hizmeti vermeyen uzmanın ismine tıklayarak çıkarabilirsiniz.">
            <div className="onb-match-list">
              {services.map(s => {
                const cur = assign[s.name] ?? team.map((_, i) => i);
                return (
                  <div className="onb-match-card" key={s.name}>
                    <div className="onb-match-head">
                      <span className="nm">{s.name}</span>
                      <span className="meta">{s.mode === "grup" ? "Grup" : "Bireysel"} · ₺{fmtPrice(s.price)} · {cur.length}/{team.length} uzman</span>
                    </div>
                    <div className="onb-member-chips">
                      {team.map((name, i) => {
                        const on = cur.includes(i);
                        return (
                          <button key={name} className={`onb-member-chip ${on ? "" : "off"}`} onClick={() => toggleAssign(s.name, i)}>
                            <span className="mini-ava" style={{ background: ONB_AVA_COLORS[i % ONB_AVA_COLORS.length] }}>{onbInitials(name)}</span>
                            {name}
                          </button>
                        );
                      })}
                    </div>
                    {cur.length === 0 && <div className="onb-warn">Bu hizmete en az bir uzman atanmalı.</div>}
                  </div>
                );
              })}
            </div>
          </OnbStep>
        )}

        {/* STEP: phone */}
        {step === "phone" && (
          <OnbStep screenLabel="Onboarding — Telefon" eyebrow={`Adım ${stepNo}`} title="Son adım: telefon numaranız" sub="Hesabınızı bu numarayla oluşturacağız — doğrulama kodunuz WhatsApp ile gelir.">
            <div className="onb-phone-row">
              <span className="cc">+90</span>
              <input inputMode="tel" autoFocus placeholder="5XX XXX XX XX" value={phone}
                     onChange={e => setPhone(onbFmtPhone(e.target.value))}
                     onKeyDown={e => e.key === "Enter" && onbPhoneValid(phone) && goToApp()}/>
            </div>
            <p className="onb-hint">Numaranız yalnızca giriş ve randevu bildirimleri için kullanılır.</p>
          </OnbStep>
        )}

        {/* nav (hidden on the first step) */}
        {step !== "type" && (
          <div className="onb-footer">
            <button className="onb-btn onb-btn-ghost" onClick={() => go(-1)}><OnbI.back style={{ width: 17, height: 17 }}/> Geri</button>
            <button className="onb-btn onb-btn-primary" disabled={!canNext} onClick={() => step === "phone" ? goToApp() : go(1)} style={{ marginLeft: "auto" }}>
              {step === "phone" ? "Hesabımı Oluştur" : step === "match" ? "Eşleştirmeyi Onayla" : "Devam Et"} <OnbI.arrow style={{ width: 17, height: 17 }}/>
            </button>
          </div>
        )}
      </main>
    </div>
  );
}

const onbMountEl = document.getElementById("onb-root");
if (onbMountEl) ReactDOM.createRoot(onbMountEl).render(<OnbApp/>);
window.OnbApp = OnbApp;
