/* Inline editing primitives — click-to-edit titles, statuses, priorities, dates */

function InlineTitle({ value, onSave, size = 14.5, weight = 600, done = false }) {
  const [editing, setEditing] = React.useState(false);
  const [v, setV] = React.useState(value);
  React.useEffect(() => setV(value), [value]);
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (editing && ref.current) { ref.current.focus(); ref.current.select(); }
  }, [editing]);

  const commit = () => {
    const trimmed = v.trim();
    if (trimmed && trimmed !== value) onSave?.(trimmed);
    setEditing(false);
  };
  const cancel = () => { setV(value); setEditing(false); };

  if (editing) {
    return (
      <input
        ref={ref}
        value={v}
        onChange={e => setV(e.target.value)}
        onClick={e => e.stopPropagation()}
        onBlur={commit}
        onKeyDown={e => {
          e.stopPropagation();
          if (e.key === 'Enter')  { e.preventDefault(); commit(); }
          if (e.key === 'Escape') { e.preventDefault(); cancel(); }
        }}
        style={{
          fontSize: size, fontWeight: weight,
          letterSpacing: '-0.01em',
          color: 'rgb(var(--ink))',
          padding: '2px 6px',
          margin: '-2px -6px',
          border: '1px solid rgb(var(--accent))',
          background: 'rgb(var(--surface))',
          borderRadius: 6, outline: 'none',
          width: '100%',
          boxShadow: '0 0 0 3px rgb(var(--accent) / 0.15)',
          fontFamily: 'inherit',
        }}
      />
    );
  }
  return (
    <span
      onClick={e => { e.stopPropagation(); setEditing(true); }}
      style={{
        fontSize: size, fontWeight: weight,
        color: done ? 'rgb(var(--muted))' : 'rgb(var(--ink))',
        textDecoration: done ? 'line-through' : 'none',
        letterSpacing: '-0.01em',
        lineHeight: 1.35,
        cursor: 'text',
        padding: '2px 6px',
        margin: '-2px -6px',
        borderRadius: 4,
        transition: 'background-color .12s',
      }}
      onMouseEnter={e => e.currentTarget.style.background = 'rgb(var(--accent-soft) / 0.4)'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
      title="Click to edit"
    >{value}</span>
  );
}

function InlineStatus({ statusId, onChange }) {
  const [open, setOpen] = React.useState(false);
  const s = statusById(statusId); if (!s) return null;
  return (
    <span style={{ position: 'relative' }} onClick={e => e.stopPropagation()}>
      <span onClick={() => setOpen(o => !o)} style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        paddingInline: 8, paddingBlock: 3,
        background: s.colour + '14', color: s.colour,
        fontSize: 11, fontWeight: 600,
        borderRadius: 999,
        cursor: 'pointer', whiteSpace: 'nowrap',
        transition: 'background-color .12s',
      }}
        onMouseEnter={e => e.currentTarget.style.background = s.colour + '24'}
        onMouseLeave={e => e.currentTarget.style.background = s.colour + '14'}
        title="Click to change status"
      >
        <span className="pip" style={{ background: s.colour }} />
        {s.title}
      </span>
      {open && (
        <>
          <span onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 60 }} />
          <div className="shadow-pop fadein" style={{
            position: 'absolute', top: '100%', left: 0, marginTop: 4,
            background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
            minWidth: 160, padding: 4, zIndex: 61,
            borderRadius: 10,
          }}>
            {D.statuses.map(st => (
              <button key={st.id} onClick={() => { onChange?.(st.id); setOpen(false); }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                  padding: '6px 10px', fontSize: 12, fontWeight: 500,
                  color: 'rgb(var(--ink))', textAlign: 'left',
                  borderRadius: 6,
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'rgb(var(--paper-2))'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <span className="pip" style={{ background: st.colour }} />
                {st.title}
                {st.id === statusId && <span style={{ marginLeft: 'auto', color: 'rgb(var(--accent))', fontSize: 11 }}>✓</span>}
              </button>
            ))}
          </div>
        </>
      )}
    </span>
  );
}

function InlinePriority({ priority, onChange }) {
  const [open, setOpen] = React.useState(false);
  const opts = [['urgent','Urgent'],['high','High'],['medium','Medium'],['low','Low']];
  return (
    <span style={{ position: 'relative' }} onClick={e => e.stopPropagation()}>
      <button onClick={() => setOpen(o => !o)}
        style={{
          padding: 4, borderRadius: 6,
          display: 'inline-flex', alignItems: 'center',
          transition: 'background-color .12s',
        }}
        onMouseEnter={e => e.currentTarget.style.background = 'rgb(var(--paper-2))'}
        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
        title="Change priority"
      >
        <PriorityDot p={priority} />
      </button>
      {open && (
        <>
          <span onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 60 }} />
          <div className="shadow-pop fadein" style={{
            position: 'absolute', top: '100%', left: 0, marginTop: 4,
            background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
            minWidth: 130, padding: 4, zIndex: 61, borderRadius: 10,
          }}>
            {opts.map(([k, lbl]) => (
              <button key={k} onClick={() => { onChange?.(k); setOpen(false); }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                  padding: '6px 10px', fontSize: 12,
                  color: 'rgb(var(--ink))', textAlign: 'left',
                  borderRadius: 6, fontWeight: 500,
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'rgb(var(--paper-2))'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <PriorityDot p={k} /> {lbl}
                {k === priority && <span style={{ marginLeft: 'auto', color: 'rgb(var(--accent))', fontSize: 11 }}>✓</span>}
              </button>
            ))}
          </div>
        </>
      )}
    </span>
  );
}

function InlineDue({ iso, onChange }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  return (
    <span style={{ position: 'relative' }} onClick={e => e.stopPropagation()}>
      <button onClick={() => { setOpen(o => !o); setTimeout(() => ref.current?.showPicker?.(), 0); }}
        style={{ padding: 0, borderRadius: 999 }}
        title="Change due date">
        <DueChip iso={iso} />
      </button>
      {open && (
        <>
          <span onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 60 }} />
          <div className="shadow-pop fadein" style={{
            position: 'absolute', top: '100%', left: 0, marginTop: 4,
            background: 'rgb(var(--surface))', border: '1px solid rgb(var(--rule))',
            padding: 10, zIndex: 61, borderRadius: 10, minWidth: 220,
          }}>
            <input ref={ref} type="date" defaultValue={iso || ''}
              onChange={e => { onChange?.(e.target.value); setOpen(false); }}
              style={{ width: '100%', fontSize: 12 }} />
            <div style={{ display: 'flex', gap: 4, marginTop: 8, flexWrap: 'wrap' }}>
              {[
                ['Today',     () => TODAY.toISOString().slice(0,10)],
                ['Tomorrow',  () => { const d = new Date(TODAY); d.setDate(d.getDate()+1); return d.toISOString().slice(0,10); }],
                ['Next Mon',  () => { const d = new Date(TODAY); d.setDate(d.getDate() + ((1 + 7 - d.getDay()) % 7 || 7)); return d.toISOString().slice(0,10); }],
                ['+1 week',   () => { const d = new Date(TODAY); d.setDate(d.getDate()+7); return d.toISOString().slice(0,10); }],
              ].map(([lbl, fn]) => (
                <button key={lbl} onClick={() => { onChange?.(fn()); setOpen(false); }}
                  style={{ fontSize: 11, padding: '3px 9px', background: 'rgb(var(--paper-2))', borderRadius: 999, color: 'rgb(var(--ink-2))', fontWeight: 500 }}>{lbl}</button>
              ))}
              {iso && <button onClick={() => { onChange?.(null); setOpen(false); }}
                style={{ fontSize: 11, padding: '3px 9px', background: 'rgb(var(--brick-soft))', borderRadius: 999, color: 'rgb(var(--brick))', fontWeight: 500 }}>Clear</button>}
            </div>
          </div>
        </>
      )}
    </span>
  );
}

Object.assign(window, { InlineTitle, InlineStatus, InlinePriority, InlineDue });
