/* ============================================
   TASK DETAIL SIDE PANEL
   ============================================ */

const TaskDetail = ({ task, open, onClose, onUpdate, onDelete, currentUser, allTasks }) => {
  const [tab, setTab] = React.useState('comments');
  const [draftComment, setDraftComment] = React.useState('');
  const [showStatusPop, setShowStatusPop] = React.useState(false);
  const [showAssigneePop, setShowAssigneePop] = React.useState(false);
  const [showPriorityPop, setShowPriorityPop] = React.useState(false);
  const [showProjectPop, setShowProjectPop] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [open, onClose]);

  if (!task) return null;

  const proj = getProject(task.project);
  const assignee = getUser(task.assignee);
  const pic = getUser(task.pic);

  const update = (patch) => onUpdate({ ...task, ...patch });

  // checklist
  const checkDone = (task.checklist || []).filter(c => c.done).length;
  const checkTotal = (task.checklist || []).length;

  const addChecklistItem = (text) => {
    update({ checklist: [...(task.checklist || []), { id: uid('c'), text, done: false }] });
  };
  const toggleChecklistItem = (id) => {
    update({ checklist: task.checklist.map(c => c.id === id ? { ...c, done: !c.done } : c) });
  };
  const removeChecklistItem = (id) => {
    update({ checklist: task.checklist.filter(c => c.id !== id) });
  };

  const addComment = () => {
    const text = draftComment.trim();
    if (!text) return;
    update({
      comments: [
        ...(task.comments || []),
        { id: uid('cm'), author: currentUser.id, text, time: new Date().toISOString().split('T')[0] }
      ]
    });
    setDraftComment('');
  };

  const tabs = [
    { id: 'comments',    label: 'Comments',    count: (task.comments || []).length },
    { id: 'checklist',   label: 'Checklist',   count: checkTotal > 0 ? `${checkDone}/${checkTotal}` : null },
    { id: 'attachments', label: 'Attachments', count: (task.attachments || []).length },
    { id: 'activity',    label: 'Activity',    count: null },
  ];

  return (
    <>
      <div className={`detail-overlay${open ? ' open' : ''}`} onClick={onClose} />
      <div className={`detail-panel${open ? ' open' : ''}`}>
        <div className="detail-head">
          <span style={{ position: 'relative' }}>
            <StatusPill status={task.status} onClick={() => setShowStatusPop(s => !s)} />
            {showStatusPop && (
              <div className="popover" style={{ top: 36, left: 0 }}>
                {STATUSES.map(s => (
                  <button
                    key={s.key}
                    className="pop-item"
                    onClick={() => { update({ status: s.key }); setShowStatusPop(false); }}
                  >
                    <span className="dot" style={{ background: s.color }} />
                    {s.label}
                  </button>
                ))}
              </div>
            )}
          </span>
          {task.recurring && (
            <span className="tag" style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <Icon name="repeat" size={11} /> {task.recurring.label}
            </span>
          )}
          <div className="detail-actions">
            <IconBtn icon="copy" title="Duplicate" />
            <IconBtn icon="link" title="Copy link" />
            <IconBtn icon="trash" title="Delete" onClick={() => { if (confirm('Delete this task?')) onDelete(task.id); }} />
            <IconBtn icon="x" title="Close" onClick={onClose} />
          </div>
        </div>

        <div className="detail-body">
          <textarea
            className="detail-title"
            value={task.name}
            onChange={(e) => update({ name: e.target.value })}
            rows={2}
          />
          <div className="detail-id">{task.id}</div>

          <div className="detail-props">
            <div className="detail-prop-label">Project</div>
            <div className="detail-prop-value">
              <span style={{ position: 'relative' }}>
                <button className="detail-prop-edit" onClick={() => setShowProjectPop(s => !s)}>
                  {proj ? (
                    <>
                      <span style={{ width: 8, height: 8, borderRadius: '50%', background: proj.color }} />
                      {proj.name}
                    </>
                  ) : <span className="empty">No project</span>}
                  <Icon name="chevronDown" size={11} />
                </button>
                {showProjectPop && (
                  <div className="popover" style={{ top: 32, left: 0, maxHeight: 280, overflowY: 'auto' }}>
                    {PROJECTS.map(p => (
                      <button key={p.id} className="pop-item" onClick={() => { update({ project: p.id }); setShowProjectPop(false); }}>
                        <span className="dot" style={{ background: p.color }} />
                        {p.name}
                      </button>
                    ))}
                  </div>
                )}
              </span>
            </div>

            <div className="detail-prop-label">Assignee</div>
            <div className="detail-prop-value">
              <span style={{ position: 'relative' }}>
                <button className="detail-prop-edit" onClick={() => setShowAssigneePop(s => !s)}>
                  {assignee ? (
                    <>
                      <Avatar user={assignee} size="sm" />
                      {assignee.name}
                    </>
                  ) : <span className="empty">Unassigned</span>}
                  <Icon name="chevronDown" size={11} />
                </button>
                {showAssigneePop && (
                  <div className="popover" style={{ top: 32, left: 0, maxHeight: 320, overflowY: 'auto' }}>
                    {USERS.map(u => (
                      <button key={u.id} className="pop-item" onClick={() => { update({ assignee: u.id }); setShowAssigneePop(false); }}>
                        <Avatar user={u} size="sm" />
                        <span>{u.name}</span>
                        <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--text-subtle)' }}>{u.role}</span>
                      </button>
                    ))}
                  </div>
                )}
              </span>
            </div>

            <div className="detail-prop-label">Person in charge</div>
            <div className="detail-prop-value">
              {pic ? (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 8px' }}>
                  <Avatar user={pic} size="sm" />
                  {pic.name}
                </span>
              ) : <span className="detail-prop-edit empty">Unassigned</span>}
            </div>

            <div className="detail-prop-label">Priority</div>
            <div className="detail-prop-value">
              <span style={{ position: 'relative' }}>
                <button className="detail-prop-edit" onClick={() => setShowPriorityPop(s => !s)}>
                  <PriorityBadge priority={task.priority} />
                  <Icon name="chevronDown" size={11} />
                </button>
                {showPriorityPop && (
                  <div className="popover" style={{ top: 32, left: 0 }}>
                    {PRIORITIES.map(p => (
                      <button key={p} className="pop-item" onClick={() => { update({ priority: p }); setShowPriorityPop(false); }}>
                        <PriorityBadge priority={p} />
                      </button>
                    ))}
                  </div>
                )}
              </span>
            </div>

            <div className="detail-prop-label">Work type</div>
            <div className="detail-prop-value">
              <select
                value={task.workType || ''}
                onChange={(e) => update({ workType: e.target.value })}
                className="detail-prop-edit"
                style={{ appearance: 'none', cursor: 'pointer' }}
              >
                <option value="">—</option>
                {WORK_TYPES.map(w => <option key={w} value={w}>{w}</option>)}
              </select>
            </div>

            <div className="detail-prop-label">Start date</div>
            <div className="detail-prop-value">
              <input
                type="date"
                className="detail-prop-edit"
                value={task.startDate || ''}
                onChange={(e) => update({ startDate: e.target.value })}
              />
            </div>

            <div className="detail-prop-label">Due date</div>
            <div className="detail-prop-value">
              <input
                type="date"
                className="detail-prop-edit"
                value={task.dueDate || ''}
                onChange={(e) => update({ dueDate: e.target.value })}
              />
              {task.dueDate && <DuePill date={task.dueDate} status={task.status} />}
            </div>

            <div className="detail-prop-label">Tags</div>
            <div className="detail-prop-value" style={{ gap: 5 }}>
              {(task.tags || []).map(t => <span key={t} className="tag">#{t}</span>)}
              <button className="detail-prop-edit empty" style={{ padding: '2px 8px', fontSize: 12 }}>
                <Icon name="plus" size={11} /> Add tag
              </button>
            </div>
          </div>

          <div className="detail-section">
            <div className="detail-section-title">Description</div>
            <textarea
              className="desc-area"
              placeholder="Add a description… use @ to mention someone"
              value={task.description || ''}
              onChange={(e) => update({ description: e.target.value })}
            />
          </div>

          <div className="tabs">
            {tabs.map(t => (
              <button key={t.id} className={`tab${tab === t.id ? ' active' : ''}`} onClick={() => setTab(t.id)}>
                {t.label}
                {t.count != null && <span className="count">{t.count}</span>}
              </button>
            ))}
          </div>

          {tab === 'checklist' && (
            <div>
              {checkTotal > 0 && (
                <div className="check-progress">
                  <div className="bar-track" style={{ flex: 1, maxWidth: 200 }}>
                    <div className="bar-fill" style={{ width: `${(checkDone/checkTotal)*100}%`, background: 'var(--c-emerald)' }} />
                  </div>
                  <span>{Math.round((checkDone/checkTotal)*100)}% complete · {checkDone}/{checkTotal}</span>
                </div>
              )}
              <div className="checklist">
                {(task.checklist || []).map(c => (
                  <div className={`check-item${c.done ? ' done' : ''}`} key={c.id}>
                    <button
                      className={`list-check${c.done ? ' done' : ''}`}
                      onClick={() => toggleChecklistItem(c.id)}
                    >
                      {c.done && <Icon name="check" size={12} stroke={3} />}
                    </button>
                    <input
                      className="check-text"
                      value={c.text}
                      onChange={(e) => update({ checklist: task.checklist.map(x => x.id === c.id ? { ...x, text: e.target.value } : x) })}
                    />
                    <button className="icon-btn" onClick={() => removeChecklistItem(c.id)} title="Remove">
                      <Icon name="x" size={12} />
                    </button>
                  </div>
                ))}
                <ChecklistAdd onAdd={addChecklistItem} />
              </div>
            </div>
          )}

          {tab === 'comments' && (
            <div>
              {(task.comments || []).length === 0 && (
                <div style={{ color: 'var(--text-subtle)', fontSize: 13, padding: '12px 0' }}>
                  No comments yet. Start a conversation.
                </div>
              )}
              {(task.comments || []).map(c => {
                const author = getUser(c.author);
                return (
                  <div key={c.id} className="comment">
                    <Avatar user={author} size="md" />
                    <div className="comment-body">
                      <div className="comment-head">
                        <span className="comment-author">{author?.short || 'Someone'}</span>
                        <span className="comment-time">{formatDate(c.time)}</span>
                      </div>
                      <div className="comment-text" dangerouslySetInnerHTML={{
                        __html: renderMentions(c.text)
                      }} />
                    </div>
                  </div>
                );
              })}
              <div className="comment-composer">
                <Avatar user={currentUser} size="md" />
                <div className="composer-body">
                  <textarea
                    className="composer-input"
                    placeholder={`Reply to ${(task.comments && task.comments.length) ? 'the team' : 'this task'}… use @ to mention`}
                    value={draftComment}
                    onChange={(e) => setDraftComment(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
                        e.preventDefault(); addComment();
                      }
                    }}
                  />
                  <div className="composer-actions">
                    <IconBtn icon="paperclip" title="Attach" />
                    <IconBtn icon="smile" title="Emoji" />
                    <span style={{ fontSize: 11, color: 'var(--text-subtle)', marginLeft: 8 }}>⌘+Enter to send</span>
                    <span className="spacer" />
                    <Btn kind="primary" icon="send" onClick={addComment}>Comment</Btn>
                  </div>
                </div>
              </div>
            </div>
          )}

          {tab === 'attachments' && (
            <div className="attach-grid">
              {(task.attachments || []).map(a => {
                const iconMap = { figma: 'image', image: 'image', video: 'file', file: 'file' };
                return (
                  <div className="attach-row" key={a.id}>
                    <div className="attach-icon"><Icon name={iconMap[a.type] || 'file'} size={16} /></div>
                    <div className="attach-meta">
                      <div className="attach-name">{a.name}</div>
                      <div className="attach-sub">{a.size}</div>
                    </div>
                    <IconBtn icon="download" title="Download" />
                    <IconBtn icon="x" title="Remove" onClick={() => update({ attachments: task.attachments.filter(x => x.id !== a.id) })} />
                  </div>
                );
              })}
              <button className="attach-add" onClick={() => {
                const name = prompt('Attachment name (e.g. spec.pdf or https://...)');
                if (!name) return;
                const isLink = name.startsWith('http');
                update({ attachments: [...(task.attachments || []), { id: uid('a'), name, size: isLink ? 'External link' : '— KB', type: isLink ? 'link' : 'file' }] });
              }}>
                <Icon name="plus" size={14} />
                Add file or link
              </button>
            </div>
          )}

          {tab === 'activity' && (
            <div className="activity-feed">
              {[
                { user: task.assignee || currentUser.id, text: <>created this task</>, time: task.createdAt },
                ...(task.comments || []).map(c => ({ user: c.author, text: <>added a comment</>, time: c.time })),
                ...(task.checklist || []).filter(c => c.done).map(c => ({ user: task.assignee, text: <>checked off <b>"{c.text}"</b></>, time: task.dueDate })),
              ].filter(a => a.time).sort((a,b) => new Date(b.time) - new Date(a.time)).map((a, i) => {
                const u = getUser(a.user);
                return (
                  <div className="act-item" key={i}>
                    <Avatar user={u} size="sm" />
                    <span className="act-text"><b>{u?.short}</b> {a.text}</span>
                    <span className="act-time">{formatDate(a.time)}</span>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </>
  );
};

const ChecklistAdd = ({ onAdd }) => {
  const [text, setText] = React.useState('');
  return (
    <div className="check-add">
      <Icon name="plus" size={13} />
      <input
        placeholder="Add a checklist item…"
        value={text}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' && text.trim()) { onAdd(text.trim()); setText(''); }
        }}
      />
    </div>
  );
};

function renderMentions(text) {
  if (!text) return '';
  const escaped = text.replace(/[&<>"']/g, ch => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' })[ch]);
  // Replace @u1 etc.
  return escaped.replace(/@u(\d+)/g, (m, id) => {
    const u = getUser('u' + id);
    return u ? `<span class="mention">@${u.short}</span>` : m;
  }).replace(/\n/g, '<br>');
}

Object.assign(window, { TaskDetail });
