const { useState, useEffect } = React;

// ==== حط القيم تبع مشروعك هنا ====
const SUPABASE_URL = "https://hnzzlwnzolheasfvlxmb.supabase.co";
const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imhuenpsd256b2xoZWFzZnZseG1iIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ0MzA2ODYsImV4cCI6MjA3MDAwNjY4Nn0.hH0Z8QDU3hiiEiKjzLxaJkyaRpQIncJcmBCE-4f1b08";

// عميل Supabase (من سكربت ال-CDN)
const sb = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

// جلب نتائج من جدول listings عبر REST
async function fetchResults({ q, city }) {
  // لو ما عندك بيانات، رجّع مصفوفة فاضية بدل ما توقّف الصفحة
  try {
    const url = new URL(`${SUPABASE_URL}/rest/v1/listings`);
    url.searchParams.set("select", "id,title,city,price,image,score,description");
    if (q && q.trim()) {
      url.searchParams.set("or", `title.ilike.*${q}*,description.ilike.*${q}*`);
    }
    if (city && city.trim()) {
      url.searchParams.set("city", `ilike.*${city}*`);
    }
    url.searchParams.set("limit", "24");

    const res = await fetch(url.toString(), {
      headers: {
        apikey: SUPABASE_ANON_KEY,
        Authorization: `Bearer ${SUPABASE_ANON_KEY}`,
      },
    });

    if (!res.ok) {
      throw new Error(`REST ${res.status} ${res.statusText}`);
    }

    const data = await res.json();
    return (data || []).map((r, i) => ({
      id: r.id ?? i,
      title: r.title ?? `Option ${i + 1}`,
      city: r.city ?? "",
      price: r.price ?? "",
      image: r.image ?? `https://picsum.photos/seed/${i}/800/500`,
      score: r.score ?? Math.floor(70 + Math.random() * 30),
      desc: r.description ?? "Local mock score",
    }));
  } catch (err) {
    console.error("fetchResults error:", err);
    return [];
  }
}

function Card({ item }) {
  return (
    <div className="rounded-2xl overflow-hidden bg-white text-black shadow-2xl">
      <div className="relative h-40">
        <img src={item.image} alt={item.title} className="w-full h-full object-cover" />
        <div className="absolute top-2 right-2 bg-black bg-opacity-70 text-white text-xs px-2 py-1 rounded-full">
          {item.score}%
        </div>
      </div>
      <div className="p-4 space-y-1">
        <h3 className="font-bold text-base leading-6">{item.title}</h3>
        <div className="text-sm text-gray-600">{item.city} {item.price && `• ${item.price}`}</div>
        <div className="text-xs text-gray-500">{item.desc}</div>
      </div>
    </div>
  );
}

function App() {
  const [q, setQ] = useState("");
  const [city, setCity] = useState("");
  const [items, setItems] = useState([]);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  async function onSearch() {
    setBusy(true);
    setErr("");
    const res = await fetchResults({ q, city });
    setItems(res);
    if (res.length === 0) {
      setErr("لا توجد نتائج — تأكد أن جدول listings فيه بيانات وسياسة القراءة مفعّلة.");
    }
    setBusy(false);
  }

  useEffect(() => {
    // بحث مبدئي للتأكد كل شيء يعمل
    onSearch();
    // eslint-disable-next-line
  }, []);

  return (
    <div className="max-w-5xl mx-auto px-4 py-10">
      <h1 className="text-center text-2xl font-extrabold text-green-400 mb-6">NeuroMatrix AI</h1>

      <div className="bg-white/5 border border-white/10 rounded-2xl p-4 mb-6">
        <div className="flex gap-2">
          <input
            type="text"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="اكتب ما تريد البحث عنه…"
            className="flex-1 rounded-xl px-4 py-3 bg-black/60 border border-white/15 outline-none focus:border-green-400/60 text-white"
          />
          <input
            type="text"
            value={city}
            onChange={(e) => setCity(e.target.value)}
            placeholder="مدينة (اختياري)"
            className="w-48 rounded-xl px-4 py-3 bg-black/60 border border-white/15 outline-none focus:border-green-400/60 text-white"
          />
          <button
            onClick={onSearch}
            className="rounded-xl px-5 bg-green-600 hover:bg-green-500 text-white"
          >
            Search
          </button>
        </div>
        {busy && <div className="text-center text-white/70 mt-3">جارِ الجلب…</div>}
        {err && !busy && <div className="text-center text-yellow-300 mt-3">{err}</div>}
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6">
        {items.map((it) => <Card key={it.id} item={it} />)}
      </div>
    </div>
  );
}

// ريندر
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
