/* SANAA — Customer-side messaging.
   Strict design rules: paper/ink palette, serif headings, terracotta accents only.
   No new colors, no new icons, no foreign chat-app aesthetics. */

// ───── "Message maker" CTA: opens compose modal from maker profile/PDP ─
function MessageMakerButton({ lang, makerId, makerSlug, makerName, productId, productName }) {
  const { user } = useAuth();
  const [open, setOpen] = React.useState(false);
  const [body, setBody] = React.useState("");
  const [subject, setSubject] = React.useState(productName ? (lang === "en" ? `About ${productName}` : `عن ${productName}`) : "");
  const [status, setStatus] = React.useState("idle"); // idle | sending | done | error
  const [err, setErr] = React.useState("");

  // ESC closes the compose modal; body scroll locked while open.
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const send = async (e) => {
    e.preventDefault();
    if (!body.trim() || !user) return;
    setStatus("sending"); setErr("");

    // Find or create conversation (customer + maker [+ product])
    let convId = null;
    let q = window.sb.from("conversations")
      .select("id")
      .eq("maker_id", makerId)
      .eq("customer_id", user.id);
    if (productId) q = q.eq("product_id", productId);
    const { data: existing } = await q.maybeSingle();
    if (existing) {
      convId = existing.id;
    } else {
      const { data: created, error: cErr } = await window.sb.from("conversations").insert({
        maker_id: makerId,
        customer_id: user.id,
        product_id: productId || null,
        guest_email: user.email,
        guest_name: user.user_metadata?.full_name || user.email.split("@")[0],
        subject: subject || null,
      }).select("id").single();
      if (cErr) {
        console.warn("conversations insert:", cErr.message);
        setErr(lang === "en" ? "We couldn't start that conversation. Please try again." : "تعذّر بدء المحادثة. حاول مرّة أخرى.");
        setStatus("error"); return;
      }
      convId = created.id;
    }

    // Insert the first message
    const { error: mErr } = await window.sb.from("messages").insert({
      conversation_id: convId,
      sender_role: "customer",
      sender_id: user.id,
      body: body.trim(),
    });
    if (mErr) {
      console.warn("messages insert:", mErr.message);
      setErr(lang === "en" ? "We couldn't send your message. Please try again." : "تعذّر إرسال رسالتك. حاول مرّة أخرى.");
      setStatus("error"); return;
    }
    setStatus("done");
    setTimeout(() => { setOpen(false); setStatus("idle"); setBody(""); }, 1800);
  };

  if (!user) {
    return (
      <a href="#/account" className="btn ghost" style={{ display: "inline-flex" }}>
        {lang === "en" ? "Sign in to message" : "سجّل لإرسال رسالة"} →
      </a>
    );
  }

  const inp = { display: "block", width: "100%", marginTop: 6, padding: "11px 14px", border: "1px solid var(--line)", borderRadius: 10, background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 14, outline: 0, boxSizing: "border-box" };
  const lbl = { fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" };

  return (
    <>
      <button onClick={() => setOpen(true)} className="btn ghost" style={{ display: "inline-flex" }}>
        {lang === "en" ? "Message the maker" : "راسل الصانع"} →
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(28,26,21,0.6)", zIndex: 90 }} />
          <div className="modal-card" style={{ position: "fixed", top: "50%", left: "50%", transform: "translate(-50%,-50%)", zIndex: 91, background: "var(--paper)", borderRadius: 18, padding: "32px 32px 28px", boxShadow: "0 30px 80px -20px rgba(28,26,21,0.5)" }}>
            <button onClick={() => setOpen(false)} style={{ position: "absolute", top: 14, right: 18, background: "transparent", border: 0, fontSize: 22, cursor: "pointer", color: "var(--muted)" }}>×</button>
            {status === "done" ? (
              <div style={{ textAlign: "center", padding: "16px 0 8px" }}>
                <Star8 size={28} color="var(--olive)" />
                <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 30, marginTop: 16 }}>{lang === "en" ? "Sent" : "أُرسلت"}</h2>
                <p style={{ marginTop: 8, color: "var(--olive)", fontSize: 13 }}>
                  {lang === "en" ? `${makerName} will reply in your inbox.` : `سيردّ ${makerName} في صندوقك.`}
                </p>
              </div>
            ) : (
              <form onSubmit={send}>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)" }}>
                  {lang === "en" ? "To" : "إلى"}
                </div>
                <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 28, marginTop: 4, marginBottom: 18 }}>{makerName}</h2>
                <div style={{ marginBottom: 14 }}>
                  <label style={lbl}>{lang === "en" ? "Subject" : "الموضوع"}</label>
                  <input value={subject} onChange={e => setSubject(e.target.value)} style={inp} placeholder={lang === "en" ? "About a piece, a workshop, or a custom request…" : "عن قطعة أو ورشة"} />
                </div>
                <div style={{ marginBottom: 14 }}>
                  <label style={lbl}>{lang === "en" ? "Your message" : "رسالتك"}</label>
                  <textarea required value={body} onChange={e => setBody(e.target.value)} rows={5} style={{ ...inp, resize: "vertical" }} placeholder={lang === "en" ? "Hello — I had a question about your work…" : "مرحبًا — لديّ سؤال عن قطعتك…"} />
                </div>
                {err && <div style={{ color: "var(--terracotta)", fontSize: 13, marginBottom: 12 }}>{err}</div>}
                <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                  <button type="submit" disabled={status === "sending" || !body.trim()} className="btn" style={{ opacity: (status === "sending" || !body.trim()) ? 0.6 : 1 }}>
                    {status === "sending" ? (lang === "en" ? "Sending…" : "يرسل…") : (lang === "en" ? "Send" : "إرسال")} →
                  </button>
                  <span style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>
                    {lang === "en" ? "Replies land in your account inbox" : "ستجد الردود في صندوقك"}
                  </span>
                </div>
              </form>
            )}
          </div>
        </>
      )}
    </>
  );
}

// ───── Customer inbox (full page or tab content) ──────────────────────
function CustomerMessages({ lang, user }) {
  const [convs, setConvs] = React.useState(null);
  const [active, setActive] = React.useState(null);
  const [messages, setMessages] = React.useState([]);
  const [reply, setReply] = React.useState("");
  const [sending, setSending] = React.useState(false);
  const [refresh, setRefresh] = React.useState(0);
  const messagesEndRef = React.useRef(null);

  React.useEffect(() => {
    if (!user) return;
    window.sb.from("conversations")
      .select("*, makers(name_en, name_ar, slug, tone, trade_en)")
      .eq("customer_id", user.id)
      .order("last_message_at", { ascending: false })
      .then(({ data }) => setConvs(data || []));
  }, [user?.id, refresh]);

  // Realtime: any change to my conversations refreshes the list
  window.useRealtimeConversations("customer_id", user?.id, () => setRefresh(r => r + 1));

  React.useEffect(() => {
    if (!active) { setMessages([]); return; }
    window.sb.from("messages").select("*").eq("conversation_id", active.id).order("created_at")
      .then(({ data }) => setMessages(data || []));
    if (active.unread_for_customer > 0) {
      window.sb.from("conversations").update({ unread_for_customer: 0 }).eq("id", active.id)
        .then(() => setRefresh(r => r + 1));
    }
  }, [active?.id]);

  // Realtime live append in active conversation
  window.useRealtimeMessages(active?.id, (row) => {
    setMessages(m => m.find(x => x.id === row.id) ? m : [...m, row]);
    if (row.sender_role !== "customer") {
      window.sb.from("conversations").update({ unread_for_customer: 0 }).eq("id", active.id)
        .then(({ error }) => { if (!error) setRefresh(r => r + 1); });
    }
  });

  React.useEffect(() => {
    if (messagesEndRef.current) messagesEndRef.current.scrollIntoView({ behavior: "smooth", block: "end" });
  }, [messages.length]);

  const send = async (e) => {
    e.preventDefault();
    const text = reply.trim();
    if (!text || !active || sending) return;
    setSending(true);
    setReply("");
    const tempId = "_tmp_" + Date.now();
    const optimistic = { id: tempId, conversation_id: active.id, sender_role: "customer", sender_id: user.id, body: text, created_at: new Date().toISOString(), _pending: true };
    setMessages(m => [...m, optimistic]);

    const { data, error } = await window.sb.from("messages").insert({
      conversation_id: active.id,
      sender_role: "customer",
      sender_id: user.id,
      body: text,
    }).select().single();
    setSending(false);
    if (error) {
      setMessages(m => m.map(x => x.id === tempId ? { ...x, _failed: true, _pending: false } : x));
      setReply(text);
      return;
    }
    setMessages(m => {
      const without = m.filter(x => x.id !== tempId && x.id !== data.id);
      return [...without, data];
    });
    setRefresh(r => r + 1);
  };

  // Retry a failed message. Used by tap/keyboard activation on the failed bubble.
  const retry = async (failed) => {
    if (!failed || !active || sending) return;
    setSending(true);
    setMessages(m => m.map(x => x.id === failed.id ? { ...x, _failed: false, _pending: true } : x));
    const { data, error } = await window.sb.from("messages").insert({
      conversation_id: active.id,
      sender_role: "customer",
      sender_id: user.id,
      body: failed.body,
    }).select().single();
    setSending(false);
    if (error) {
      setMessages(m => m.map(x => x.id === failed.id ? { ...x, _failed: true, _pending: false } : x));
      return;
    }
    setMessages(m => {
      const without = m.filter(x => x.id !== failed.id && x.id !== data.id);
      return [...without, data];
    });
    setRefresh(r => r + 1);
  };

  if (convs === null) {
    return <div style={{ padding: "40px 0", color: "var(--muted)", fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase" }}>{lang === "en" ? "Loading…" : "تحميل…"}</div>;
  }

  if (convs.length === 0) {
    return (
      <div style={{ padding: "70px 24px", textAlign: "center", border: "1px solid var(--line-2)", borderRadius: 14, background: "var(--paper)" }}>
        <Star8 size={24} color="var(--gold-soft)" />
        <h3 style={{ marginTop: 18, fontFamily: "var(--ff-display)", fontSize: 28, color: "var(--ink)", letterSpacing: "-0.01em" }}>
          {lang === "en" ? "Your inbox is quiet." : "صندوقك هادئ."}
        </h3>
        <p style={{ marginTop: 10, fontSize: 14, color: "var(--olive)", maxWidth: 380, marginLeft: "auto", marginRight: "auto", lineHeight: 1.6, fontStyle: "italic" }}>
          {lang === "en"
            ? "Open a maker's page or a piece, then tap Message the maker to start a thread."
            : "افتح صفحة صانع أو قطعة، واضغط 'راسل الصانع' لتبدأ محادثة."}
        </p>
        <a href="#/makers" className="btn ghost" style={{ marginTop: 24, display: "inline-flex" }}>
          {lang === "en" ? "Browse makers" : "تصفّح الصنّاع"} →
        </a>
      </div>
    );
  }

  // Mobile flow: when a conversation is open, hide the list and show a back link.
  // (Desktop ignores the data attribute — see styles.css.)
  return (
    <div className="mk-conv-grid" data-thread-open={active ? "true" : "false"} style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 0, border: "1px solid var(--line-2)", borderRadius: 14, overflow: "hidden", minHeight: 520, background: "var(--paper)" }}>
      <div className="mk-conv-list" style={{ borderRight: "1px solid var(--line-2)", overflowY: "auto", maxHeight: 620 }}>
        {convs.map((c, i) => {
          const isActive = active?.id === c.id;
          const isUnread = c.unread_for_customer > 0;
          return (
          <button key={c.id} onClick={() => setActive(c)} style={{
            width: "100%", textAlign: "left", padding: "18px 18px 18px 16px",
            border: 0,
            borderTop: i === 0 ? "none" : "1px solid var(--line-2)",
            borderLeft: isActive ? "3px solid var(--terracotta)" : "3px solid transparent",
            background: isActive ? "var(--paper-2)" : "var(--paper)",
            cursor: "pointer", display: "block",
            transition: "background .15s",
          }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                {isUnread && !isActive && <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--terracotta)", flexShrink: 0 }} />}
                <div style={{ fontFamily: "var(--ff-display)", fontSize: 17, fontWeight: isUnread ? 500 : 400, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  {c.makers?.name_en || (lang === "en" ? "Maker" : "صانع")}
                </div>
              </div>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, color: "var(--muted)", letterSpacing: "0.18em", flexShrink: 0 }}>
                {window.fmtDate(c.last_message_at, lang)}
              </div>
            </div>
            {c.makers?.trade_en && (
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", color: "var(--terracotta)", textTransform: "uppercase", marginTop: 4, marginLeft: isUnread && !isActive ? 14 : 0 }}>{c.makers.trade_en}</div>
            )}
            <div style={{ marginTop: 6, fontSize: 13, color: isUnread ? "var(--ink)" : "var(--muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", marginLeft: isUnread && !isActive ? 14 : 0, fontStyle: c.subject ? "normal" : "italic" }}>
              {c.subject || (lang === "en" ? "Untitled thread" : "بدون موضوع")}
            </div>
          </button>
          );
        })}
      </div>
      <div className="mk-conv-thread" style={{ display: "flex", flexDirection: "column", maxHeight: 620 }}>
        {!active ? (
          <div style={{ flex: 1, display: "grid", placeItems: "center", padding: "40px 20px" }}>
            <div style={{ textAlign: "center", maxWidth: 320 }}>
              <Star8 size={18} color="var(--gold-soft)" />
              <div style={{ marginTop: 14, fontFamily: "var(--ff-display)", fontSize: 22, color: "var(--ink)" }}>
                {lang === "en" ? "Select a thread" : "اختر محادثة"}
              </div>
              <div style={{ marginTop: 6, fontSize: 13, color: "var(--muted)", lineHeight: 1.55 }}>
                {lang === "en" ? "Tap any conversation on the left to read or reply." : "اضغط على محادثة لتقرأ وتردّ."}
              </div>
            </div>
          </div>
        ) : (
          <>
            <div style={{ padding: "16px 22px", borderBottom: "1px solid var(--line-2)", background: "var(--paper-2)" }}>
              <button onClick={() => setActive(null)} className="mk-conv-back" style={{ display: "none", background: "transparent", border: 0, padding: 0, marginBottom: 8, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)", cursor: "pointer" }}>
                ← {lang === "en" ? "All threads" : "كل المحادثات"}
              </button>
              <div style={{ fontFamily: "var(--ff-display)", fontSize: 20, letterSpacing: "-0.01em" }}>{active.subject || (lang === "en" ? "Untitled thread" : "بدون موضوع")}</div>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--muted)", marginTop: 4, textTransform: "uppercase" }}>
                {lang === "en" ? "With" : "مع"} {active.makers?.name_en}{active.makers?.trade_en ? ` · ${active.makers.trade_en}` : ""}
              </div>
            </div>
            <div style={{ flex: 1, overflowY: "auto", padding: "20px 22px", display: "flex", flexDirection: "column", gap: 12 }}>
              {messages.map(m => {
                const isFailed = !!m._failed;
                const bubbleStyle = {
                  maxWidth: "78%",
                  alignSelf: m.sender_role === "customer" ? "flex-end" : "flex-start",
                  padding: "10px 14px", borderRadius: 14,
                  background: m.sender_role === "customer" ? "var(--ink)" : "var(--paper-2)",
                  color: m.sender_role === "customer" ? "var(--paper)" : "var(--ink)",
                  fontSize: 14, lineHeight: 1.45,
                  opacity: m._pending ? 0.55 : 1,
                  border: isFailed ? "1px solid var(--terracotta)" : "none",
                  whiteSpace: "pre-wrap", wordBreak: "break-word",
                  cursor: isFailed ? "pointer" : "default",
                  font: "inherit",
                  textAlign: "inherit",
                };
                const meta = (
                  <div style={{ marginTop: 4, fontFamily: "var(--ff-mono)", fontSize: 8, opacity: 0.6, letterSpacing: "0.18em" }}>
                    {isFailed ? (lang === "en" ? "Not sent — tap to retry" : "لم تُرسل — اضغط للإعادة") :
                     m._pending ? (lang === "en" ? "Sending…" : "يرسل…") :
                     window.fmtDateTime(m.created_at, lang)}
                  </div>
                );
                if (isFailed) {
                  return (
                    <button key={m.id} type="button" onClick={() => retry(m)}
                      aria-label={lang === "en" ? "Message failed — tap to retry" : "فشل الإرسال — اضغط للإعادة"}
                      style={bubbleStyle}>
                      {m.body}
                      {meta}
                    </button>
                  );
                }
                return (
                  <div key={m.id} style={bubbleStyle}>
                    {m.body}
                    {meta}
                  </div>
                );
              })}
              <div ref={messagesEndRef} />
            </div>
            <form onSubmit={send} style={{ padding: "14px 18px", borderTop: "1px solid var(--line-2)", display: "flex", gap: 10 }}>
              <input value={reply} onChange={e => setReply(e.target.value)} placeholder={lang === "en" ? "Reply…" : "ردّ…"} style={{ flex: 1, padding: "10px 14px", border: "1px solid var(--line)", borderRadius: 999, background: "var(--paper)", fontSize: 14, outline: 0 }} />
              <button type="submit" disabled={sending || !reply.trim()} className="btn" style={{ opacity: (sending || !reply.trim()) ? 0.5 : 1 }}>{sending ? "…" : "→"}</button>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MessageMakerButton, CustomerMessages });
