/* ============================================================
   BrotherVader — Daily Log wall.
   Daily photo/update posts with a non-calendar day selector
   (a row of date pills). Anyone can leave an anonymous comment;
   each comment is saved and pings the owner on Telegram.
   ============================================================ */

function fmtDay(date) {
  const [y, m, d] = date.split("-").map(Number);
  const MON = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  return { mon: MON[m - 1], d, y, long: `${MON[m - 1]} ${d}, ${y}` };
}

function DailyLog({ posts, admin, onAddPost, onSavePost, onDeletePost, onComment }) {
  const [editing, setEditing] = useState(null); // post | {new:true}
  const dates = [...new Set((posts || []).map((p) => p.date))].sort().reverse();
  const [day, setDay] = useState(null);
  const activeDay = day || dates[0] || null;
  const dayPosts = (posts || []).filter((p) => p.date === activeDay);

  return (
    <section id="daily" className="section">
      <div className="container">
        <Reveal className="section-head">
          <div>
            <div className="section-index">07 — THE DAILY</div>
            <h2 className="section-title">Daily<br/>Log</h2>
          </div>
          <div style={{ maxWidth: 340 }}>
            <p className="muted" style={{ margin: 0 }}>Photos, updates and thoughts from the grind. Pick a day to read it — and leave a comment. <b style={{ color: "var(--chalk)" }}>It’s anonymous.</b></p>
            {admin && <button className="btn btn-primary" style={{ marginTop: 16 }} onClick={() => setEditing({ new: true })}><Icons.Plus size={15}/> New post</button>}
          </div>
        </Reveal>

        {dates.length === 0 ? (
          <Reveal className="wall-empty card">
            <Icons.Camera size={26} />
            <p className="muted">No daily posts yet.{admin ? " Add your first update." : ""}</p>
          </Reveal>
        ) : (
          <>
            <Reveal className="daily-days">
              {dates.map((dt) => {
                const f = fmtDay(dt);
                const n = (posts || []).filter((p) => p.date === dt).length;
                return (
                  <button key={dt} className={"daily-pill" + (dt === activeDay ? " on" : "")} onClick={() => setDay(dt)}>
                    <span className="daily-pill-mon">{f.mon}</span>
                    <span className="daily-pill-d display tnum">{f.d}</span>
                    <span className="daily-pill-n dim">{n} post{n > 1 ? "s" : ""}</span>
                  </button>
                );
              })}
            </Reveal>

            <div className="daily-feed">
              {dayPosts.map((p) => (
                <PostCard key={p.id} post={p} admin={admin}
                  onEdit={() => setEditing(p)} onDelete={() => onDeletePost(p.id)} onComment={onComment} />
              ))}
            </div>
          </>
        )}
      </div>

      {editing && (
        <PostEditor post={editing.new ? null : editing} onClose={() => setEditing(null)}
          onSave={(p) => { editing.new ? onAddPost(p) : onSavePost(p); setEditing(null); }} />
      )}
    </section>
  );
}

function PostCard({ post, admin, onEdit, onDelete, onComment }) {
  const [comments, setComments] = useState(post.comments || []);
  const [text, setText] = useState("");
  const [name, setName] = useState("");
  const [busy, setBusy] = useState(false);
  const [lightbox, setLightbox] = useState(null);
  const f = fmtDay(post.date);

  async function submit(e) {
    e.preventDefault();
    const body = text.trim();
    if (!body) return;
    setBusy(true);
    try {
      const c = await onComment("post:" + post.id, body, name.trim());
      setComments((cs) => [...cs, c]);
      setText("");
    } catch (ex) { alert(ex.message || "Could not post comment."); }
    finally { setBusy(false); }
  }

  return (
    <Reveal className="card post-card">
      <div className="post-head">
        <div>
          <span className="tag tag-gym">{f.long}</span>
          {post.title && <h3 className="display post-title">{post.title}</h3>}
        </div>
        {admin && (
          <div className="post-actions">
            <button className="pen pen-sm" onClick={onEdit} aria-label="Edit post"><Icons.Pen /></button>
            <button className="pen pen-sm" onClick={onDelete} aria-label="Delete post"><Icons.Trash /></button>
          </div>
        )}
      </div>

      {post.images && post.images.length > 0 && (
        <div className={"post-imgs n" + Math.min(post.images.length, 3)}>
          {post.images.map((src, i) => (
            <button key={i} className="post-img" onClick={() => setLightbox(src)}>
              <img src={src} alt={post.title || "post"} />
            </button>
          ))}
        </div>
      )}

      {post.body && <p className="post-body">{post.body}</p>}

      <div className="post-comments">
        <div className="post-comments-head eyebrow">{comments.length} comment{comments.length === 1 ? "" : "s"}</div>
        <ul className="post-comment-list">
          {comments.map((c) => (
            <li key={c.id} className="post-comment">
              <span className="post-comment-name head">{c.name || "Anonymous"}</span>
              <span className="post-comment-text">{c.text}</span>
            </li>
          ))}
        </ul>
        <form className="post-comment-form" onSubmit={submit}>
          <p className="post-comment-encourage dim">You can comment here and it will be saved. Your comment is anonymous.</p>
          <div className="post-comment-inputs">
            <input className="input post-comment-name-input" value={name} onChange={(e) => setName(e.target.value)} placeholder="Name (optional)" maxLength={40} />
            <input className="input post-comment-text-input" value={text} onChange={(e) => setText(e.target.value)} placeholder="Leave a comment…" maxLength={1000} />
            <button className="btn btn-primary" type="submit" disabled={busy || !text.trim()}><Icons.Send size={15}/></button>
          </div>
        </form>
      </div>

      {lightbox && (
        <div className="post-lightbox" onClick={() => setLightbox(null)}>
          <img src={lightbox} alt="" />
          <button className="pen post-lightbox-close" onClick={() => setLightbox(null)}><Icons.Close /></button>
        </div>
      )}
    </Reveal>
  );
}

function PostEditor({ post, onClose, onSave }) {
  const isNew = !post;
  const todayISO = new Date().toISOString().slice(0, 10);
  const [date, setDate] = useState(post ? post.date : todayISO);
  const [title, setTitle] = useState(post ? post.title : "");
  const [body, setBody] = useState(post ? post.body : "");
  const [images, setImages] = useState(post ? (post.images || []) : []);
  const [imageIds, setImageIds] = useState(post ? (post.imageIds || []) : []);
  const [busy, setBusy] = useState(false);

  async function upload() {
    const picked = await pickImageFile();
    if (!picked) return;
    setBusy(true);
    try {
      const r = await API.upload(picked.dataUrl, { target: "post" });
      setImages((im) => [...im, r.url]);
      setImageIds((ids) => [...ids, r.id]);
    } catch (ex) { alert(ex.message || "Upload failed"); }
    finally { setBusy(false); }
  }
  function removeImg(i) { setImages(images.filter((_, idx) => idx !== i)); setImageIds(imageIds.filter((_, idx) => idx !== i)); }

  return (
    <Modal title={isNew ? "New daily post" : "Edit post"} onClose={onClose} maxWidth={620}
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={() => onSave({ ...(post || { id: "post-" + Date.now() }), date, title, body, imageIds })}>
          <Icons.Check size={15}/> {isNew ? "Post" : "Save"}</button>
      </>}>
      <div className="field"><label>Date</label><input className="input tnum" type="date" value={date} onChange={(e) => setDate(e.target.value)} /></div>
      <div className="field"><label>Title</label><input className="input" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Heavy pull day" /></div>
      <div className="field"><label>Update</label><textarea className="textarea" style={{ minHeight: 120 }} value={body} onChange={(e) => setBody(e.target.value)} placeholder="What happened today?" /></div>
      <div className="field" style={{ marginBottom: 0 }}>
        <label>Photos</label>
        {images.length > 0 && (
          <div className="post-editor-imgs">
            {images.map((src, i) => (
              <span key={i} className="post-editor-img">
                <img src={src} alt="" />
                <button className="pen pen-sm" onClick={() => removeImg(i)} aria-label="Remove"><Icons.Close size={12}/></button>
              </span>
            ))}
          </div>
        )}
        <button type="button" className="btn" style={{ marginTop: 10 }} onClick={upload} disabled={busy}>
          <Icons.Camera size={15}/> {busy ? "Uploading…" : "Add photo"}
        </button>
      </div>
    </Modal>
  );
}

Object.assign(window, { DailyLog });
