// Family competitions — React UI (transpiled in-browser by Babel standalone, like worldcup).
// Routes live in the URL hash so the phone's back button works:
//   #            home (competition list)
//   #c/3         competition 3 gallery
//   #c/3/e/7     entry 7 full-screen
const { useState, useEffect, useCallback, useMemo, useRef } = React;

const AR = new Intl.NumberFormat('ar-AE');
const n = (x) => AR.format(x || 0);
// Arabic counting: 3–10 take the plural, 11+ take the singular (١٦ مشاركة).
const entriesLabel = (k) => (k === 0 ? 'لا توجد مشاركات بعد' : k === 1 ? 'مشاركة واحدة' : k === 2 ? 'مشاركتان'
  : k <= 10 ? `${n(k)} مشاركات` : `${n(k)} مشاركة`);
const fmtDate = (iso) => new Date(iso).toLocaleString('ar-AE', { timeZone: 'Asia/Dubai', weekday: 'long', hour: 'numeric', minute: '2-digit' });

function parseHash() {
  const m = location.hash.match(/^#c\/(\d+)(?:\/e\/(\d+))?/);
  return m ? { comp: Number(m[1]), entry: m[2] ? Number(m[2]) : null } : { comp: null, entry: null };
}
// inApp: true once we've navigated inside the site, so "close" can use history.back()
// safely (a shared deep link to an entry has no in-site page to go back to).
let inApp = false;
const go = (h) => { inApp = true; if (location.hash !== h) location.hash = h; };

// ── confetti in flag colours ──
function burstConfetti() {
  const box = document.createElement('div');
  box.className = 'confetti';
  const cols = ['#E0242F', '#00843D', '#FFFFFF', '#1A1A1A', '#EBC261'];
  for (let i = 0; i < 70; i++) {
    const p = document.createElement('i');
    p.style.left = Math.random() * 100 + 'vw';
    p.style.background = cols[i % cols.length];
    p.style.animationDelay = Math.random() * 0.4 + 's';
    p.style.animationDuration = 1.6 + Math.random() * 1.4 + 's';
    p.style.transform = `rotate(${Math.random() * 360}deg)`;
    box.appendChild(p);
  }
  document.body.appendChild(box);
  setTimeout(() => box.remove(), 3600);
}

// ── small pieces ──
const hasMedia = (e) => !!e.src;
const votable = (c) => c.status === 'open' && c.entries.some(hasMedia);
const isVideoComp = (c) => c && c.icon === 'video';
const soonOne = (c) => (isVideoComp(c) ? 'الفيديو قريبًا' : 'الصورة قريبًا');
const soonMany = (c) => (isVideoComp(c) ? 'المقاطع قريبًا' : 'الصور قريبًا');

function Status({ c, mine }) {
  if (c.status === 'closed') return <span className="pill pill-muted">{c.resultsVisible ? '🏆 النتائج' : 'انتهى التصويت'}</span>;
  if (mine) return <span className="pill pill-green">✓ صوّتّ</span>;
  if (!votable(c)) return <span className="pill pill-soon">{soonMany(c)}</span>;
  return <span className="pill pill-red">صوّت الآن</span>;
}

// Name-only entry (photo/video not uploaded yet): an album card with the first letter.
function Placeholder({ name, big, label }) {
  return (
    <div className={'ph' + (big ? ' ph-big' : '')}>
      <span className="ph-initial">{(name || '').replace(/^(أم|ام|أبو|ابو)\s+/, '').trim().charAt(0)}</span>
      <span className="ph-label">{label || 'الصورة قريبًا'}</span>
    </div>
  );
}

function Thumb({ e, c }) {
  if (!hasMedia(e)) return <Placeholder name={e.name} label={soonOne(c)} />;
  if (e.thumb) return <img src={e.thumb} alt="" loading="lazy" decoding="async" />;
  if (e.type === 'video') return <video src={e.src + '#t=0.5'} muted playsInline preload="metadata" />;
  return <div className="thumb-empty">🖼️</div>;
}

function rankOf(c) {
  if (!c.resultsVisible) return {};
  const sorted = [...c.entries].filter((e) => e.votes > 0).sort((a, b) => b.votes - a.votes);
  const ranks = {};
  let place = 0, prev = null;
  sorted.forEach((e, i) => { if (e.votes !== prev) { place = i + 1; prev = e.votes; } if (place <= 3) ranks[e.id] = place; });
  return ranks;
}
const MEDAL = { 1: '🥇', 2: '🥈', 3: '🥉' };

// ── home ──
function Home({ data, identity, votes, onForget }) {
  const comps = data.competitions;
  const open = comps.filter(votable);
  const done = open.filter((c) => votes[c.id]).length;
  return (
    <>
      <section className="hero">
        <Hero55 />
        <div className="hero-card">
          <h1>{data.settings.site_title}</h1>
          {data.settings.site_subtitle && <p>{data.settings.site_subtitle}</p>}
        </div>
      </section>

      <div className="container">
        {identity ? (
          <div className="hello">
            <div className="hello-top">
              <span>أهلًا <b>{identity.name}</b> 👋</span>
              <button className="link" onClick={onForget}>لست {identity.name}؟</button>
            </div>
            {open.length > 0 && (
              <>
                <div className="progress"><span style={{ width: (done / open.length) * 100 + '%' }} /></div>
                <div className="hello-sub">
                  {done === open.length ? 'صوّتّ في كل المسابقات 🎉 شكرًا لك!' : `صوّتّ في ${n(done)} من ${n(open.length)} مسابقات`}
                </div>
              </>
            )}
          </div>
        ) : (
          <div className="hello hello-intro">
            <b>كيف تصوّت؟</b>
            <ol>
              <li>اختر مسابقة</li>
              <li>اضغط على الصورة أو الفيديو اللي عجبك</li>
              <li>اضغط «صوّت» واكتب اسمك ورمزك</li>
            </ol>
          </div>
        )}

        <h2 className="section-title">المسابقات</h2>
        {comps.length === 0 && <div className="empty">المسابقات قادمة قريبًا ✨</div>}
        <div className="grid">
          {comps.map((c) => (
            <button key={c.id} className={'comp-card' + (votes[c.id] ? ' is-voted' : '')} onClick={() => go('#c/' + c.id)}>
              <div className="comp-art"><CatArt icon={c.icon} /><Status c={c} mine={votes[c.id]} /></div>
              <div className="comp-body">
                <div className="comp-title">{c.title}</div>
                <div className="comp-meta">{entriesLabel(c.entries.length)}</div>
              </div>
            </button>
          ))}
        </div>
        <footer className="foot"><FlagStripe />عيد اتحاد سعيد 🇦🇪</footer>
      </div>
    </>
  );
}

// ── competition gallery ──
function Gallery({ c, votes }) {
  const mine = votes[c.id];
  const ranks = useMemo(() => rankOf(c), [c]);
  const entries = useMemo(() => (c.resultsVisible
    ? [...c.entries].sort((a, b) => (b.votes || 0) - (a.votes || 0))
    : c.entries), [c]);
  return (
    <>
      <header className="topbar">
        <button className="back" onClick={() => go('#')} aria-label="رجوع">→</button>
        <div className="topbar-title">{c.title}</div>
      </header>
      <div className="container">
        <div className="comp-banner">
          <div className="comp-banner-art"><CatArt icon={c.icon} /></div>
          <div>
            {c.description && <p className="desc">{c.description}</p>}
            <div className="comp-meta">
              {entriesLabel(c.entries.length)}
              {c.status === 'open' && c.closesAt && <> · يغلق {fmtDate(c.closesAt)}</>}
            </div>
            <div style={{ marginTop: 6 }}><Status c={c} mine={mine} /></div>
          </div>
        </div>

        {c.status === 'open' && <GalleryHint c={c} mine={mine} />}
        {votable(c) && c.showResults === 'after_close' && <p className="hint muted">النتائج تظهر بعد انتهاء التصويت 🤫</p>}
        {c.entries.length === 0 && <div className="empty">المشاركات قادمة قريبًا ✨</div>}

        <div className="entries">
          {entries.map((e) => (
            <button key={e.id} className={'entry' + (mine === e.id ? ' is-mine' : '')} onClick={() => go(`#c/${c.id}/e/${e.id}`)}>
              <div className="entry-media">
                <Thumb e={e} c={c} />
                {e.type === 'video' && <span className="play">▶</span>}
                {mine === e.id && <span className="mine-tag">✓ صوتك</span>}
                {ranks[e.id] && <span className="medal">{MEDAL[ranks[e.id]]}</span>}
              </div>
              <div className="entry-name">{e.name}</div>
              {c.resultsVisible && <div className="entry-votes">{n(e.votes)} {e.votes === 1 ? 'صوت' : 'أصوات'}</div>}
            </button>
          ))}
        </div>
      </div>
    </>
  );
}

// One short instruction line for an open competition, depending on what's on the page.
function GalleryHint({ c, mine }) {
  const missing = c.entries.some((x) => !hasMedia(x));
  const video = isVideoComp(c);
  let text = null;
  if (votable(c) && missing) text = video ? 'اضغط على فيديو للتصويت، أو على اسم بدون فيديو لرفعه 👇' : 'اضغط على صورة للتصويت، أو على اسم بدون صورة لرفعها 👇';
  else if (votable(c) && !mine) text = 'اضغط على المشاركة لتكبيرها والتصويت لها 👇';
  else if (missing) text = video ? 'اضغط على اسم المشارك لرفع الفيديو 🎬' : 'اضغط على اسم المشارك لرفع الصورة 📷';
  return text ? <p className="hint">{text}</p> : null;
}

// ── full-screen viewer ──
function Viewer({ c, entryId, votes, identity, onVote, onUpload }) {
  const idx = c.entries.findIndex((e) => e.id === entryId);
  const e = c.entries[idx];
  const touch = useRef(null);
  const mine = votes[c.id];
  if (!e) { go('#c/' + c.id); return null; }

  const step = (d) => {
    const next = c.entries[(idx + d + c.entries.length) % c.entries.length];
    history.replaceState(null, '', `#c/${c.id}/e/${next.id}`);
    window.dispatchEvent(new HashChangeEvent('hashchange'));
  };
  const onTouchStart = (ev) => { touch.current = ev.touches[0].clientX; };
  const onTouchEnd = (ev) => {
    if (touch.current == null || c.entries.length < 2) return;
    const dx = ev.changedTouches[0].clientX - touch.current;
    touch.current = null;
    if (Math.abs(dx) > 50) step(dx > 0 ? 1 : -1);   // RTL: swipe right = next
  };

  const ready = hasMedia(e);
  const locked = c.status !== 'open' || (mine && !c.allowChange && mine !== e.id);
  return (
    <div className="viewer" onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
      <div className="viewer-top">
        <button className="v-btn" onClick={() => inApp ? history.back() : go('#c/' + c.id)} aria-label="إغلاق">✕</button>
        <span className="v-count">{n(idx + 1)} من {n(c.entries.length)}</span>
      </div>
      <div className="viewer-media" key={e.id}>
        {!ready ? <Placeholder name={e.name} big label={soonOne(c)} />
          : e.type === 'video'
            ? <video src={e.src} poster={e.thumb || undefined} controls playsInline preload="metadata" />
            : <img src={e.src} alt={e.name} />}
        {c.entries.length > 1 && <>
          <button className="v-nav v-prev" onClick={() => step(-1)} aria-label="السابق">
            <svg width="18" height="18" viewBox="0 0 18 18"><path d="M6 3l6 6-6 6" stroke="#fff" strokeWidth="2.4" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
          </button>
          <button className="v-nav v-next" onClick={() => step(1)} aria-label="التالي">
            <svg width="18" height="18" viewBox="0 0 18 18"><path d="M12 3l-6 6 6 6" stroke="#fff" strokeWidth="2.4" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
          </button>
        </>}
      </div>
      <div className="viewer-panel">
        <div className="v-name">{e.name}</div>
        {e.caption && <div className="v-caption">{e.caption}</div>}
        {c.resultsVisible && <div className="v-caption">{n(e.votes)} {e.votes === 1 ? 'صوت' : 'أصوات'}</div>}
        {mine === e.id
          ? <div className="v-voted">✓ صوتك لهذه المشاركة</div>
          : !ready ? (c.status === 'open' && (
            <>
              <button className="btn btn-upload" onClick={() => onUpload(c, e)}>{isVideoComp(c) ? '🎬 ارفع الفيديو' : '📷 ارفع الصورة'}</button>
              <div className="v-note">{isVideoComp(c) ? 'التصويت يبدأ بعد رفع الفيديو' : 'التصويت يبدأ بعد رفع الصورة'}</div>
            </>
          ))
          : c.status === 'open' && (
            <button className="btn btn-vote" disabled={locked} onClick={() => onVote(c, e)}>
              {locked ? 'لا يمكن تغيير صوتك' : mine ? 'غيّر صوتي لهذه المشاركة' : 'صوّت لهذه المشاركة 💚'}
            </button>
          )}
        {ready && c.status === 'open' && identity && e.uploader === identity.name && (
          <button className="v-link" onClick={() => onUpload(c, e)}>{isVideoComp(c) ? 'تغيير الفيديو' : 'تغيير الصورة'} (رفعتها أنت)</button>
        )}
      </div>
    </div>
  );
}

// ── vote sheet (asks name + PIN once, then just confirms) ──
function VoteSheet({ family, identity, pick, onClose, onDone }) {
  const [name, setName] = useState(identity?.name || '');
  const [pin, setPin] = useState(identity?.pin || '');
  const [askPin, setAskPin] = useState(!identity);
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);

  const submit = async () => {
    if (!name) return setErr('اختر اسمك من القائمة');
    if (!pin) return setErr('اكتب رمزك السري');
    setBusy(true); setErr('');
    const r = await window.api.vote(name, pin, pick.c.id, pick.e.id);
    setBusy(false);
    if (!r.ok) { setErr(r.error); if (/الرمز|الاسم/.test(r.error || '')) { setAskPin(true); setPin(''); } return; }
    onDone({ name, pin });
  };

  return (
    <div className="sheet-bg" onClick={onClose}>
      <div className="sheet" onClick={(ev) => ev.stopPropagation()}>
        <div className="sheet-grip" />
        <div className="sheet-pick">
          <div className="sheet-thumb"><Thumb e={pick.e} c={pick.c} /></div>
          <div>
            <div className="muted small">{pick.c.title}</div>
            <div className="sheet-name">صوتك لـ «{pick.e.name}»</div>
          </div>
        </div>
        {askPin ? (
          <>
            <label className="lbl">اسمك</label>
            <select value={name} onChange={(ev) => setName(ev.target.value)}>
              <option value="">— اختر اسمك —</option>
              {family.map((f) => <option key={f} value={f}>{f}</option>)}
            </select>
            <label className="lbl">رمزك السري</label>
            <input type="password" inputMode="numeric" autoComplete="off" placeholder="••••" value={pin}
              onChange={(ev) => setPin(ev.target.value)} onKeyDown={(ev) => ev.key === 'Enter' && submit()} />
          </>
        ) : (
          <p className="muted">تصوّت باسم <b>{name}</b> · <button className="link" onClick={() => setAskPin(true)}>تغيير</button></p>
        )}
        <div className="err">{err}</div>
        <button className="btn btn-vote" onClick={submit} disabled={busy}>{busy ? '...لحظة' : 'تأكيد التصويت'}</button>
        <button className="btn btn-ghost" onClick={onClose}>إلغاء</button>
      </div>
    </div>
  );
}

// ── upload sheet: family member adds the photo/video for a participant ──
function UploadSheet({ family, identity, target, onClose, onDone }) {
  const { c, e } = target;
  const video = isVideoComp(c);
  const [name, setName] = useState(identity?.name || '');
  const [pin, setPin] = useState(identity?.pin || '');
  const [askPin, setAskPin] = useState(!identity);
  const [file, setFile] = useState(null);
  const [preview, setPreview] = useState('');
  const [progress, setProgress] = useState(null);
  const [err, setErr] = useState('');
  const fileRef = useRef(null);

  useEffect(() => () => { if (preview) URL.revokeObjectURL(preview); }, [preview]);

  const choose = (ev) => {
    const f = ev.target.files[0];
    if (!f) return;
    const isVid = f.type.startsWith('video/');
    if (video !== isVid) { setErr(video ? 'هذه المسابقة للفيديو فقط' : 'هذه المسابقة للصور فقط'); return; }
    setErr(''); setFile(f); setPreview(URL.createObjectURL(f));
  };

  const submit = async () => {
    if (!name) return setErr('اختر اسمك من القائمة');
    if (!pin) return setErr('اكتب رمزك السري');
    if (!file) return setErr(video ? 'اختر الفيديو أولًا' : 'اختر الصورة أولًا');
    setErr(''); setProgress(0);
    const headers = { 'X-Member-Name': encodeURIComponent(name), 'X-Member-Pin': encodeURIComponent(pin) };
    // Check name/PIN/permission before sending the (possibly large) file.
    let r;
    try {
      const pre = await fetch(`/api/entries/${e.id}/can-upload`, { method: 'POST', headers });
      const d = await pre.json().catch(() => ({}));
      r = pre.ok && d.ok ? { ok: true } : { ok: false, error: d.error || 'حدث خطأ، حاول مرة ثانية' };
    } catch (_) { r = { ok: false, error: 'تحقق من الاتصال بالإنترنت' }; }
    if (r.ok) {
      const fd = new FormData();
      await window.Media.append(fd, file);
      r = await window.Media.send(`/api/entries/${e.id}/media`, fd, { headers, onProgress: (f) => setProgress(f) });
    }
    setProgress(null);
    if (!r.ok) { setErr(r.error); if (/الرمز|الاسم/.test(r.error || '')) { setAskPin(true); setPin(''); } return; }
    onDone({ name, pin });
  };

  const busy = progress != null;
  return (
    <div className="sheet-bg" onClick={busy ? undefined : onClose}>
      <div className="sheet" onClick={(ev) => ev.stopPropagation()}>
        <div className="sheet-grip" />
        <div className="muted small">{c.title}</div>
        <div className="sheet-name">{video ? 'فيديو' : 'صورة'} «{e.name}»</div>

        <input ref={fileRef} type="file" accept={video ? 'video/*' : 'image/*'} hidden onChange={choose} />
        {preview ? (
          <div className="up-preview" onClick={() => !busy && fileRef.current.click()}>
            {video ? <video src={preview} muted playsInline controls /> : <img src={preview} alt="" />}
            {!busy && <span className="up-change">تغيير</span>}
          </div>
        ) : (
          <button className="up-pick" onClick={() => fileRef.current.click()}>
            <span className="up-pick-icon">{video ? '🎬' : '📷'}</span>
            <span>{video ? 'اختر الفيديو من جهازك' : 'اختر الصورة من جهازك'}</span>
          </button>
        )}

        {askPin ? (
          <>
            <label className="lbl">اسمك</label>
            <select value={name} onChange={(ev) => setName(ev.target.value)} disabled={busy}>
              <option value="">— اختر اسمك —</option>
              {family.map((f) => <option key={f} value={f}>{f}</option>)}
            </select>
            <label className="lbl">رمزك السري</label>
            <input type="password" inputMode="numeric" autoComplete="off" placeholder="••••" value={pin} disabled={busy}
              onChange={(ev) => setPin(ev.target.value)} />
          </>
        ) : (
          <p className="muted">ترفع باسم <b>{name}</b> · <button className="link" onClick={() => setAskPin(true)}>تغيير</button></p>
        )}

        {busy && <div className="progress"><span style={{ width: Math.round(progress * 100) + '%' }} /></div>}
        <div className="err">{err}</div>
        <button className="btn btn-upload" onClick={submit} disabled={busy}>
          {busy ? `جارٍ الرفع… ${Math.round(progress * 100)}٪` : video ? 'ارفع الفيديو' : 'ارفع الصورة'}
        </button>
        {!busy && <button className="btn btn-ghost" onClick={onClose}>إلغاء</button>}
      </div>
    </div>
  );
}

// ── app ──
function App() {
  const boot = window.APP_DATA;
  const [data, setData] = useState({ settings: boot.settings, family: boot.family, competitions: boot.competitions });
  const [identity, setIdentity] = useState(boot.identity);
  const [votes, setVotes] = useState(boot.votes || {});
  const [route, setRoute] = useState(parseHash());
  const [pick, setPick] = useState(null);
  const [upload, setUpload] = useState(null);
  const [toast, setToast] = useState('');

  useEffect(() => {
    const on = () => { setRoute(parseHash()); setPick(null); setUpload(null); };   // phone back button also closes any sheet
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);

  useEffect(() => { if (!route.entry) window.scrollTo(0, 0); }, [route.comp]);
  useEffect(() => { document.body.style.overflow = route.entry || pick || upload ? 'hidden' : ''; }, [route.entry, pick, upload]);

  const refresh = useCallback(async (who = identity) => {
    const d = await window.api.data();
    if (d) setData(d);
    if (who) setVotes(await window.api.votes(who.name));
  }, [identity]);

  useEffect(() => {
    const on = () => document.visibilityState === 'visible' && refresh();
    document.addEventListener('visibilitychange', on);
    return () => document.removeEventListener('visibilitychange', on);
  }, [refresh]);

  const done = async (who) => {
    window.api.saveIdentity(who);
    setIdentity(who);
    setVotes((v) => ({ ...v, [pick.c.id]: pick.e.id }));
    setPick(null);
    burstConfetti();
    setToast('وصل صوتك! شكرًا 💚');
    setTimeout(() => setToast(''), 2600);
    refresh(who);
  };

  const uploaded = async (who) => {
    const video = isVideoComp(upload.c);
    window.api.saveIdentity(who);
    setIdentity(who);
    setUpload(null);
    burstConfetti();
    setToast(video ? 'تم رفع الفيديو! شكرًا 💚' : 'تم رفع الصورة! شكرًا 💚');
    setTimeout(() => setToast(''), 2600);
    refresh(who);
  };

  const forget = () => { window.api.saveIdentity(null); setIdentity(null); setVotes({}); };

  const comp = route.comp != null ? data.competitions.find((c) => c.id === route.comp) : null;
  if (route.comp != null && !comp) setTimeout(() => go('#'), 0);

  return (
    <div className="app">
      {comp && <FlagStripe />}
      {comp ? <Gallery c={comp} votes={votes} /> : <Home data={data} identity={identity} votes={votes} onForget={forget} />}
      {comp && route.entry && <Viewer c={comp} entryId={route.entry} votes={votes} identity={identity}
        onVote={(c, e) => setPick({ c, e })} onUpload={(c, e) => setUpload({ c, e })} />}
      {pick && <VoteSheet family={data.family} identity={identity} pick={pick} onClose={() => setPick(null)} onDone={done} />}
      {upload && <UploadSheet family={data.family} identity={identity} target={upload} onClose={() => setUpload(null)} onDone={uploaded} />}
      {toast && <div className="toast">{toast}</div>}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
