// Woodbury Operator — Messages. Registers window.MessagesScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, Button, Avatar, Input, Modal, Select, Textarea } = NS;

  const THREADS = [
    { name: "Efua Asante", avatar: "../../assets/images/av-efua.jpg", preview: "The unit is making a loud grinding noise…", time: "2h", unread: 2, site: "Lashibi Townhouses · House 5" },
    { name: "Kofi Mensah", avatar: "../../assets/images/av-kofi.jpg", preview: "Thank you, I'll sign the renewal today.", time: "5h", unread: 0, site: "Lashibi Townhouses · House 1" },
    { name: "Ama Osei", avatar: "../../assets/images/av-ama.jpg", preview: "Can we schedule the inspection for Friday?", time: "1d", unread: 0, site: "Cantonments City · Apt 5A" },
    { name: "Yaw Boateng", avatar: "../../assets/images/av-yaw.jpg", preview: "Application documents attached.", time: "2d", unread: 0, site: "Mirage · Apartment B3" },
    { name: "Nana Adjei", avatar: "../../assets/images/av-nana.jpg", preview: "Water pressure is back to normal now.", time: "3d", unread: 0, site: "Onehive Tse Addo · Unit 101" },
  ];
  const SEED = {
    "Efua Asante": [
      { me: false, text: "Good morning, the AC in House 5 is making a loud grinding noise and isn't cooling.", time: "09:12" },
      { me: false, text: "It started last night. Could someone come take a look today?", time: "09:12" },
      { me: true, text: "Akwaaba Efua — sorry to hear that. I've notified the HVAC team and marked it urgent.", time: "09:31" },
      { me: false, text: "Thank you so much, that's a relief!", time: "09:40" },
    ],
  };

  function MessagesScreen() {
    const [active, setActive] = React.useState(THREADS[0]);
    const [convos, setConvos] = React.useState(SEED);
    const [draft, setDraft] = React.useState("");
    const [compose, setCompose] = React.useState(false);
    const scrollRef = React.useRef(null);
    const msgs = convos[active.name] || [];

    React.useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [msgs.length, active]);

    const send = () => {
      const text = draft.trim();
      if (!text) return;
      const t = new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
      setConvos((c) => ({ ...c, [active.name]: [...(c[active.name] || []), { me: true, text, time: t }] }));
      setDraft("");
    };

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 20, padding: "36px 40px", maxWidth: 1440, height: "100%" }}>
        <window.WBPageHeader eyebrow="Communication" title="Messages"
          actions={<Button variant="primary" icon="pencil" onClick={() => setCompose(true)}>Compose</Button>} />
        <Card style={{ display: "grid", gridTemplateColumns: "340px 1fr", height: 640, overflow: "hidden" }}>
          <div style={{ borderRight: "1px solid var(--border)", display: "flex", flexDirection: "column" }}>
            <div style={{ padding: 16, borderBottom: "1px solid var(--border)" }}><Input icon="search" placeholder="Search residents..." size="sm" /></div>
            <div style={{ overflowY: "auto" }}>
              {THREADS.map((t) => (
                <div key={t.name} onClick={() => setActive(t)} style={{ display: "flex", gap: 12, padding: 16, borderBottom: "1px solid var(--border)", background: active.name === t.name ? "var(--brand-tint)" : "transparent", cursor: "pointer" }}>
                  <Avatar src={t.avatar} name={t.name} size={44} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", justifyContent: "space-between" }}><span style={{ fontWeight: 700, fontSize: 14, color: "var(--text-heading)" }}>{t.name}</span><span style={{ fontSize: 11, color: "var(--text-muted)" }}>{t.time}</span></div>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, marginTop: 2 }}>
                      <span style={{ fontSize: 13, color: "var(--text-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t.preview}</span>
                      {t.unread > 0 && <span style={{ flexShrink: 0, minWidth: 18, height: 18, borderRadius: 9999, background: "var(--brand)", color: "var(--cream-50)", fontSize: 11, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center", padding: "0 5px" }}>{t.unread}</span>}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div style={{ display: "flex", flexDirection: "column" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 24px", borderBottom: "1px solid var(--border)" }}>
              <Avatar src={active.avatar} name={active.name} size={40} />
              <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{active.name}</div><div style={{ fontSize: 12, color: "var(--success)" }}>{active.site}</div></div>
              <Button variant="ghost" size="sm" icon="user" onClick={() => window.WBToast("Opening " + active.name + "'s profile")}>Profile</Button>
            </div>
            <div ref={scrollRef} style={{ flex: 1, overflowY: "auto", padding: 24, display: "flex", flexDirection: "column", gap: 12, background: "var(--bg-app)" }}>
              {msgs.length === 0 && <div style={{ margin: "auto", color: "var(--text-muted)", fontSize: 14 }}>No messages yet — say hello.</div>}
              {msgs.map((m, i) => (
                <div key={i} style={{ alignSelf: m.me ? "flex-end" : "flex-start", maxWidth: "70%" }}>
                  <div style={{ padding: "10px 14px", borderRadius: 16, borderBottomRightRadius: m.me ? 4 : 16, borderBottomLeftRadius: m.me ? 16 : 4, background: m.me ? "var(--brand)" : "var(--surface)", color: m.me ? "var(--cream-50)" : "var(--text-heading)", fontSize: 14, lineHeight: 1.5, boxShadow: m.me ? "none" : "var(--shadow-xs)" }}>{m.text}</div>
                  <div style={{ fontSize: 10, color: "var(--text-muted)", marginTop: 4, textAlign: m.me ? "right" : "left" }}>{m.time}</div>
                </div>
              ))}
            </div>
            <div style={{ display: "flex", gap: 12, padding: 16, borderTop: "1px solid var(--border)" }}>
              <Input placeholder="Type a message…" value={draft} onChange={(e) => setDraft(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") send(); }} containerStyle={{ flex: 1 }} />
              <Button variant="primary" icon="send" onClick={send}>Send</Button>
            </div>
          </div>
        </Card>

        {/* Compose modal */}
        <Modal open={compose} onClose={() => setCompose(false)} icon="pencil" title="New Message" subtitle="Start a conversation with a resident."
          footer={<React.Fragment><Button variant="secondary" onClick={() => setCompose(false)}>Cancel</Button><Button variant="primary" icon="send" onClick={() => { setCompose(false); window.WBToast("Message sent"); }}>Send</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Select label="To" options={THREADS.map((t) => t.name)} />
            <Input label="Subject" placeholder="e.g. Scheduled inspection" />
            <Textarea label="Message" placeholder="Write your message…" />
          </div>
        </Modal>
      </div>
    );
  }
  window.MessagesScreen = MessagesScreen;
})();
