// 知乎 — 直答 page.

const D_BG = '#0B0D11';
const D_TEXT = '#EDEEF0';
const D_MUTED = '#7A8089';
const D_DIM = '#4A4F57';
const D_BLUE = '#1772F6';
const D_PURPLE = '#7C6BFF';

const D_SUGGESTIONS = [
  '请概述「全球人口老龄化趋势」催生发展的产业',
  '什么是 AI 大模型?',
  '「自动驾驶最新进展」为主题的报告',
];

const D_KB_LIBRARIES = [
  { title: '《新京报书评周刊》年度书单', desc: '《新京报书评周刊》年度阅读推荐书单。',
    author: '新京报书评周刊', meta: '220 人订阅 · 5 个内容',
    swatch: ['#C58A6F', '#8A4F3D'], cover: ['#5B4636', '#2A1F18'] },
  { title: '深度学习从入门到精通', desc: '收录 12 本经典 ML / DL 教材的精华章节。',
    author: '咕叽咕叽', meta: '1.2 万人订阅 · 12 个内容',
    swatch: ['#6E9CD9', '#345A92'], cover: ['#1F3550', '#0F1F30'] },
  { title: '播客主理人的工具箱', desc: '从选题到剪辑，独立播客人都在用的方法。',
    author: '声音漫游', meta: '3200 人订阅 · 8 个内容',
    swatch: ['#E8B36B', '#A06B2F'], cover: ['#3D2C18', '#1E160A'] },
];

function DLine({ d, w = 18, sw = 1.5, stroke = D_TEXT, fill = 'none' }) {
  return (
    <svg width={w} height={w} viewBox="0 0 24 24" fill={fill} stroke={stroke}
         strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <path d={d}/>
    </svg>
  );
}

function DirectAnswer({ onBack, onMessageTap, onProfileTap, onPlusTap }) {
  const [text, setText] = React.useState('');
  return (
    <div style={{
      position: 'absolute', inset: 0, background: D_BG,
      color: D_TEXT, display: 'flex', flexDirection: 'column',
      fontFamily: '"PingFang SC", "Noto Sans SC", -apple-system, system-ui',
      overflow: 'hidden',
    }}>
      <div style={{ height: 38, flexShrink: 0 }}/>

      {/* Top bar (line icons) */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '6px 14px 4px', flexShrink: 0,
      }}>
        <DLine d="M4 7h16 M4 12h16 M4 17h16" w={18}/>
        <DLine d="M5 4 h11 a2 2 0 012 2 v14 l-7 -3 -8 3 V6 a2 2 0 012-2z"/>
      </div>

      {/* Scrollable hero + card */}
      <div style={{ flex: 1, overflowY: 'auto', position: 'relative' }}>
        <DottedMap/>

        {/* Hero — text along an upward arch */}
        <div style={{
          padding: '24px 0 14px', position: 'relative', zIndex: 2,
          display: 'flex', justifyContent: 'center',
        }}>
          <svg viewBox="0 0 300 90" width="280" height="84" style={{ overflow: 'visible' }}>
            <defs>
              {/* Arch — middle high, ends low */}
              <path id="heroArc" d="M 10 70 Q 150 5 290 70" fill="none"/>
            </defs>
            <text
              fontFamily='"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Source Han Sans CN","Noto Sans SC",sans-serif'
              fontSize="24" fontWeight="800" letterSpacing="2" fill={D_TEXT}
              textAnchor="middle"
            >
              <textPath href="#heroArc" startOffset="50%">
                用<tspan fill={D_PURPLE}>提问</tspan>发现世界
              </textPath>
            </text>
          </svg>
        </div>

        {/* Suggestion pills — moved up close to hero */}
        <div style={{
          padding: '6px 14px 14px',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
          position: 'relative', zIndex: 2,
        }}>
          {D_SUGGESTIONS.map((s, i) => (
            <div key={i} onClick={() => setText(s)} style={{
              fontSize: 11, color: D_DIM, cursor: 'pointer',
              padding: '2px 10px',
            }}>{s}</div>
          ))}
        </div>

        {/* Knowledge library carousel — horizontally swipeable */}
        <KbCarousel items={D_KB_LIBRARIES}/>

        <div style={{ height: 40 }}/>
      </div>

      {/* Selector pills above the input */}
      <div style={{
        display: 'flex', gap: 8, padding: '0 12px 6px', flexShrink: 0,
      }}>
        <div style={{
          padding: '4px 10px', borderRadius: 14, background: '#1A1D23',
          fontSize: 10, color: D_TEXT,
          display: 'flex', alignItems: 'center', gap: 4,
        }}>
          <span style={{ color: D_PURPLE }}>◇</span> 智能思考
          <DLine d="M5 9 l5 5 l5 -5" w={9} sw={1.4} stroke={D_MUTED}/>
        </div>
        <div style={{
          padding: '4px 10px', borderRadius: 14, background: '#1A1D23',
          fontSize: 10, color: D_TEXT,
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          <DLine d="M12 3 a9 9 0 110 18 a9 9 0 010 -18 M3 12 h18 M12 3 c4 4 4 14 0 18 c-4 -4 -4 -14 0 -18"
                 w={11} sw={1.3} stroke={D_TEXT}/>
          <span>知</span>
          <DLine d="M3 9 L12 5 L21 9 L12 13 Z M6 11 v4 c2 2 10 2 12 0 v-4" w={11} sw={1.3} stroke={D_TEXT}/>
          <DLine d="M5 4 h11 a2 2 0 012 2 v14 l-7 -3 -8 3 V6 a2 2 0 012-2z" w={11} sw={1.3} stroke={D_TEXT}/>
          <DLine d="M5 9 l5 5 l5 -5" w={9} sw={1.4} stroke={D_MUTED}/>
        </div>
      </div>

      {/* Input bar */}
      <div style={{
        margin: '0 12px 8px', flexShrink: 0,
        background: '#1A1D23', borderRadius: 22,
        display: 'flex', alignItems: 'center', padding: '6px 12px',
        gap: 8,
      }}>
        <DLine d="M12 3 a3 3 0 00-3 3 v6 a3 3 0 006 0 V6 a3 3 0 00-3 -3 z M5 11 v1 a7 7 0 0014 0 v-1 M12 19 v3 M9 22 h6"
               w={14} sw={1.4} stroke={D_MUTED}/>
        <input
          value={text}
          onChange={e => setText(e.target.value)}
          placeholder="输入你的问题，使用@提问答主/知识库"
          style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            color: D_TEXT, fontSize: 10.5, padding: 0, minWidth: 0,
            fontFamily: 'inherit',
          }}
        />
        <DLine d="M21 12 l-8 8 a5 5 0 01-7 -7 l9 -9 a3.5 3.5 0 015 5 l-9 9 a2 2 0 01-3 -3 l8 -8"
               w={14} sw={1.4} stroke={D_MUTED}/>
      </div>

      {/* Bottom nav — shared with home, with 直答 active */}
      <BottomNav onBack={onBack} activeTab="direct" onMessageTap={onMessageTap} onProfileTap={onProfileTap} onPlusTap={onPlusTap}/>
    </div>
  );
}

function KbCarousel({ items }) {
  const [idx, setIdx] = React.useState(0);
  const scrollRef = React.useRef(null);
  const userTouching = React.useRef(false);

  const onScroll = () => {
    const el = scrollRef.current;
    if (!el) return;
    const w = el.clientWidth;
    const next = Math.round(el.scrollLeft / w);
    if (next !== idx) setIdx(next);
  };

  // Auto-advance every 3.5s, pause while user is touching
  React.useEffect(() => {
    const id = setInterval(() => {
      if (userTouching.current) return;
      const el = scrollRef.current;
      if (!el) return;
      const w = el.clientWidth;
      const next = (Math.round(el.scrollLeft / w) + 1) % items.length;
      el.scrollTo({ left: next * w, behavior: 'smooth' });
    }, 3500);
    return () => clearInterval(id);
  }, [items.length]);

  return (
    <div style={{ position: 'relative', zIndex: 2, marginTop: 6 }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '0 24px 6px',
      }}>
        <span style={{ fontSize: 11, fontWeight: 600, color: D_TEXT }}>推荐知识库</span>
        <span style={{ fontSize: 10, color: D_BLUE, display: 'flex', alignItems: 'center', gap: 3 }}>
          <DLine d="M11 4 a7 7 0 110 14 a7 7 0 010 -14 M16 16 l4 4" w={11} sw={1.6} stroke={D_BLUE}/>
          知识广场
        </span>
      </div>

      <div
        ref={scrollRef}
        onScroll={onScroll}
        onTouchStart={() => { userTouching.current = true; }}
        onTouchEnd={() => { setTimeout(() => { userTouching.current = false; }, 1500); }}
        onMouseDown={() => { userTouching.current = true; }}
        onMouseUp={() => { setTimeout(() => { userTouching.current = false; }, 1500); }}
        style={{
          display: 'flex', overflowX: 'auto', scrollSnapType: 'x mandatory',
          scrollbarWidth: 'none', WebkitOverflowScrolling: 'touch',
        }}
      >
        {items.map((it, i) => (
          <div key={i} style={{
            flexShrink: 0, width: '100%', scrollSnapAlign: 'start',
            padding: '0 12px', boxSizing: 'border-box',
          }}>
            <div style={{
              background: '#14171D', borderRadius: 10, padding: 12,
              display: 'flex', gap: 10,
            }}>
              <div style={{
                width: 56, height: 56, borderRadius: 6, flexShrink: 0,
                background: `linear-gradient(135deg, ${it.cover[0]}, ${it.cover[1]})`,
              }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: D_TEXT,
                              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.title}</div>
                <div style={{ fontSize: 9.5, color: D_MUTED, marginTop: 3, lineHeight: 1.4,
                              display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical',
                              overflow: 'hidden' }}>{it.desc}</div>
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 4,
                  fontSize: 9, color: D_MUTED, marginTop: 5,
                }}>
                  <span style={{
                    width: 12, height: 12, borderRadius: 6,
                    background: `linear-gradient(135deg, ${it.swatch[0]}, ${it.swatch[1]})`,
                  }}/>
                  <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {it.author} · {it.meta}
                  </span>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', gap: 4, marginTop: 10 }}>
        {items.map((_, i) => (
          <span key={i} style={{
            width: i === idx ? 8 : 4, height: 4, borderRadius: 2,
            background: i === idx ? D_BLUE : '#2A2E35', transition: 'width 0.2s',
          }}/>
        ))}
      </div>
    </div>
  );
}

function DottedMap() {
  const dots = [];
  for (let y = 0; y < 14; y++) {
    for (let x = 0; x < 40; x++) {
      const cx = (x - 20) * 8 + 160;
      const cy = y * 12 + 30;
      const d = Math.sqrt((x - 20) ** 2 + (y - 7) ** 2);
      if (d < 6 + Math.sin(x * 0.6) * 1.2 && (x + y * 3) % 3 === 0) {
        dots.push(<circle key={`${x},${y}`} cx={cx} cy={cy} r="1" fill="#3F8DFF" opacity={0.35 - d * 0.04}/>);
      }
    }
  }
  return (
    <svg style={{
      position: 'absolute', top: 80, left: 0, right: 0,
      width: '100%', height: 220, pointerEvents: 'none',
    }} viewBox="0 0 320 220" preserveAspectRatio="xMidYMid meet">
      <circle cx="160" cy="110" r="100" fill="none" stroke="#1E2733" strokeWidth="0.5"/>
      <circle cx="160" cy="110" r="70" fill="none" stroke="#1E2733" strokeWidth="0.5"/>
      <circle cx="160" cy="110" r="40" fill="none" stroke="#1E2733" strokeWidth="0.5"/>
      {dots}
    </svg>
  );
}

Object.assign(window, { DirectAnswer });
