/* ============================================================
   MUIY — In Memory  (src/tribute.jsx → TributeSheet)
   ------------------------------------------------------------
   A solemn, still full-screen memorial:
     · a fixed dedication to Muiz ("Mui")
     · a community remembrance wall — approved entries are shared to
       everyone; a user's own entry shows immediately with a
       "Pending review" badge until an admin approves it.

   Data:
     · shared wall  → window.TCTrib (src/tributes.js)  [approved rows]
     · the user's own remembrances are also mirrored into their
       document (store.data.tributes) so they persist offline and
       appear right away.
   Styles: assets/tribute.css. Registered as the `tribute` modal in
   shell.jsx; opened from About (me.jsx).
   ============================================================ */

/* a single small candle flame — simple teardrop, gently flickering */
function MemFlame() {
  return (
    <span className="mem-flame" aria-hidden="true">
      <svg width="18" height="26" viewBox="0 0 18 26">
        <ellipse cx="9" cy="23" rx="4.4" ry="1.6" fill="rgba(244,216,160,.18)" />
        <g className="fl">
          <path d="M9 2 C 13.5 7 14.5 11 12.8 14.4 C 11.8 16.4 10.6 17.4 9 17.4 C 7 17.4 5.2 16 4.6 13.8 C 4 11.6 5 8 9 2 Z" fill="#F4D8A0" />
          <path d="M9 7 C 11 9.5 11.4 11.8 10.4 13.6 C 9.8 14.7 9.4 15.2 9 15.2 C 8 15.2 7.2 14.2 7 12.8 C 6.8 11.3 7.4 9.6 9 7 Z" fill="#FBF0D6" />
        </g>
      </svg>
    </span>
  );
}

function MemStars() {
  const stars = React.useMemo(() => {
    let s = 20240630;
    const rnd = () => { s = (s * 1103515245 + 12345) & 0x7fffffff; return s / 0x7fffffff; };
    return Array.from({ length: 42 }, () => ({
      x: rnd() * 100, y: rnd() * 62, r: 0.6 + rnd() * 1.5,
      d: (rnd() * 6).toFixed(2), o: 0.2 + rnd() * 0.4,
    }));
  }, []);
  return (
    <div className="mem-stars" aria-hidden="true">
      {stars.map((st, i) => (
        <span key={i} className="mem-star" style={{
          left: st.x + '%', top: st.y + '%', width: st.r * 2, height: st.r * 2,
          opacity: st.o, animationDelay: st.d + 's',
        }} />
      ))}
    </div>
  );
}

function MemCard({ t }) {
  const pending = t.status === 'pending';
  const priv = t.status === 'private';
  return (
    <div className="mem-card">
      <MemFlame />
      <div className="mem-card-b">
        <div className="mem-card-n">{t.name}</div>
        {t.relationship && <div className="mem-card-r">{t.relationship}</div>}
        {t.note && <div className="mem-card-note">{t.note}</div>}
        {t.from && <div className="mem-card-from">— {t.from}</div>}
      </div>
      {pending && <span className="mem-badge">Pending review</span>}
      {priv && <span className="mem-badge">On this device</span>}
    </div>
  );
}

function MemAddForm({ onSubmit, onCancel, shared }) {
  const [name, setName] = React.useState('');
  const [rel, setRel] = React.useState('');
  const [note, setNote] = React.useState('');
  const [from, setFrom] = React.useState('');
  const canSave = name.trim().length > 0;
  return (
    <div className="mem-form">
      <div>
        <label className="lab">Their name</label>
        <input className="mem-in" value={name} maxLength={80} autoFocus
          onChange={(e) => setName(e.target.value)} placeholder="Name" />
      </div>
      <div>
        <label className="lab">Who they were <span style={{ opacity: .6, fontWeight: 700 }}>(optional)</span></label>
        <input className="mem-in" value={rel} maxLength={60}
          onChange={(e) => setRel(e.target.value)} placeholder="friend · brother · daughter …" />
      </div>
      <div>
        <label className="lab">A few words <span style={{ opacity: .6, fontWeight: 700 }}>(optional)</span></label>
        <textarea className="mem-ta" rows={3} value={note} maxLength={600}
          onChange={(e) => setNote(e.target.value)} placeholder="A memory, or what they meant to you…" />
      </div>
      <div>
        <label className="lab">From <span style={{ opacity: .6, fontWeight: 700 }}>(optional)</span></label>
        <input className="mem-in" value={from} maxLength={80}
          onChange={(e) => setFrom(e.target.value)} placeholder="Your name" />
      </div>
      <div className="mem-form-row">
        <button className="mem-btn mem-btn-ghost" onClick={onCancel}>Cancel</button>
        <button className="mem-btn mem-btn-primary" disabled={!canSave}
          style={{ opacity: canSave ? 1 : 0.5 }}
          onClick={() => canSave && onSubmit({ name: name.trim(), relationship: rel.trim(), note: note.trim(), from: from.trim() })}>
          Add to the wall
        </button>
      </div>
      <div className="mem-hint">
        {shared
          ? 'Shared with the whole community. To keep this a gentle place, entries appear for everyone once a moderator approves them.'
          : 'Saved on this device. When you sign in and sync is enabled, you can share remembrances with the community.'}
      </div>
    </div>
  );
}

function TributeSheet({ store, close }) {
  const shared = !!(window.TCTrib && window.TCTrib.isConfigured());
  const local = (store.data && store.data.tributes) || [];
  const [remote, setRemote] = React.useState([]);
  const [adding, setAdding] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    let live = true;
    if (window.TCTrib) {
      window.TCTrib.listApproved().then((rows) => { if (live) setRemote(rows || []); }).catch(() => {});
    }
    const onKey = (e) => { if (e.key === 'Escape') close(); };
    window.addEventListener('keydown', onKey);
    return () => { live = false; window.removeEventListener('keydown', onKey); };
  }, []);

  // one wall: shared/approved entries from the community, then this
  // user's own (not-yet-approved) remembrances kept on their device.
  const wall = [...remote, ...local];

  const submit = (payload) => {
    const entry = {
      id: (window.TC && window.TC.uid && window.TC.uid()) || String(Date.now()),
      name: payload.name, relationship: payload.relationship || '', note: payload.note || '',
      from: payload.from || '', createdAt: new Date().toISOString(),
      status: shared ? 'pending' : 'private',
    };
    store.mutate((d) => { d.tributes = d.tributes || []; d.tributes.unshift(entry); });
    if (window.TCTrib) { try { window.TCTrib.submit(payload); } catch (e) {} }
    setAdding(false);
    store.showToast(shared ? 'Added — it will appear once approved' : 'Added to the wall', '🕯️');
    setTimeout(() => { const el = scrollRef.current; if (el) el.scrollTo({ top: 0, behavior: 'smooth' }); }, 60);
  };

  const Pearl = window.Pearl;
  const Icon = window.Icon;

  return (
    <div className="mem-overlay" role="dialog" aria-label="In memory" data-screen-label="In Memory">
      <MemStars />
      <div className="mem-top">
        <button className="mem-back" onClick={close} aria-label="Close">
          {Icon ? <Icon name="chevL" size={22} color="#EDE7F5" /> : '←'}
        </button>
        <div className="mem-eyebrow">In Memory</div>
      </div>

      <div className="mem-scroll" ref={scrollRef}>
        {/* ---- collective dedication: everyone we've lost ---- */}
        <div className="mem-lede">
          <div className="mem-lede-t">For the friends we've lost</div>
          <div className="mem-lede-s">This space holds every friend our thalassaemia family has had to say goodbye to — the ones who walked this road beside us, and are carried with us still.</div>
        </div>

        <div className="mem-rule" />

        {/* ---- Muiz: the friend MUIY is named for ---- */}
        <div className="mem-hero">
          <div className="mem-kicker">The friend MUIY is named for</div>
          <div className="mem-pearl">{Pearl ? <Pearl size={104} /> : null}</div>
          <div className="mem-name">In loving memory of Muiz&nbsp;(“Mui”)</div>
          <div className="mem-role">a dear friend, brother, and tireless advocate for the thalassaemia community.</div>
        </div>

        <div className="mem-prose">
          <p>Mui dedicated his life to supporting people living with thalassaemia in the Maldives, serving our community with compassion, courage, and unwavering commitment. Whether helping patients, supporting families, or advocating for better care and services, he always stood for those who needed a voice.</p>
          <p>More than a leader, Mui was a source of strength, hope, and kindness to countless people. His impact reaches far beyond the roles he held and lives on in the community he helped build and the lives he touched.</p>
        </div>

        <div className="mem-dua">
          <p>May Allah forgive all our departed friends, accept every good deed they left behind as a source of ongoing reward, fill their graves with light, mercy, and peace, expand them into gardens from the gardens of Paradise, and grant them the highest ranks in Jannatul Firdaus. May He reunite us with them in His eternal mercy and make their memories a source of inspiration and goodness for those they left behind. Ameen.</p>
        </div>

        <div className="mem-epitaph">Your voice may be silent, but your legacy lives on.</div>

        <div className="mem-rule" />

        {/* ---- the remembrance wall ---- */}
        <div className="mem-sec-h">
          <div className="t">The remembrance wall</div>
          <div className="s">For the thal friends we've lost, and carry with us. Light a candle for someone you're remembering.</div>
        </div>

        <div className="mem-wall">
          {wall.length === 0 && (
            <div className="mem-empty">No names yet.<br />Be the first to remember someone here.</div>
          )}
          {wall.map((t) => <MemCard key={t.id} t={t} />)}
        </div>

        {adding
          ? <MemAddForm onSubmit={submit} onCancel={() => setAdding(false)} shared={shared} />
          : (
            <button className="mem-add" onClick={() => setAdding(true)}>
              {Icon ? <Icon name="plus" size={18} color="#F4D8A0" /> : '+'} Add a name
            </button>
          )}

        <div className="mem-foot">
          <div className="a">Dedicated to our thal friends who left us too soon.<br />Forever part of our story.</div>
          <div className="b">Made with ♥ in 🇲🇻 for ThalFrndz</div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TributeSheet, MemFlame, MemCard, MemAddForm });
