// Direction A — "Operator"
// Warm paper background, ink text, single amber accent.
// Dense, info-first, board-led. Designed to feel like a working tool
// for two people running a growth & strategy team.

const A_TOKENS = {
  // Surfaces — warm neutral with real tonal depth (inspired by Linear/Height on warm)
  paper: '#f4f1ea',       // app background
  paperDeep: '#e8e3d6',   // column/subtle wash
  ink: '#15130f',         // near-black, warm
  inkSoft: '#5a564e',     // secondary text
  inkFaint: '#9a958a',    // tertiary/meta
  line: '#dcd5c3',        // borders
  lineSoft: '#ebe5d3',    // subtle dividers
  card: '#ffffff',        // card background (cleaner than cream)
  cardHover: '#fbfaf6',
  accent: '#b4541a',      // burnt amber — signature
  accentDeep: '#8f3f11',  // hover
  accentSoft: '#f7dfc6',  // wash
  accentFaint: '#fcecd9',
  good: '#4a6b3a',
  goodSoft: '#e0e7d2',
  warn: '#a8791c',
  warnSoft: '#f3e4bc',
  bad: '#9a3a24',
  badSoft: '#f3d0c2',
  // category — more harmonious, all tuned to the warm palette
  catAcquisition: '#8b4a1e',
  catBIC: '#2d5269',
  catMHC: '#5e3a6f',
  catOperations: '#3c6248',
  catMarketing: '#934a62',
  catOther: '#6b655c',
};

const A_CAT_COLOR = {
  Acquisition: A_TOKENS.catAcquisition,
  BIC: A_TOKENS.catBIC,
  MHC: A_TOKENS.catMHC,
  Operations: A_TOKENS.catOperations,
  Marketing: A_TOKENS.catMarketing,
  Other: A_TOKENS.catOther,
};

const A_STATUS_META = {
  'To Do':       { tint: '#e8e3d4', glyph: '◌' },
  'In Progress': { tint: '#f4e3c4', glyph: '◐' },
  'Waiting':     { tint: '#e3ddf0', glyph: '◔' },
  'Blocked':     { tint: '#f1cfc2', glyph: '✕' },
  'Done':        { tint: '#dbe4cd', glyph: '●' },
};

function APill({ children, bg, fg, mono, style }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      fontSize: 10.5, fontWeight: 500, letterSpacing: 0.3,
      textTransform: 'uppercase',
      padding: '2px 7px',
      borderRadius: 2,
      background: bg, color: fg,
      fontFamily: mono ? 'var(--mono)' : 'var(--body)',
      whiteSpace: 'nowrap',
      ...style,
    }}>{children}</span>
  );
}

function ADueChip({ due }) {
  const info = window.dueLabel(due);
  if (!info) return <span style={{ color: A_TOKENS.inkFaint, fontSize: 11, fontFamily: 'var(--mono)' }}>—</span>;
  const colors = {
    overdue: { bg: A_TOKENS.badSoft, fg: A_TOKENS.bad },
    today:   { bg: A_TOKENS.accentSoft, fg: A_TOKENS.accent },
    soon:    { bg: A_TOKENS.warnSoft, fg: A_TOKENS.warn },
    week:    { bg: A_TOKENS.paperDeep, fg: A_TOKENS.inkSoft },
    far:     { bg: 'transparent', fg: A_TOKENS.inkFaint },
  }[info.tone];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 3,
      fontSize: 11, fontFamily: 'var(--mono)', fontWeight: 500,
      padding: '2px 6px', borderRadius: 2,
      background: colors.bg, color: colors.fg,
      whiteSpace: 'nowrap',
    }}>{info.text}</span>
  );
}

function AAvatar({ name, size = 20 }) {
  if (name === 'Both') {
    return (
      <div style={{ display: 'inline-flex' }}>
        <AAvatar name="Phil" size={size} />
        <div style={{ marginLeft: -6 }}><AAvatar name="Bob" size={size} /></div>
      </div>
    );
  }
  const letter = name[0];
  // Refined avatar gradients instead of flat colors — Linear-esque
  const bg = name === 'Phil'
    ? 'linear-gradient(135deg, #3a6379 0%, #254859 100%)'
    : name === 'Bob'
    ? 'linear-gradient(135deg, #8a5a35 0%, #5e3a1c 100%)'
    : A_TOKENS.inkSoft;
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: bg, color: '#ffffff',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.46, fontWeight: 600,
      boxShadow: `0 0 0 1.5px ${A_TOKENS.card}, 0 1px 2px rgba(0,0,0,.08)`,
      fontFamily: 'var(--body)',
      flexShrink: 0,
      letterSpacing: 0,
    }}>{letter}</div>
  );
}

// ────── Task card — the atom of the board view ──────
function ATaskCard({ task, onOpen, onDragStart, onDragEnd, dragging, onQuickStatus, onDelete }) {
  const overdue = task.due_date && new Date(task.due_date) < new Date(new Date().toDateString());
  const [confirming, setConfirming] = React.useState(false);
  const [hovered, setHovered] = React.useState(false);
  React.useEffect(() => { if (!hovered) setConfirming(false); }, [hovered]);
  return (
    <div
      draggable
      onDragStart={(e) => { e.dataTransfer.setData('text/plain', String(task.id)); onDragStart && onDragStart(task); }}
      onDragEnd={onDragEnd}
      onClick={onOpen}
      style={{
        background: A_TOKENS.card,
        border: `1px solid ${A_TOKENS.lineSoft}`,
        borderRadius: 8,
        padding: '14px 15px 13px',
        marginBottom: 10,
        cursor: 'pointer',
        transition: 'transform .12s, box-shadow .12s, border-color .12s',
        opacity: dragging ? 0.4 : 1,
        position: 'relative',
        boxShadow: '0 1px 2px rgba(20,16,10,.03)',
      }}
      onMouseEnter={(e) => { setHovered(true); e.currentTarget.style.borderColor = A_TOKENS.line; e.currentTarget.style.boxShadow = '0 4px 12px rgba(20,16,10,.06), 0 1px 3px rgba(20,16,10,.04)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
      onMouseLeave={(e) => { setHovered(false); e.currentTarget.style.borderColor = A_TOKENS.lineSoft; e.currentTarget.style.boxShadow = '0 1px 2px rgba(20,16,10,.03)'; e.currentTarget.style.transform = 'translateY(0)'; }}
    >
      {hovered && onDelete && (
        <button
          onClick={(e) => {
            e.stopPropagation();
            if (confirming) { onDelete(task.id); }
            else { setConfirming(true); }
          }}
          title={confirming ? 'Click again to confirm' : 'Delete task'}
          style={{
            position: 'absolute', top: 8, right: 8, zIndex: 2,
            width: confirming ? 'auto' : 22, height: 22, padding: confirming ? '0 8px' : 0,
            borderRadius: 4, border: 'none',
            background: confirming ? A_TOKENS.accent : 'rgba(20,16,10,.06)',
            color: confirming ? '#fff' : A_TOKENS.inkSoft,
            fontSize: confirming ? 10.5 : 14, lineHeight: 1, cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: confirming ? 'var(--mono)' : 'inherit',
            letterSpacing: confirming ? 0.5 : 0, textTransform: confirming ? 'uppercase' : 'none',
            fontWeight: confirming ? 600 : 400,
          }}
          onMouseEnter={(e) => { if (!confirming) e.currentTarget.style.background = 'rgba(20,16,10,.12)'; }}
          onMouseLeave={(e) => { if (!confirming) e.currentTarget.style.background = 'rgba(20,16,10,.06)'; }}
        >
          {confirming ? 'Delete?' : '×'}
        </button>
      )}
      {/* Category stripe as a thin top accent, softer than left border */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 2,
        background: A_CAT_COLOR[task.category], opacity: 0.7,
        borderRadius: '8px 8px 0 0',
      }} />
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginBottom: 10, marginTop: 2 }}>
        <div style={{ flex: 1, fontSize: 13.5, lineHeight: 1.45, color: A_TOKENS.ink, fontWeight: 550, letterSpacing: -0.15 }}>
          {task.title}
        </div>
        {task.priority === 'High' && (
          <div title="High priority" style={{
            width: 6, height: 6, borderRadius: '50%',
            background: A_TOKENS.accent, marginTop: 7, flexShrink: 0,
            boxShadow: `0 0 0 3px ${A_TOKENS.accentFaint}`,
          }} />
        )}
      </div>
      {task.next_step && (
        <div style={{
          fontSize: 12, color: A_TOKENS.inkSoft, lineHeight: 1.5,
          marginBottom: 12,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
        }}>
          <span style={{ color: A_TOKENS.inkFaint, marginRight: 5 }}>→</span>{task.next_step}
        </div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 5,
          fontSize: 10.5, color: A_CAT_COLOR[task.category],
          fontWeight: 550, letterSpacing: 0.1,
        }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: A_CAT_COLOR[task.category] }} />
          {task.category}
        </span>
        <ADueChip due={task.due_date} />
        <div style={{ flex: 1 }} />
        <AAvatar name={task.owner} size={18} />
      </div>
    </div>
  );
}

// ────── Kanban board ──────
function ABoard({ store, filter, onOpenTask }) {
  const [dragId, setDragId] = React.useState(null);
  const [overCol, setOverCol] = React.useState(null);

  const visible = store.tasks.filter((t) => {
    if (filter.owner && filter.owner !== 'All' && t.owner !== filter.owner && t.owner !== 'Both') return false;
    if (filter.category && t.category !== filter.category) return false;
    if (filter.q && !(`${t.title} ${t.next_step}`.toLowerCase().includes(filter.q.toLowerCase()))) return false;
    return true;
  });

  const byStatus = Object.fromEntries(window.MOCK.STATUSES.map((s) => [s, []]));
  visible.forEach((t) => byStatus[t.status] && byStatus[t.status].push(t));

  // Sort: priority desc, due asc, null due last
  const priOrd = { High: 0, Medium: 1, Low: 2 };
  Object.keys(byStatus).forEach((s) => byStatus[s].sort((a, b) =>
    (priOrd[a.priority] - priOrd[b.priority])
    || ((a.due_date || '9999') < (b.due_date || '9999') ? -1 : 1)
  ));

  const handleDrop = (e, status) => {
    e.preventDefault();
    const id = Number(e.dataTransfer.getData('text/plain'));
    if (id) store.updateTask(id, { status });
    setDragId(null); setOverCol(null);
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14, padding: '0 32px 32px', minHeight: 0 }}>
      {window.MOCK.STATUSES.map((status) => {
        const count = byStatus[status].length;
        const isOver = overCol === status;
        return (
          <div
            key={status}
            onDragOver={(e) => { e.preventDefault(); setOverCol(status); }}
            onDragLeave={() => setOverCol(null)}
            onDrop={(e) => handleDrop(e, status)}
            style={{
              display: 'flex', flexDirection: 'column',
              background: isOver ? A_TOKENS.accentFaint : A_TOKENS.paperDeep,
              borderRadius: 10,
              padding: '16px 12px 12px',
              minHeight: 460,
              transition: 'background .15s',
              border: isOver ? `1px dashed ${A_TOKENS.accent}` : `1px solid transparent`,
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 14, padding: '0 6px' }}>
              <span style={{
                color: A_TOKENS.inkSoft, fontSize: 14, lineHeight: 1,
                opacity: 0.75,
              }}>{A_STATUS_META[status].glyph}</span>
              <span style={{
                fontSize: 12.5, fontWeight: 600, letterSpacing: -0.1,
                color: A_TOKENS.ink, fontFamily: 'var(--body)',
              }}>{status}</span>
              <div style={{ flex: 1 }} />
              <span style={{
                fontSize: 11, color: A_TOKENS.inkFaint, fontFamily: 'var(--mono)',
                fontVariantNumeric: 'tabular-nums',
              }}>{count}</span>
            </div>
            <div style={{ flex: 1 }}>
              {byStatus[status].map((t) => (
                <ATaskCard key={t.id} task={t}
                  onOpen={() => onOpenTask(t.id)}
                  onDragStart={() => setDragId(t.id)}
                  onDragEnd={() => { setDragId(null); setOverCol(null); }}
                  onDelete={store.deleteTask}
                  dragging={dragId === t.id} />
              ))}
              {count === 0 && (
                <div style={{ fontSize: 11.5, color: A_TOKENS.inkFaint, textAlign: 'center', padding: '28px 8px' }}>
                  {isOver ? 'Drop here' : '—'}
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { A_TOKENS, A_CAT_COLOR, A_STATUS_META, APill, ADueChip, AAvatar, ATaskCard, ABoard });
