// Card component — B-style (conversational / letter-feel).
// Renders a content card with feedback buttons and persisted state.

const T = {
  paper: '#fffdf8',
  bg: '#f7f5f0',
  bgDeep: '#f3efe6',
  ink: '#24201b',
  inkMuted: '#6f685d',
  inkFaint: '#a59e92',
  rule: '#e8e2d6',
  ruleSoft: '#efeadf',
  accent: 'oklch(0.55 0.10 165)',
  warn: 'oklch(0.60 0.12 30)',
  neutral: 'oklch(0.68 0.015 85)',
  add: 'oklch(0.55 0.08 270)',
  star: 'oklch(0.65 0.14 75)',
};

window.T = T;

// Render inline markdown-ish: **bold** only, rest plain.
function renderInline(text) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return parts.map((p, i) => {
    if (p.startsWith('**') && p.endsWith('**')) {
      return <b key={i} style={{ color: T.ink, fontWeight: 600 }}>{p.slice(2, -2)}</b>;
    }
    return <React.Fragment key={i}>{p}</React.Fragment>;
  });
}

function Block({ block }) {
  if (block.type === 'p') {
    return (
      <p style={{
        margin: '0 0 14px', fontSize: block.small ? 14 : 16.5,
        lineHeight: 1.8, color: block.small ? T.inkMuted : T.ink,
      }}>{renderInline(block.text)}</p>
    );
  }
  if (block.type === 'h') {
    return (
      <h4 style={{
        margin: '22px 0 10px', fontSize: 15, fontWeight: 600,
        color: T.ink, letterSpacing: 0,
      }}>{block.text}</h4>
    );
  }
  if (block.type === 'list') {
    return (
      <ul style={{
        margin: '0 0 14px', paddingLeft: 0, listStyle: 'none',
      }}>
        {block.items.map((it, i) => (
          <li key={i} style={{
            position: 'relative', paddingLeft: 20, marginBottom: 8,
            fontSize: 16, lineHeight: 1.75, color: T.ink,
          }}>
            <span style={{
              position: 'absolute', left: 2, top: '0.75em',
              width: 6, height: 6, borderRadius: '50%',
              background: T.inkFaint,
            }} />
            {renderInline(it)}
          </li>
        ))}
      </ul>
    );
  }
  if (block.type === 'quote') {
    return (
      <blockquote style={{
        margin: '18px 0',
        paddingLeft: 16,
        borderLeft: `2px solid ${T.rule}`,
        fontSize: 15.5, lineHeight: 1.75, color: T.inkMuted,
      }}>
        {renderInline(block.text)}
        {block.cite && (
          <div style={{ fontSize: 12, color: T.inkFaint, marginTop: 6 }}>— {block.cite}</div>
        )}
      </blockquote>
    );
  }
  if (block.type === 'note') {
    return (
      <div style={{
        margin: '16px 0',
        padding: '12px 16px',
        background: T.bg,
        border: `1px dashed ${T.rule}`,
        borderRadius: 8,
        fontSize: 14, lineHeight: 1.7, color: T.inkMuted,
      }}>{renderInline(block.text)}</div>
    );
  }
  if (block.type === 'table') {
    return (
      <div style={{
        margin: '16px 0',
        border: `1px solid ${T.ruleSoft}`,
        borderRadius: 8, overflow: 'hidden',
        fontSize: 13.5,
      }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: `repeat(${block.headers.length}, 1fr)`,
          padding: '10px 14px', background: T.bg,
          color: T.inkMuted, fontWeight: 500, gap: 10,
          borderBottom: `1px solid ${T.ruleSoft}`,
        }}>
          {block.headers.map((h, i) => <div key={i}>{h}</div>)}
        </div>
        {block.rows.map((row, ri) => (
          <div key={ri} style={{
            display: 'grid',
            gridTemplateColumns: `repeat(${block.headers.length}, 1fr)`,
            padding: '11px 14px', gap: 10,
            borderBottom: ri < block.rows.length - 1 ? `1px solid ${T.ruleSoft}` : 'none',
            color: T.ink, lineHeight: 1.5,
          }}>
            {row.map((c, ci) => (
              <div key={ci} style={{ color: ci === 0 ? T.ink : T.inkMuted }}>
                {renderInline(c)}
              </div>
            ))}
          </div>
        ))}
      </div>
    );
  }
  if (block.type === 'diagram') {
    return (
      <div style={{
        margin: '16px 0',
        padding: '20px 22px',
        background: T.bg,
        border: `1px solid ${T.ruleSoft}`,
        borderRadius: 10,
        fontFamily: '"SF Mono", "JetBrains Mono", ui-monospace, Menlo, monospace',
        fontSize: 12, lineHeight: 1.55,
        color: T.ink, overflowX: 'auto', whiteSpace: 'pre',
      }}>
{`              ┌────────────────────────────────────┐
              │          主脑 Agent · AI 副总        │
              │  跨模块查询 · 主动预警 · 决策辅助      │
              └─┬──────┬──────┬──────┬──────┬──────┘
                │      │      │      │      │
         ┌──────▼─┐ ┌──▼──┐ ┌▼────┐ ┌▼────┐ ┌▼──────┐
         │ 采购    │ │内勤 │ │财务 │ │维保  │ │业务员  │
         │ Agent  │ │Agent│ │Agent│ │Agent│ │Agent   │
         │ 组     │ │组   │ │     │ │     │ │×8      │
         └────────┘ └─────┘ └─────┘ └─────┘ └────────┘
              ↕      ↕      ↕      ↕      ↕
         子 Agent 和主脑双向——主动汇报异常 + 向下调度

              ┌──────── 跨部门共享 ────────┐
         ┌────▼────┐              ┌───────▼───────┐
         │ 证照     │              │ 招标情报       │
         │ Agent   │              │ Agent         │
         └─────────┘              └───────────────┘`}
      </div>
    );
  }
  if (block.type === 'pipeline') {
    const steps = [
      ['1', '业务员（现场）', '从科主任了解未来采购计划、预算、偏好品牌/参数'],
      ['2', '录入日报（语音）', 'AI 自动生成结构化日报 + 提取需求信息'],
      ['3', '业务员 Agent / 主脑', '把需求派给推荐 Agent'],
      ['4', '推荐 Agent', '医院需求 + 产品特色 + 毛利 + 关系 + 科主任偏好 → 给出建议'],
      ['5', '采购（人）', '跟厂家做报备'],
      ['6', '业务员回医院', '推这家厂家的这款产品，推动按这款的技术参数写招标要求'],
      ['7', '等招标挂出', ''],
    ];
    return (
      <div style={{
        margin: '18px 0',
        display: 'flex', flexDirection: 'column', gap: 2,
      }}>
        {steps.map(([n, head, desc], i) => (
          <React.Fragment key={i}>
            <div style={{
              display: 'flex', gap: 14, alignItems: 'flex-start',
              padding: '12px 16px',
              background: T.paper,
              border: `1px solid ${T.ruleSoft}`,
              borderRadius: 8,
            }}>
              <div style={{
                width: 24, height: 24, borderRadius: '50%',
                background: T.ink, color: T.paper,
                fontSize: 12, fontWeight: 600,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0, fontFamily: '"SF Mono", ui-monospace, monospace',
              }}>{n}</div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 500, color: T.ink, marginBottom: desc ? 2 : 0 }}>{head}</div>
                {desc && <div style={{ fontSize: 13.5, color: T.inkMuted, lineHeight: 1.55 }}>{desc}</div>}
              </div>
            </div>
            {i < steps.length - 1 && (
              <div style={{
                height: 16, display: 'flex', justifyContent: 'center', alignItems: 'center',
              }}>
                <div style={{ width: 1, height: 16, background: T.rule }} />
              </div>
            )}
          </React.Fragment>
        ))}
      </div>
    );
  }
  return null;
}

window.Block = Block;

const FEEDBACK_CONFIG = {
  agree:    { color: T.accent,  glyph: '✓', full: '这条对' },
  disagree: { color: T.warn,    glyph: '✕', full: '不是我意思' },
  skip:     { color: T.neutral, glyph: '—', full: '不重要' },
  add:      { color: T.add,     glyph: '+', full: '我想补充' },
};
window.FEEDBACK_CONFIG = FEEDBACK_CONFIG;

function FeedbackCard({ card, state, note, onState, onNote, index }) {
  const [noteOpen, setNoteOpen] = React.useState(!!note || state === 'add');

  React.useEffect(() => {
    if (state === 'add' || !!note) setNoteOpen(true);
  }, [state, note]);

  const active = state ? FEEDBACK_CONFIG[state] : null;
  const cardRef = React.useRef(null);

  return (
    <article
      id={`card-${card.id}`}
      ref={cardRef}
      style={{
        scrollMarginTop: 100,
        background: T.paper,
        border: `1px solid ${T.rule}`,
        borderRadius: 16,
        padding: 'clamp(26px, 5vw, 44px)',
        position: 'relative',
        transition: 'box-shadow 200ms ease',
        boxShadow: active
          ? `inset 5px 0 0 ${active.color}, 0 1px 2px rgba(0,0,0,0.03)`
          : '0 1px 2px rgba(0,0,0,0.03)',
        marginBottom: 20,
      }}
    >
      {/* Meta row */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18,
        fontFamily: '"SF Mono", "JetBrains Mono", ui-monospace, monospace',
        fontSize: 11, color: T.inkFaint, letterSpacing: 0.5,
        flexWrap: 'wrap',
      }}>
        <span style={{ fontVariantNumeric: 'tabular-nums' }}>
          {String(index + 1).padStart(2, '0')}
        </span>
        <span style={{ width: 16, height: 1, background: T.rule }} />
        <span>{card.sectionLabel}</span>
        {card.star && (
          <span style={{
            marginLeft: 'auto',
            display: 'inline-flex', alignItems: 'center', gap: 4,
            padding: '2px 8px', borderRadius: 999,
            background: 'oklch(0.97 0.04 80)',
            color: T.star, fontSize: 11, fontWeight: 500,
            letterSpacing: 0,
          }}>
            <svg width="10" height="10" viewBox="0 0 12 12" fill="currentColor"><path d="M6 1l1.5 3.1 3.5.5-2.5 2.4.6 3.4L6 8.9 2.9 10.4l.6-3.4L1 4.6l3.5-.5z"/></svg>
            关键 · 优先看
          </span>
        )}
      </div>

      {/* Title */}
      <h3 style={{
        margin: '0 0 8px', fontSize: 'clamp(20px, 2.4vw, 26px)', fontWeight: 500,
        color: T.ink, letterSpacing: -0.4, lineHeight: 1.3,
      }}>
        {card.title}
      </h3>
      {card.subtitle && (
        <div style={{
          fontSize: 15, color: T.inkMuted, marginBottom: 20,
          lineHeight: 1.6,
        }}>
          {card.subtitle}
        </div>
      )}
      {!card.subtitle && <div style={{ marginBottom: 8 }} />}

      {/* Body */}
      <div style={{
        fontSize: 16.5, lineHeight: 1.8, color: T.ink,
      }}>
        {card.body.map((b, i) => <Block key={i} block={b} />)}
      </div>

      {/* Reaction buttons */}
      <div style={{
        marginTop: 28,
        display: 'flex', gap: 8, flexWrap: 'wrap',
      }}>
        {Object.entries(FEEDBACK_CONFIG).map(([k, c]) => {
          const isActive = state === k;
          return (
            <button
              key={k}
              onClick={() => {
                if (k === 'add') {
                  setNoteOpen(true);
                  onState(state === 'add' && !note ? null : 'add');
                  return;
                }
                onState(isActive ? null : k);
              }}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 10,
                minHeight: 44, padding: '0 16px',
                background: isActive ? c.color : 'transparent',
                color: isActive ? '#fff' : T.ink,
                border: `1px solid ${isActive ? c.color : T.rule}`,
                borderRadius: 999,
                fontSize: 15, fontWeight: 500,
                cursor: 'pointer',
                transition: 'all 150ms ease',
                fontFamily: 'inherit',
                WebkitTapHighlightColor: 'transparent',
              }}
            >
              <span style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 20, height: 20, borderRadius: '50%',
                background: isActive ? 'rgba(255,255,255,0.22)' : 'transparent',
                border: isActive ? 'none' : `1px solid ${T.rule}`,
                fontSize: 11, fontWeight: 700,
                color: isActive ? '#fff' : c.color,
              }}>{c.glyph}</span>
              {c.full}
            </button>
          );
        })}
      </div>

      {noteOpen && (
        <div style={{ marginTop: 16 }}>
          <textarea
            value={note || ''}
            onChange={(e) => onNote(e.target.value)}
            placeholder="说两句…（留空不影响，写了哥哥会看到）"
            rows={3}
            style={{
              width: '100%', resize: 'vertical',
              padding: '14px 16px',
              border: `1px solid ${T.rule}`,
              borderRadius: 12,
              fontSize: 15, lineHeight: 1.6,
              fontFamily: 'inherit', color: T.ink,
              background: T.bg, outline: 'none',
              boxSizing: 'border-box',
            }}
            onFocus={(e) => e.target.style.borderColor = T.add}
            onBlur={(e) => e.target.style.borderColor = T.rule}
          />
        </div>
      )}
    </article>
  );
}

window.FeedbackCard = FeedbackCard;
