/* Learn — Hub + Article viewer */

const LEARN_TOPICS = [
  {
    id: 'tiling',
    title: 'The Tiling',
    sub: 'What is a Penrose mosaic?',
    icon: '◇',
    color: '#e8794a',
    body: [
      { type: 'p', text: 'A Penrose tiling covers the entire infinite plane using just two shapes — without ever repeating.' },
      { type: 'p', text: 'Unlike a bathroom floor of squares, which repeats the same pattern over and over, a Penrose tiling is aperiodic: no matter how large a section you copy, you will never find an identical copy elsewhere.' },
      { type: 'heading', text: 'Two Simple Rules' },
      { type: 'p', text: 'Place thick and thin rhombi edge-to-edge, matching specific vertex rules at every corner. These local constraints force a globally aperiodic structure to emerge.' },
      { type: 'p', text: 'The result is a pattern that is ordered (every local neighborhood appears infinitely often) yet never periodic — an impossible balancing act that fascinated mathematicians for decades.' },
      { type: 'demo', kind: 'mini-tiling' },
      { type: 'heading', text: 'Where It Began' },
      { type: 'p', text: 'The question of whether aperiodic tilings exist was posed by Hao Wang in 1961. His student Robert Berger found a set of 20,426 tiles that worked. Gradually that number shrank — until Roger Penrose reached just two tiles in 1974.' },
    ],
  },
  {
    id: 'rhombi',
    title: 'Two Rhombi',
    sub: 'Angles, proportions, golden ratio',
    icon: '◆',
    color: '#5cc6ff',
    body: [
      { type: 'p', text: 'The thick rhombus has interior angles of 72° and 108°. The thin rhombus has angles of 36° and 144°.' },
      { type: 'demo', kind: 'two-rhombi' },
      { type: 'heading', text: 'Golden Proportions' },
      { type: 'p', text: 'Both shapes share the same edge length, but their diagonals are related by the golden ratio φ ≈ 1.618. The ratio of thick to thin tiles in an infinite Penrose tiling is exactly φ.' },
      { type: 'p', text: 'The thick rhombus has diagonals in ratio φ:1. The thin rhombus has diagonals in ratio 1:φ. This golden relationship runs through every aspect of the tiling.' },
      { type: 'heading', text: 'Area' },
      { type: 'p', text: 'A thick rhombus has area sin(72°) ≈ 0.951 per unit edge. A thin rhombus has area sin(36°) ≈ 0.588. Their ratio is — once again — the golden ratio φ.' },
    ],
  },
  {
    id: 'aperiodicity',
    title: 'Aperiodicity',
    sub: 'Why the pattern never repeats',
    icon: '∞',
    color: '#9bb6ff',
    body: [
      { type: 'p', text: 'A pattern is periodic if you can slide a copy of it by some fixed distance and have it match exactly. Penrose tilings have no such translation symmetry.' },
      { type: 'heading', text: 'Local Isomorphism' },
      { type: 'p', text: 'Despite never repeating globally, every finite patch that appears will appear infinitely many times. Any neighborhood of radius R can be found within distance 2R of any other point. Mathematicians call this local isomorphism.' },
      { type: 'p', text: 'This means a Penrose tiling looks "almost the same" everywhere — but "almost" hides an infinite gap from true periodicity.' },
      { type: 'heading', text: 'Matching Rules' },
      { type: 'p', text: 'Penrose ensured aperiodicity by decorating tile edges with arrows or arcs. Only specific orientations are allowed. These matching rules make periodic arrangements impossible while still permitting a tiling of the full plane.' },
    ],
  },
  {
    id: 'golden',
    title: 'Golden Ratio',
    sub: 'φ is everywhere in the mosaic',
    icon: 'φ',
    color: '#FFD700',
    body: [
      { type: 'p', text: 'The golden ratio φ = (1 + √5) / 2 ≈ 1.618 appears at every scale in Penrose tilings.' },
      { type: 'heading', text: 'In the Tiles' },
      { type: 'p', text: 'The diagonal ratio of each rhombus involves φ. The ratio of thick to thin tiles is φ. The frequency ratio of any vertex figure type to another involves powers of φ.' },
      { type: 'heading', text: 'In the Geometry' },
      { type: 'p', text: 'Penrose tilings have fivefold symmetry — and φ is intimately connected to the regular pentagon. cos(36°) = φ/2, and the diagonal of a unit pentagon is exactly φ.' },
      { type: 'p', text: 'This is why φ appears: Penrose tilings are built from 5-fold rotational symmetry, and φ is the algebraic heart of five-ness.' },
      { type: 'heading', text: 'Self-Similarity' },
      { type: 'p', text: 'A Penrose tiling can be inflated — replacing each tile with a larger arrangement of tiles — and the result is the same tiling scaled by φ. This self-similar fractal structure continues infinitely.' },
    ],
  },
  {
    id: 'vertex',
    title: 'Vertex Figures',
    sub: '7 ways tiles can meet',
    icon: '✦',
    color: '#e8794a',
    body: [
      { type: 'p', text: 'In a Penrose P3 tiling, tiles meet at vertices in exactly 7 distinct configurations, named by Conway and others:' },
      { type: 'demo', kind: 'vertex-figures' },
      { type: 'heading', text: 'The Seven' },
      { type: 'p', text: 'Star (5 thick), Sun (5 thick + 5 thin), Ace (1 thick + 2 thin), Deuce (2 thin), Jack (1 thick + 4 thin), Queen (3 thick + 2 thin), and King (3 thick + 2 thin, different arrangement).' },
      { type: 'p', text: 'The angles at each vertex must sum to exactly 360°. Since thick contributes 72° or 108° and thin contributes 36° or 144°, only these 7 combinations work.' },
      { type: 'heading', text: 'Frequencies' },
      { type: 'p', text: 'Each type occurs with a specific density related to powers of φ. Stars and Suns are the rarest; Aces and Deuces are the most common.' },
    ],
  },
  {
    id: 'quasicrystals',
    title: 'Quasicrystals',
    sub: 'From mosaic to Nobel Prize',
    icon: '⬡',
    color: '#21f0ff',
    body: [
      { type: 'p', text: 'In 1982, Dan Shechtman observed an aluminum-manganese alloy with sharp diffraction peaks and fivefold symmetry — forbidden by classical crystallography. He had discovered quasicrystals.' },
      { type: 'heading', text: 'The Connection' },
      { type: 'p', text: 'Quasicrystals are the three-dimensional analog of Penrose tilings. Their atoms arrange aperiodically, producing sharp diffraction spots (long-range order) without translational periodicity.' },
      { type: 'p', text: 'Shechtman faced years of skepticism. Linus Pauling reportedly said: "There is no such thing as quasicrystals, only quasi-scientists." Shechtman received the Nobel Prize in Chemistry in 2011.' },
      { type: 'heading', text: 'Penrose\'s Role' },
      { type: 'p', text: 'When Alan Mackay computed the diffraction pattern of a Penrose tiling in 1982, he found sharp spots with tenfold symmetry — just like Shechtman\'s alloy. The mathematical framework was already waiting.' },
    ],
  },
  {
    id: 'art',
    title: 'Penrose & Art',
    sub: 'Connection with Escher & design',
    icon: '🎨',
    color: '#ff2bd6',
    body: [
      { type: 'p', text: 'Roger Penrose and M.C. Escher had a profound mutual influence. Penrose was inspired by Escher\'s impossible constructions; Escher used Penrose\'s ideas about tessellations in his later work.' },
      { type: 'heading', text: 'Impossible Objects' },
      { type: 'p', text: 'In 1954, young Roger Penrose attended an Escher exhibition and was inspired to create the "Penrose triangle" — an impossible three-dimensional object. He sent it to Escher, who used it to create his famous Waterfall and Ascending and Descending lithographs.' },
      { type: 'heading', text: 'In Modern Design' },
      { type: 'p', text: 'Penrose tilings appear in architecture, textiles, and digital art. Their combination of mathematical rigor and visual beauty makes them a favorite of designers seeking structured yet organic patterns.' },
    ],
  },
  {
    id: 'wild',
    title: 'In the Wild',
    sub: 'Mosaic in architecture & nature',
    icon: '🏛',
    color: '#22ff66',
    body: [
      { type: 'p', text: 'Penrose-like patterns appear in surprising places, from medieval Islamic art to modern architecture to the molecular structure of materials.' },
      { type: 'heading', text: 'Islamic Art' },
      { type: 'p', text: 'The Darb-i Imam shrine in Isfahan, Iran (1453) features girih patterns that are locally isomorphic to Penrose tilings — created five centuries before Penrose.' },
      { type: 'heading', text: 'Architecture' },
      { type: 'p', text: 'The Federation Square in Melbourne, Australia uses a Penrose-inspired pinwheel tiling. The Storey Hall at RMIT University features a full Penrose tiling facade.' },
      { type: 'heading', text: 'Nature' },
      { type: 'p', text: 'Quasicrystalline structures have been found in a meteorite from the Khatyrka region of Russia — the first natural quasicrystal, confirming that nature discovered aperiodic order before mathematicians.' },
    ],
  },
];

function MiniTilingDemo({ palette }) {
  const canvasRef = React.useRef(null);
  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || !window.PenroseGeo) return;
    const ctx = canvas.getContext('2d');
    const w = canvas.width = 280;
    const h = canvas.height = 160;
    const tiles = window.PenroseGeo.generateTiling({ radius: 8, pattern: 0.5 });
    const scale = 12;
    ctx.clearRect(0, 0, w, h);
    for (const t of tiles) {
      ctx.beginPath();
      t.verts.forEach((v, i) => {
        const px = w/2 + v.x * scale;
        const py = h/2 - v.y * scale;
        i === 0 ? ctx.moveTo(px, py) : ctx.lineTo(px, py);
      });
      ctx.closePath();
      ctx.fillStyle = t.type === 'thick' ? palette.thick + '55' : palette.thin + '55';
      ctx.fill();
      ctx.strokeStyle = t.type === 'thick' ? palette.thickEdge + '88' : palette.thinEdge + '88';
      ctx.lineWidth = 0.6;
      ctx.stroke();
    }
  }, [palette]);
  return <canvas ref={canvasRef} style={{ width: '100%', height: 160, borderRadius: 12, background: palette.bg2 }} />;
}

function TwoRhombiDemo({ palette }) {
  const VF = window.VertexFigures;
  if (!VF) return null;
  const thickDims = VF.rhombDims('thick');
  const thinDims = VF.rhombDims('thin');
  const S = 50;
  function RhombSVG({ dims, color, edge, label, angles }) {
    const pts = [
      [0, -dims.dy * S], [dims.dx * S, 0],
      [0, dims.dy * S], [-dims.dx * S, 0],
    ];
    return (
      <svg viewBox={`${-dims.dx*S-10} ${-dims.dy*S-18} ${dims.dx*2*S+20} ${dims.dy*2*S+28}`}
           style={{ width: 120, height: 'auto' }}>
        <polygon points={pts.map(p => p.join(',')).join(' ')}
          fill={color + '44'} stroke={edge} strokeWidth="1.5" />
        <text x="0" y={-dims.dy*S + 12} textAnchor="middle"
          fill={palette.ink} fontSize="9" fontFamily="JetBrains Mono, monospace">{angles[0]}</text>
        <text x="0" y={dims.dy*S - 5} textAnchor="middle"
          fill={palette.ink} fontSize="9" fontFamily="JetBrains Mono, monospace">{angles[1]}</text>
        <text x="0" y={dims.dy*S + 16} textAnchor="middle"
          fill={palette.dim} fontSize="10" fontFamily="JetBrains Mono, monospace" fontWeight="700">{label}</text>
      </svg>
    );
  }
  return (
    <div style={{ display: 'flex', justifyContent: 'center', gap: 16, padding: '12px 0' }}>
      <RhombSVG dims={thickDims} color={palette.thick} edge={palette.thickEdge} label="Thick" angles={['72°', '108°']} />
      <RhombSVG dims={thinDims} color={palette.thin} edge={palette.thinEdge} label="Thin" angles={['36°', '144°']} />
    </div>
  );
}

function VertexFiguresDemo({ palette }) {
  const VF = window.VertexFigures;
  if (!VF) return null;
  const figs = ['star', 'sun', 'ace', 'deuce', 'jack', 'queen', 'king'];
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, padding: '8px 0',
    }}>
      {figs.map(key => {
        const fig = VF.VERTEX_FIGURES[key];
        if (!fig) return null;
        const scaleMap = { sun: 0.12, star: 0.18, deuce: 0.3, ace: 0.22, jack: 0.18, queen: 0.18, king: 0.18 };
        const html = VF.vertexFigureToSVG(fig, {
          size: 60, scale: 60 * (scaleMap[key] || 0.22),
          palette, glow: false, id: 'learn-' + key,
        });
        return (
          <div key={key} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3 }}>
            <div dangerouslySetInnerHTML={{ __html: html }} style={{ lineHeight: 0 }} />
            <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 8, color: palette.dim, letterSpacing: '0.08em' }}>
              {fig.name}
            </span>
          </div>
        );
      })}
    </div>
  );
}

function LearnArticle({ topic, palette, onBack }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 10,
      background: palette.bg1, color: palette.ink,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* Header */}
      <div style={{
        padding: '52px 20px 14px', display: 'flex', alignItems: 'center', gap: 12,
        borderBottom: `1px solid ${palette.dim}15`,
      }}>
        <div onClick={onBack} style={{
          width: 34, height: 34, borderRadius: 999,
          border: `1px solid ${palette.dim}22`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', flexShrink: 0,
          WebkitTapHighlightColor: 'transparent',
        }}>
          <svg width="12" height="12" viewBox="0 0 14 14"><path d="M9 2L4 7l5 5" fill="none" stroke={palette.ink} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg>
        </div>
        <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: '0.18em', color: palette.dim }}>LEARN</span>
      </div>

      {/* Content */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 22px 40px' }}>
        {/* Hero icon */}
        <div style={{
          width: 56, height: 56, borderRadius: 16,
          background: topic.color + '18',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 26, marginBottom: 14,
        }}>{topic.icon}</div>

        <h1 style={{
          fontSize: 26, fontWeight: 700, margin: '0 0 6px', lineHeight: 1.2,
        }}>{topic.title}</h1>
        <p style={{
          fontSize: 13, color: palette.dim, margin: '0 0 24px', lineHeight: 1.5,
        }}>{topic.sub}</p>

        {topic.body.map((block, i) => {
          if (block.type === 'heading') {
            return <h2 key={i} style={{
              fontSize: 16, fontWeight: 700, margin: '24px 0 8px',
              color: palette.ink,
            }}>{block.text}</h2>;
          }
          if (block.type === 'p') {
            return <p key={i} style={{
              fontSize: 14, lineHeight: 1.7, margin: '0 0 12px',
              color: palette.ink + 'cc',
            }}>{block.text}</p>;
          }
          if (block.type === 'demo') {
            if (block.kind === 'mini-tiling') return <MiniTilingDemo key={i} palette={palette} />;
            if (block.kind === 'two-rhombi') return <TwoRhombiDemo key={i} palette={palette} />;
            if (block.kind === 'vertex-figures') return <VertexFiguresDemo key={i} palette={palette} />;
          }
          return null;
        })}
      </div>
    </div>
  );
}

function LearnHub({ palette }) {
  const [openTopic, setOpenTopic] = React.useState(null);

  if (openTopic) {
    return <LearnArticle topic={openTopic} palette={palette} onBack={() => setOpenTopic(null)} />;
  }

  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column',
      overflow: 'hidden', position: 'relative',
    }}>
      {/* Header */}
      <div style={{ padding: '52px 22px 14px' }}>
        <div style={{ fontSize: 24, fontWeight: 700, color: palette.ink }}>Learn</div>
        <div style={{ fontSize: 12, color: palette.dim, marginTop: 3 }}>
          Interactive stories about Penrose tilings
        </div>
      </div>

      {/* Cards */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '4px 14px 20px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {LEARN_TOPICS.map(topic => (
          <div key={topic.id} onClick={() => setOpenTopic(topic)} style={{
            display: 'flex', alignItems: 'center', gap: 14,
            padding: '14px 14px', borderRadius: 16,
            background: `${palette.bg2}88`,
            border: `1px solid ${palette.dim}11`,
            cursor: 'pointer',
            WebkitTapHighlightColor: 'transparent',
            touchAction: 'manipulation',
          }}>
            <div style={{
              width: 46, height: 46, borderRadius: 14, flexShrink: 0,
              background: topic.color + '15',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 22,
            }}>{topic.icon}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 700, color: palette.ink }}>{topic.title}</div>
              <div style={{ fontSize: 12, color: palette.dim, marginTop: 2 }}>{topic.sub}</div>
            </div>
            <svg width="7" height="12" viewBox="0 0 7 12" style={{ flexShrink: 0, opacity: 0.4 }}>
              <path d="M1 1l5 5-5 5" fill="none" stroke={palette.dim} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
        ))}
      </div>
    </div>
  );
}

window.LearnHub = LearnHub;
window.LEARN_TOPICS = LEARN_TOPICS;
