// BuddyHint.jsx — namecard that unlocks the buddy's real clues (from static-data) one per week
// All clue data is loaded first; React hides clues whose unlockAt hasn't passed yet.
const HINT_ICONS = ["cap", "pin", "music", "heart", "user", "sparkle"];

function BuddyHint({ go, state, reset }) {
  const me = state.me || {};
  const clues = Array.isArray(me.clues) ? me.clues : [];
  const ig = me.ig || {};
  const herd = state.herd || window.HERDS[0];

  // Ref to the namecard element for html2canvas capture
  const cardRef = React.useRef(null);

  // Share feedback: "copied" toast when the native share sheet isn't available
  const [copied, setCopied] = React.useState(false);

  // Re-evaluate every minute so the page auto-updates when a clue unlocks mid-session
  const [now, setNow] = React.useState(() => new Date());
  React.useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 60_000);
    return () => clearInterval(t);
  }, []);

  // A clue is open when its unlockAt timestamp has passed (or has no timestamp)
  const isOpen = (clue) => !clue.unlockAt || now >= new Date(clue.unlockAt);

  const total = clues.length || 1;
  const unlockedCount = clues.filter(isOpen).length;
  const full = unlockedCount >= total;

  // Next clue to unlock — earliest future unlockAt
  const nextUnlock = clues
    .filter((c) => c.unlockAt && now < new Date(c.unlockAt))
    .map((c) => new Date(c.unlockAt))
    .sort((a, b) => a - b)[0] || null;

  const fmtDate = (date) =>
    date.toLocaleDateString("th-TH", {
      weekday: "long", day: "numeric", month: "long", year: "numeric",
    });

  const fmtShort = (date) =>
    date.toLocaleDateString("th-TH", { day: "numeric", month: "short", year: "numeric" });

  // Days remaining until a future date (ceil so "today" = 0, "tomorrow" = 1)
  const daysUntil = (date) => Math.ceil((date - now) / (1000 * 60 * 60 * 24));

  // nice avatar initial — strip พี่/น้อง prefix
  const cleanName = (ig.displayName || "").replace(/^(พี่|น้อง)\s*/, "");
  const initial = (cleanName || ig.displayName || me.agent || "?").trim().charAt(0) || "?";

  // Text used as title/fallback
  const shareText = full
    ? `${herd.emoji} เจอพี่รหัสของฉันแล้ว — ${ig.displayName || me.agent || "บั๊ดดี้"}` +
      (ig.username ? ` @${ig.username}` : "") + " · Buddy Safari · CSTU 41"
    : `${herd.emoji} กำลังตามหาพี่รหัสในฝูง${herd.name} — ปลดล็อกแล้ว ${unlockedCount}/${total} เบาะแส · Buddy Safari · CSTU 41`;

  // Share as image via html2canvas → navigator.share({files}) → download → copy text
  const share = async () => {
    if (typeof html2canvas !== 'undefined' && cardRef.current) {
      try {
        const canvas = await html2canvas(cardRef.current, {
          useCORS: true,
          scale: 2,
          logging: false,
          backgroundColor: '#FFFCF6',
        });
        const blob = await new Promise((r) => canvas.toBlob(r, 'image/png'));
        const file = new File([blob], 'buddy-safari.png', { type: 'image/png' });

        if (navigator.canShare && navigator.canShare({ files: [file] })) {
          try {
            await navigator.share({ title: 'Buddy Safari · CSTU 41', files: [file] });
            return;
          } catch (e) {
            if (e.name === 'AbortError') return;
            // share({files}) rejected → fall through to download
          }
        }

        // Fallback: download the image
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'buddy-safari.png';
        a.click();
        URL.revokeObjectURL(url);
        return;
      } catch (e) {
        if (e.name === 'AbortError') return;
        // html2canvas failed entirely → fall through to text share
      }
    }

    // Final fallback: text via native share or clipboard copy
    const payload = { title: "Buddy Safari · CSTU 41", text: shareText, url: location.href };
    try {
      if (navigator.share) { await navigator.share(payload); return; }
      await navigator.clipboard.writeText(`${shareText}\n${location.href}`);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (e) { /* user dismissed */ }
  };

  return (
    <div className="min-h-[100dvh] w-full px-5 pt-10 pb-9 flex flex-col font-serif text-safari-mahogany">
      {/* back + logout */}
      <div className="flex items-center justify-between mb-2">
        <button onClick={() => go("select")}
          className="inline-flex items-center gap-1.5 -ml-1 px-2.5 py-1.5 rounded-full
                     text-[13.5px] font-semibold text-safari-brown hover:bg-safari-mahogany/5 transition-colors">
          <Icon name="arrow" className="w-4 h-4 rotate-180" /> กลับ
        </button>
        <LogoutButton onClick={reset} />
      </div>

      <FlowDots step={3} />

      {/* namecard */}
      <div ref={cardRef} className="mt-3.5 rounded-3xl overflow-hidden relative bg-[#FFFCF6] border border-safari-mahogany/10
                      shadow-[0_14px_34px_rgba(59,42,26,0.2)]">
        {/* top band */}
        <div className="px-[18px] py-4 flex items-center gap-3.5 relative"
             style={{ background: `linear-gradient(135deg, ${herd.from}, ${herd.to})` }}>
          <div className="w-[72px] h-[72px] rounded-2xl shrink-0 relative bg-white/90 flex items-center justify-center overflow-hidden">
            {full ? (
              <div className="absolute inset-0 flex items-center justify-center font-serif font-bold text-[34px] leading-none"
                   style={{ color: herd.from, background: `linear-gradient(135deg, ${herd.from}1a, ${herd.from}33)` }}>
                {initial}
              </div>
            ) : (
              <span style={{ color: herd.from }}><Icon name="paw" className="w-10 h-10" /></span>
            )}
            {!full && (
              <div className="absolute bottom-1 right-1 w-5.5 h-5.5 rounded-md bg-safari-mahogany text-safari-grass flex items-center justify-center p-1">
                <Icon name="lock" className="w-3.5 h-3.5" />
              </div>
            )}
          </div>
          <div className="flex-1 min-w-0 text-safari-grass">
            <div className="text-[11px] opacity-85 tracking-widest font-semibold">BUDDY · {herd.en}</div>
            <div className={`font-display mt-1 tracking-wide truncate ${full ? "text-[22px]" : "text-[26px]"}`}>
              {full ? (ig.displayName || me.agent || "บั๊ดดี้") : "? ? ?"}
            </div>
            {full && ig.username ? (
              <a href={ig.profileUrl || `https://instagram.com/${ig.username}`} target="_blank" rel="noopener noreferrer"
                 className="text-[12px] mt-1 opacity-95 underline decoration-white/40 underline-offset-2 inline-block truncate">
                @{ig.username}
              </a>
            ) : (
              <div className="text-[12px] mt-1 opacity-90">{herd.emoji} {herd.name}</div>
            )}
          </div>
          <div className="absolute top-3.5 right-3.5 text-white/60"><Icon name="qr" className="w-6 h-6" /></div>
        </div>

        {/* progress */}
        <div className="px-[18px] pt-3.5 pb-1">
          <div className="flex justify-between gap-2 text-[12.5px] text-safari-brown mb-1.5 whitespace-nowrap">
            <span className="font-semibold">สัปดาห์ที่ {unlockedCount} / {total}</span>
            <span>{unlockedCount} เบาะแสปลดล็อกแล้ว</span>
          </div>
          <div className="h-2 rounded-full bg-safari-mahogany/10 overflow-hidden">
            <div className="h-full bg-safari-green rounded-full transition-all duration-500"
                 style={{ width: `${(unlockedCount / total) * 100}%` }} />
          </div>
        </div>

        {/* hint rows — all clues loaded from static-data; locked by unlockAt timestamp */}
        <div className="px-3.5 pt-2 pb-4 flex flex-col gap-2">
          {clues.map((c, i) => {
            const open = isOpen(c);
            const wk = i + 1;
            const unlockDate = c.unlockAt ? new Date(c.unlockAt) : null;
            return (
              <div key={i} className={[
                "flex items-start gap-3 px-3.5 py-2.5 rounded-2xl border transition-all duration-300",
                open ? "bg-safari-green/15 border-safari-green/30" : "bg-[#f0e9da] border-safari-mahogany/10 opacity-70",
              ].join(" ")}>
                <div className={`w-9 h-9 rounded-xl shrink-0 flex items-center justify-center mt-0.5
                                 ${open ? "bg-safari-green text-safari-grass" : "bg-[#d9ccb4] text-safari-brown"}`}>
                  <Icon name={open ? HINT_ICONS[i % HINT_ICONS.length] : "lock"} className="w-5 h-5" />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-[11.5px] text-safari-brown font-semibold">เบาะแสสัปดาห์ที่ {wk}</div>
                  <div className={`text-[15px] font-semibold mt-px leading-snug break-words
                                   ${open ? "text-safari-mahogany" : "text-transparent [text-shadow:0_0_9px_#8B5E2E] select-none"}`}>
                    {open ? c.text : "ยังไม่ถึงเวลาปลดล็อก"}
                  </div>
                  {!open && unlockDate && (
                    <div className="flex items-center gap-1.5 mt-1.5">
                      <span className="text-[11px] font-semibold text-safari-brown bg-safari-mahogany/8 rounded-full px-2 py-0.5">
                        {fmtShort(unlockDate)}
                      </span>
                      <span className="text-[11px] text-safari-brown/60">
                        อีก {daysUntil(unlockDate)} วัน
                      </span>
                    </div>
                  )}
                </div>
                {!open && <span className="text-safari-brown/60 mt-1"><Icon name="lock" className="w-4 h-4" /></span>}
              </div>
            );
          })}
        </div>
      </div>

      {/* footer */}
      <div className="mt-4">
        {!full ? (
          nextUnlock ? (
            <div className="rounded-2xl px-4 py-3 bg-[#FFFCF6] border border-safari-mahogany/10
                            shadow-sm flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-safari-mahogany/8 flex items-center justify-center shrink-0">
                <Icon name="lock" className="w-5 h-5 text-safari-brown" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-[11px] text-safari-brown/70 font-semibold tracking-wide">เบาะแสถัดไปเปิดใน</div>
                <div className="text-[15px] font-semibold text-safari-mahogany leading-tight">
                  {daysUntil(nextUnlock) === 0 ? "วันนี้!" : `อีก ${daysUntil(nextUnlock)} วัน`}
                </div>
                <div className="text-[11px] text-safari-brown/60 mt-0.5">{fmtDate(nextUnlock)}</div>
              </div>
            </div>
          ) : (
            <p className="text-center text-[12px] text-safari-brown italic">
              เบาะแสใหม่จะเปิดอัตโนมัติทุกสัปดาห์
            </p>
          )
        ) : (
          <>
            <div className="text-center px-3.5 py-3.5 rounded-2xl bg-safari-gold/15 text-safari-brown text-[14.5px] mb-3 leading-snug">
              ปลดล็อกเบาะแสทั้งหมดแล้ว !
            </div>
            <SafariButton color="red" onClick={() => go("select")}>
              กลับสู่หน้าหลัก
            </SafariButton>
          </>
        )}

        {/* share buddy card */}
        <button onClick={share}
          className="mt-3 w-full rounded-2xl px-5 py-3.5 flex items-center justify-center gap-2.5
                     font-serif font-semibold text-[16px] text-safari-brown bg-[#FFFCF6]
                     border-2 border-safari-mahogany/12 hover:border-safari-mahogany/25
                     active:translate-y-px transition-all">
          <Icon name={copied ? "check" : "share"} className="w-5 h-5" />
          {copied ? "คัดลอกแล้ว !" : "แชร์การ์ดบั๊ดดี้"}
        </button>

        <PageFooter />
      </div>
    </div>
  );
}

window.BuddyHint = BuddyHint;
