// ForwardQueue — capture items for next week before they slip.
// ADHD-friendly open-loop parking lot tied to the weekly block rhythm.
// On Sunday: shows "Promote to this week" button on each item.
// Items can be tagged to a block so MC knows where they'll land.

const FQ_BLOCKS = [
  { id: 'ceo',      label: 'Mon · CEO Hour',        accent: '#6366f1' },
  { id: 'delivery', label: 'Tue–Thu · Delivery',    accent: '#059669' },
  { id: 'outreach', label: 'Fri · Outreach + Sales', accent: '#d97706' },
  { id: 'other',    label: 'General / No block',    accent: '#94a3b8' },
];

function blockMeta(id) {
  return FQ_BLOCKS.find((b) => b.id === id) || FQ_BLOCKS[3];
}

function ForwardQueue() {
  const { state, addNextWeekItem, deleteNextWeekItem, promoteNextWeekItem, updateNextWeekBlock } = useStore();
  const [draft, setDraft] = React.useState('');
  const [draftBlock, setDraftBlock] = React.useState('other');
  const [adding, setAdding] = React.useState(false);
  const inputRef = React.useRef(null);

  const isSunday = new Date().getDay() === 0;
  const items = state.nextWeek || [];

  const submit = (e) => {
    e?.preventDefault();
    const t = draft.trim();
    if (!t) { setAdding(false); return; }
    addNextWeekItem(t, draftBlock);
    setDraft('');
    setDraftBlock('other');
    setAdding(false);
  };

  const startAdding = () => {
    setAdding(true);
    setTimeout(() => inputRef.current?.focus(), 50);
  };

  const cardStyle = {
    background: 'var(--surface)',
    border: '1px solid var(--border)',
    borderRadius: 12,
    padding: '16px 20px',
    display: 'flex',
    flexDirection: 'column',
    gap: 12,
  };

  const headStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 8,
  };

  const titleStyle = {
    fontFamily: 'var(--font-display)',
    fontWeight: 700,
    fontSize: 15,
    color: 'var(--fg)',
    margin: 0,
  };

  const subStyle = {
    fontFamily: 'var(--font-mono)',
    fontSize: 11,
    color: 'var(--fg-muted)',
    marginTop: 2,
  };

  const addBtnStyle = {
    display: 'flex',
    alignItems: 'center',
    gap: 6,
    padding: '5px 12px',
    borderRadius: 8,
    border: '1px solid var(--border)',
    background: 'transparent',
    color: 'var(--fg-muted)',
    fontFamily: 'var(--font-mono)',
    fontSize: 12,
    cursor: 'pointer',
    flexShrink: 0,
  };

  const emptyStyle = {
    textAlign: 'center',
    padding: '18px 0',
    color: 'var(--fg-muted)',
    fontFamily: 'var(--font-mono)',
    fontSize: 12,
    lineHeight: 1.7,
  };

  return (
    <div style={cardStyle}>
      {/* Header */}
      <div style={headStyle}>
        <div>
          <h2 style={titleStyle}>Next week</h2>
          <div style={subStyle}>
            {isSunday
              ? '📋 Sunday planning — promote items to this week'
              : 'Park open loops here — no decision needed yet'}
          </div>
        </div>
        <button style={addBtnStyle} onClick={startAdding}>
          <Icons.Plus size={13}/> Capture
        </button>
      </div>

      {/* Inline capture form */}
      {adding && (
        <form onSubmit={submit}
              style={{ display: 'flex', flexDirection: 'column', gap: 8,
                       padding: '12px 14px', background: 'var(--bg-elev)',
                       borderRadius: 10, border: '1px solid var(--border)' }}>
          <input
            ref={inputRef}
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Escape') { setAdding(false); setDraft(''); } }}
            placeholder="What do you need to do next week?"
            style={{
              fontFamily: 'var(--font-display)', fontWeight: 600,
              fontSize: 14, padding: '8px 10px',
              border: '1px solid var(--border)', borderRadius: 8,
              background: 'var(--surface)', color: 'var(--fg)',
              outline: 'none', width: '100%', boxSizing: 'border-box',
            }}
          />
          {/* Block selector */}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {FQ_BLOCKS.map((b) => (
              <button
                key={b.id}
                type="button"
                onClick={() => setDraftBlock(b.id)}
                style={{
                  padding: '3px 10px', borderRadius: 20, border: 'none',
                  cursor: 'pointer', fontFamily: 'var(--font-mono)', fontSize: 11,
                  fontWeight: 600,
                  background: draftBlock === b.id ? b.accent : 'var(--bg-elev)',
                  color: draftBlock === b.id ? '#fff' : 'var(--fg-muted)',
                  outline: draftBlock === b.id ? `2px solid ${b.accent}44` : 'none',
                  transition: 'all .12s',
                }}
              >
                {b.label}
              </button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button
              type="button"
              onClick={() => { setAdding(false); setDraft(''); }}
              style={{
                padding: '5px 14px', borderRadius: 8, border: '1px solid var(--border)',
                background: 'transparent', color: 'var(--fg-muted)',
                fontFamily: 'var(--font-mono)', fontSize: 12, cursor: 'pointer',
              }}
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={!draft.trim()}
              style={{
                padding: '5px 14px', borderRadius: 8, border: 'none',
                background: 'var(--accent)', color: '#fff',
                fontFamily: 'var(--font-mono)', fontSize: 12,
                cursor: draft.trim() ? 'pointer' : 'default',
                opacity: draft.trim() ? 1 : 0.5,
              }}
            >
              Park it
            </button>
          </div>
        </form>
      )}

      {/* Item list */}
      {items.length === 0 && !adding ? (
        <div style={emptyStyle}>
          Nothing parked yet.<br/>
          <span style={{ opacity: 0.6 }}>Capture anything your brain wants to hold on to.</span>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {items.map((item) => {
            const bm = blockMeta(item.block || 'other');
            return (
              <FQItem
                key={item.id}
                item={item}
                bm={bm}
                isSunday={isSunday}
                onDelete={() => deleteNextWeekItem(item.id)}
                onPromote={() => promoteNextWeekItem(item.id)}
                onBlockChange={(block) => updateNextWeekBlock(item.id, block)}
              />
            );
          })}
        </div>
      )}

      {/* Sunday summary hint */}
      {isSunday && items.length > 0 && (
        <div style={{
          padding: '8px 12px', borderRadius: 8,
          background: '#2563eb18', color: '#2563eb',
          fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600,
        }}>
          🗓 Review each item — promote what fits this week. Leave the rest parked.
        </div>
      )}
    </div>
  );
}

function FQItem({ item, bm, isSunday, onDelete, onPromote, onBlockChange }) {
  const [blockOpen, setBlockOpen] = React.useState(false);

  const rowStyle = {
    display: 'flex',
    alignItems: 'flex-start',
    gap: 10,
    padding: '9px 12px',
    borderRadius: 10,
    background: 'var(--bg-elev)',
    border: '1px solid var(--border)',
    position: 'relative',
  };

  const chipStyle = {
    flexShrink: 0,
    padding: '2px 8px',
    borderRadius: 20,
    fontFamily: 'var(--font-mono)',
    fontSize: 10,
    fontWeight: 700,
    background: bm.accent + '22',
    color: bm.accent,
    cursor: 'pointer',
    border: 'none',
    whiteSpace: 'nowrap',
    marginTop: 1,
  };

  const textStyle = {
    flex: 1,
    fontFamily: 'var(--font-display)',
    fontWeight: 600,
    fontSize: 13,
    color: 'var(--fg)',
    lineHeight: 1.5,
  };

  const actStyle = {
    display: 'flex',
    alignItems: 'center',
    gap: 4,
    flexShrink: 0,
  };

  const iconBtnStyle = (danger) => ({
    background: 'transparent',
    border: 'none',
    cursor: 'pointer',
    color: danger ? 'var(--red, #e05)' : 'var(--fg-muted)',
    padding: '2px 4px',
    borderRadius: 6,
    fontSize: 12,
    opacity: 0.7,
  });

  return (
    <div style={rowStyle}>
      {/* Block tag chip */}
      <div style={{ position: 'relative' }}>
        <button style={chipStyle} onClick={() => setBlockOpen((o) => !o)} title="Change block">
          {bm.label}
        </button>
        {blockOpen && (
          <div style={{
            position: 'absolute', top: '100%', left: 0, zIndex: 50,
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 10, padding: 6, marginTop: 4,
            display: 'flex', flexDirection: 'column', gap: 4,
            boxShadow: '0 4px 20px rgba(0,0,0,0.12)',
            minWidth: 180,
          }} onMouseLeave={() => setBlockOpen(false)}>
            {FQ_BLOCKS.map((b) => (
              <button key={b.id}
                onClick={() => { onBlockChange(b.id); setBlockOpen(false); }}
                style={{
                  background: item.block === b.id ? b.accent + '18' : 'transparent',
                  border: 'none', borderRadius: 6, padding: '5px 10px',
                  cursor: 'pointer', textAlign: 'left',
                  fontFamily: 'var(--font-mono)', fontSize: 11,
                  color: item.block === b.id ? b.accent : 'var(--fg)',
                  fontWeight: item.block === b.id ? 700 : 400,
                }}
              >
                {b.label}
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Text */}
      <span style={textStyle}>{item.text}</span>

      {/* Actions */}
      <div style={actStyle}>
        {isSunday && (
          <button
            style={{
              padding: '3px 10px', borderRadius: 8, border: 'none',
              background: '#2563eb', color: '#fff',
              fontFamily: 'var(--font-mono)', fontSize: 11,
              fontWeight: 700, cursor: 'pointer',
              whiteSpace: 'nowrap',
            }}
            title="Move to This Week priorities"
            onClick={onPromote}
          >
            → This week
          </button>
        )}
        <button style={iconBtnStyle(true)} title="Remove" onClick={onDelete}>✕</button>
      </div>
    </div>
  );
}

Object.assign(window, { ForwardQueue });
