const { useState: useStateSL } = React;

function ShilletnaLanding() {
  const [creating,    setCreating]    = useStateSL(false);
  const [groupName,   setGroupName]   = useStateSL("");
  const [groupSlug,   setGroupSlug]   = useStateSL("");
  const [fieldError,  setFieldError]  = useStateSL("");
  const [busy,        setBusy]        = useStateSL(false);
  const [createError, setCreateError] = useStateSL("");

  const groups = Object.values(GROUP_CONFIGS);

  function handleSlugInput(val) {
    setGroupSlug(val.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, 24));
    setFieldError("");
  }

  async function handleCreate() {
    const slug = groupSlug.trim();
    const name = groupName.trim();
    if (!name) return setFieldError("اكتب اسم المجموعة");
    if (!slug)  return setFieldError("اكتب رابط المجموعة");
    if (slug.length < 3) return setFieldError("الرابط قصير جداً · ٣ أحرف على الأقل");
    if (GROUP_CONFIGS[slug]) return setFieldError("هذا الرابط محجوز بالفعل");

    setBusy(true);
    setCreateError("");
    try {
      const binId = await createGroup(slug, name, "♠");
      window.location.href = `/${slug}?bid=${binId}`;
    } catch {
      setCreateError("فشل إنشاء المجموعة · تحقق من الاتصال وحاول مرة أخرى");
      setBusy(false);
    }
  }

  function resetForm() {
    setCreating(false);
    setGroupName("");
    setGroupSlug("");
    setFieldError("");
    setCreateError("");
  }

  return (
    <div className="shilletna-screen">

      {/* Hero */}
      <div className="shilletna-hero">
        <div className="shilletna-suit">♠</div>
        <div className="shilletna-title">شلتنا</div>
        <div className="shilletna-tagline">سجّل نتائج مجموعتك · طرنيب وتركس</div>
      </div>

      {/* Groups list */}
      <div className="shilletna-section">
        <div className="section-title" style={{ fontSize: 17, marginBottom: 10 }}>المجموعات</div>
        {groups.map(g => (
          <a key={g.slug} href={`/${g.slug}`} className="group-card">
            <div className="group-card-icon" style={{ background: g.color }}>{g.icon}</div>
            <div className="group-card-info">
              <div className="group-card-name">{g.name}</div>
              <div className="group-card-url">shilletna.com/{g.slug}</div>
            </div>
            <div className="group-card-arrow">←</div>
          </a>
        ))}
      </div>

      {/* Create group */}
      <div className="shilletna-section">
        <div className="section-title" style={{ fontSize: 17, marginBottom: 10 }}>مجموعة جديدة</div>

        {!creating ? (
          <button
            className="btn-primary"
            style={{ width: "100%", fontSize: 20, padding: "15px 0" }}
            onClick={() => setCreating(true)}
          >+ أنشئ مجموعتك</button>
        ) : (
          <div style={{ background: "rgba(0,0,0,0.45)", border: "3px solid #000", borderRadius: 20, padding: 16, boxShadow: "5px 5px 0 #000" }}>

            <input
              className="field"
              placeholder="اسم المجموعة · مثال: الشلة"
              value={groupName}
              onChange={e => { setGroupName(e.target.value); setFieldError(""); }}
              style={{ marginBottom: 10, display: "block" }}
              dir="rtl"
            />

            <div style={{ position: "relative", marginBottom: 4 }}>
              <input
                className="field"
                placeholder="رابط المجموعة · مثال: shella"
                value={groupSlug}
                onChange={e => handleSlugInput(e.target.value)}
                style={{ display: "block", direction: "ltr" }}
              />
            </div>

            {groupSlug && (
              <div style={{ fontFamily: "Cairo, sans-serif", fontSize: 12, color: "var(--gold)", fontWeight: 800, marginBottom: 10, paddingRight: 4 }}>
                shilletna.com/<span style={{ color: "var(--neon-cyan)" }}>{groupSlug}</span>
              </div>
            )}

            {fieldError  && <div style={{ color: "var(--red)", fontFamily: "Lalezar,serif", fontSize: 15, marginBottom: 8 }}>{fieldError}</div>}
            {createError && <div style={{ color: "var(--red)", fontFamily: "Lalezar,serif", fontSize: 14, marginBottom: 8 }}>{createError}</div>}

            <div style={{ display: "flex", gap: 10 }}>
              <button
                className="btn-primary"
                style={{ flex: 1, fontSize: 19, padding: "12px 0" }}
                onClick={handleCreate}
                disabled={busy}
              >{busy ? "جاري الإنشاء…" : "إنشاء ♠"}</button>
              <button
                className="btn-primary"
                style={{ flex: 1, fontSize: 19, padding: "12px 0", background: "#000", color: "var(--cream)" }}
                onClick={resetForm}
              >إلغاء</button>
            </div>
          </div>
        )}
      </div>

      <div style={{ textAlign: "center", fontFamily: "Cairo,sans-serif", fontSize: 11, color: "var(--cream)", opacity: 0.25, marginTop: 8, paddingBottom: 24, fontWeight: 700 }}>
        shilletna.com · لعبتنا لعبتك
      </div>

    </div>
  );
}

Object.assign(window, { ShilletnaLanding });
