// Variant 1: Museum Catalog — 博物誌 / 分類カード風
// Deep ink on cream, red seal, catalog number, serif typography.

function renderEmphasis(text, color = '#8b2920') {
  if (!text) return null;
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return parts.map((p, i) => p.startsWith('**') ?
    <b key={i} style={{ color }}>{p.slice(2, -2)}</b> :
    <React.Fragment key={i}>{p}</React.Fragment>
  );
}
window.renderEmphasis = renderEmphasis;

function MuseumResult({ subject, level, onChangeLevel, tone, onChangeTone, onClose }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, background: '#f4ecdc',
      overflowY: 'auto', WebkitOverflowScrolling: 'touch',
      fontFamily: '"Noto Serif JP", "Hiragino Mincho Pro", serif',
      color: '#1a1612',
    }}>
      {/* paper texture */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'repeating-linear-gradient(0deg, rgba(120,90,50,0.03) 0 1px, transparent 1px 4px)',
      }}/>

      {/* sticky handle bar */}
      <StickyHeader variant="museum" onClose={onClose} subject={subject}/>

      <div style={{ padding: '8px 24px 40px', position: 'relative' }}>

        {/* Masthead */}
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
          borderBottom: '1px solid #1a1612', paddingBottom: 10, marginBottom: 18,
        }}>
          <div>
            <div style={{
              fontFamily: 'ui-monospace, "SF Mono", monospace', fontSize: 10,
              letterSpacing: 3, color: '#8b2920',
            }}>CATALOG № {subject.catalogNo}</div>
            <div style={{
              fontFamily: 'ui-monospace, "SF Mono", monospace', fontSize: 9,
              letterSpacing: 2, color: '#6b5a3a', marginTop: 3,
            }}>{subject.category.toUpperCase()}</div>
          </div>
          <div style={{
            fontFamily: 'ui-monospace, "SF Mono", monospace', fontSize: 9,
            letterSpacing: 2, color: '#6b5a3a', textAlign: 'right',
          }}>
            <div>PLATE I</div>
            <div>2026 · Ⅳ · 18</div>
          </div>
        </div>

        {/* Title */}
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18, marginBottom: 14 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontSize: 11, letterSpacing: 3, color: '#8b2920',
              fontFamily: 'ui-monospace, monospace', marginBottom: 2,
            }}>{subject.reading}</div>
            <div style={{
              fontSize: 44, fontWeight: 500, letterSpacing: 2, lineHeight: 1.1,
            }}>{subject.name}</div>
            <div style={{
              fontStyle: 'italic', fontSize: 13, color: '#6b5a3a', marginTop: 4,
              letterSpacing: 0.5,
            }}>{subject.latin}</div>
          </div>
          {/* red seal */}
          <div style={{
            width: 64, height: 64, flexShrink: 0,
            border: '2.5px solid #8b2920', borderRadius: 2,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#8b2920', fontFamily: '"Noto Serif JP", serif',
            transform: 'rotate(-6deg)', marginTop: 4,
            boxShadow: 'inset 0 0 0 1px #f4ecdc',
          }}>
            <div style={{ textAlign: 'center', fontWeight: 600, fontSize: 13, letterSpacing: 1, lineHeight: 1.1 }}>
              <div>収蔵</div>
              <div>済</div>
            </div>
          </div>
        </div>

        {/* Illustration plate */}
        <div style={{
          border: '1px solid #1a1612', padding: 8, background: '#f9f3e2',
          marginBottom: 6,
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            height: 200, background: '#f4ecdc',
            border: '0.5px dashed #6b5a3a',
          }}>
            <SubjectIllustration which={subject.thumb} size={190}/>
          </div>
        </div>
        <div style={{
          fontFamily: 'ui-monospace, monospace', fontSize: 9,
          color: '#6b5a3a', letterSpacing: 1.5, textAlign: 'center', marginBottom: 22,
        }}>Fig. 1 — 現地撮影（iPhoneカメラ）</div>

        {/* Specimen table */}
        <SpecTable rows={[
          ['分類', subject.category],
          ['時代', subject.era],
          ['地域', subject.region],
          ['材質', subject.material || '—'],
        ]}/>

        {/* Summary */}
        <SectionTitle no="Ⅰ" title="概要" sub="これは なに？"/>
        <p style={{
          fontSize: 15, lineHeight: 1.95, margin: '6px 0 24px',
          textIndent: '1em',
        }}>{renderEmphasis(subject.summary)}</p>

        {/* Level pills + tone */}
        <LevelPicker level={level} onChange={onChangeLevel} variant="museum"/>
        <ToneToggle tone={tone} onChange={onChangeTone} variant="museum"/>

        {/* History */}
        <SectionTitle no="Ⅱ" title="歴史的経緯" sub="どう生まれて、どう広まった？"/>
        <div style={{ borderLeft: '1px solid #1a1612', paddingLeft: 16, marginTop: 10, marginBottom: 26 }}>
          {subject.history.map((h, i) => (
            <div key={i} style={{ position: 'relative', marginBottom: 14 }}>
              <div style={{
                position: 'absolute', left: -20, top: 7, width: 7, height: 7,
                borderRadius: '50%', background: '#8b2920',
              }}/>
              <div style={{
                fontFamily: 'ui-monospace, monospace', fontSize: 10,
                letterSpacing: 1.5, color: '#8b2920', marginBottom: 2,
              }}>{h.year}</div>
              <div style={{ fontSize: 14, lineHeight: 1.75 }}>{h.text}</div>
            </div>
          ))}
        </div>

        {/* Subject connections */}
        <SectionTitle no="Ⅲ" title="学びとつながる" sub="中学・高校の勉強でいうと"/>
        <div style={{ marginTop: 10, marginBottom: 22 }}>
          {subject.connections.map((c, i) => (
            <div key={i} style={{
              display: 'flex', gap: 12, padding: '12px 0',
              borderBottom: i < subject.connections.length - 1 ? '0.5px solid #c4b593' : 'none',
            }}>
              <div style={{ width: 72, flexShrink: 0 }}>
                <div style={{
                  background: '#8b2920', color: '#f4ecdc', padding: '2px 6px',
                  fontSize: 10, textAlign: 'center', letterSpacing: 1,
                  fontFamily: '"Noto Serif JP", serif',
                }}>{c.subject}</div>
                <div style={{
                  fontSize: 9, color: '#6b5a3a', textAlign: 'center',
                  marginTop: 3, fontFamily: 'ui-monospace, monospace', letterSpacing: 1,
                }}>{c.grade}</div>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 2 }}>{c.topic}</div>
                <div style={{ fontSize: 13, color: '#3a2f22', lineHeight: 1.7 }}>{c.note}</div>
              </div>
            </div>
          ))}
          <LessonsButton subject={subject} accent="#8b2920"/>
        </div>

        {/* Deeper */}
        <SectionTitle no="Ⅳ" title="もっと深く" sub="いちばんおもしろいところ"/>
        <div style={{
          marginTop: 10, padding: '16px 18px', background: '#ede3c7',
          border: '0.5px solid #c4b593', position: 'relative',
        }}>
          <div style={{
            position: 'absolute', top: -10, left: 14, background: '#f4ecdc',
            padding: '0 8px', fontSize: 10, letterSpacing: 2, color: '#8b2920',
            fontFamily: 'ui-monospace, monospace',
          }}>NOTA BENE</div>
          <div style={{ fontSize: 14, lineHeight: 1.85 }}>{renderEmphasis(subject.deeper)}</div>
        </div>

        {/* Footer */}
        <div style={{
          marginTop: 28, paddingTop: 14, borderTop: '1px solid #1a1612',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          fontFamily: 'ui-monospace, monospace', fontSize: 10, color: '#6b5a3a',
          letterSpacing: 1.5,
        }}>
          <div>{subject.tags.join('  ')}</div>
          <div>— 館員  AI</div>
        </div>
      </div>
    </div>
  );
}

function SectionTitle({ no, title, sub }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'baseline', gap: 12,
      borderBottom: '0.5px solid #1a1612', paddingBottom: 4, marginTop: 8,
    }}>
      <div style={{
        fontFamily: '"Noto Serif JP", serif', fontSize: 14, color: '#8b2920',
        width: 22, flexShrink: 0, letterSpacing: 1,
      }}>{no}</div>
      <div style={{ fontSize: 17, fontWeight: 500, letterSpacing: 2 }}>{title}</div>
      <div style={{
        fontSize: 11, color: '#6b5a3a', marginLeft: 'auto',
        fontFamily: '"Noto Sans JP", sans-serif',
      }}>{sub}</div>
    </div>
  );
}

function SpecTable({ rows }) {
  return (
    <div style={{
      border: '0.5px solid #1a1612', marginBottom: 22,
      fontSize: 12, fontFamily: '"Noto Sans JP", sans-serif',
    }}>
      {rows.map(([k, v], i) => (
        <div key={i} style={{
          display: 'flex', borderTop: i > 0 ? '0.5px solid #c4b593' : 'none',
        }}>
          <div style={{
            width: 72, padding: '8px 10px', background: '#ede3c7',
            borderRight: '0.5px solid #c4b593', color: '#6b5a3a',
            fontSize: 11, letterSpacing: 2,
          }}>{k}</div>
          <div style={{ flex: 1, padding: '8px 10px', lineHeight: 1.6 }}>{v}</div>
        </div>
      ))}
    </div>
  );
}

function LevelPicker({ level, onChange, variant }) {
  const levels = [
    { key: 'elementary', label: '小学', age: '7–12' },
    { key: 'jhs', label: '中学', age: '13–15' },
    { key: 'hs', label: '高校', age: '16–18' },
    { key: 'adult', label: '大人', age: '19+' },
  ];
  const accent = variant === 'museum' ? '#8b2920' : variant === 'notebook' ? '#5a6b4a' : '#1e3a5f';
  return (
    <div style={{
      display: 'flex', gap: 0, marginBottom: 22,
      border: `1px solid ${accent}`,
    }}>
      {levels.map((l, i) => {
        const active = l.key === level;
        return (
          <button key={l.key} onClick={() => onChange(l.key)} style={{
            flex: 1, padding: '8px 4px', border: 'none', cursor: 'pointer',
            background: active ? accent : 'transparent',
            color: active ? '#f4ecdc' : accent,
            borderLeft: i > 0 ? `0.5px solid ${accent}` : 'none',
            fontFamily: '"Noto Serif JP", serif', fontSize: 13, letterSpacing: 2,
          }}>
            <div>{l.label}</div>
            <div style={{
              fontFamily: 'ui-monospace, monospace', fontSize: 8,
              letterSpacing: 1, opacity: 0.7, marginTop: 1,
            }}>{l.age}</div>
          </button>
        );
      })}
    </div>
  );
}

function StickyHeader({ variant, onClose, subject }) {
  const bg = '#f4ecdc';
  const sendToManabiya = () => {
    const img = subject?.__image || subject?.thumb;
    const caption = subject?.name || '写真';
    if (!img || typeof img !== 'string' || !img.startsWith('data:')) {
      alert('写真データがありません'); return;
    }
    shrinkForManabiya(img).then(small => {
      const url = (window.MANABIYA_URL || 'https://manabiya.pages.dev/')
        + '?photo=' + encodeURIComponent(small)
        + '&caption=' + encodeURIComponent(caption);
      let opened = null;
      try { opened = window.open(url, '_blank'); } catch {}
      if (!opened) window.location.href = url;
    });
  };
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 5, background: bg,
      padding: '10px 16px 4px', display: 'flex',
      alignItems: 'center', justifyContent: 'space-between',
      borderBottom: '0.5px solid #c4b593',
    }}>
      <div style={{ width: 40, height: 4, background: '#c4b593', borderRadius: 2,
        margin: '0 auto', position: 'absolute', left: '50%', top: 6,
        transform: 'translateX(-50%)',
      }}/>
      <button onClick={onClose} style={{
        background: 'none', border: 'none', cursor: 'pointer',
        fontFamily: 'ui-monospace, monospace', fontSize: 11, letterSpacing: 2,
        color: '#1a1612', padding: '8px 0',
      }}>← 撮る</button>
      {subject ? (
        <button onClick={sendToManabiya} title="まなびや家庭教師で掘る" style={{
          background: '#1a1612', color: '#f4ecdc',
          border: 'none', cursor: 'pointer',
          fontFamily: 'ui-monospace, monospace', fontSize: 10, letterSpacing: 2,
          padding: '6px 12px', borderRadius: 999,
        }}>まなびやへ</button>
      ) : (
        <div style={{
          fontFamily: 'ui-monospace, monospace', fontSize: 10, letterSpacing: 2,
          color: '#6b5a3a',
        }}>ENTRY</div>
      )}
    </div>
  );
}

async function shrinkForManabiya(dataUrl) {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      let edge = 240, q = 0.55;
      const attempt = () => {
        const c = document.createElement('canvas');
        const scale = Math.min(1, edge / Math.max(img.width, img.height));
        c.width = Math.round(img.width * scale);
        c.height = Math.round(img.height * scale);
        c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
        const out = c.toDataURL('image/jpeg', q);
        if (out.length < 10000 || edge <= 120) return resolve(out);
        edge = Math.round(edge * 0.8); q = Math.max(0.4, q - 0.05);
        attempt();
      };
      attempt();
    };
    img.onerror = () => resolve(dataUrl);
    img.src = dataUrl;
  });
}
window.shrinkForManabiya = shrinkForManabiya;

window.MuseumResult = MuseumResult;
window.SectionTitle = SectionTitle;
window.LevelPicker = LevelPicker;
window.StickyHeader = StickyHeader;
window.SpecTable = SpecTable;

// Shared tone toggle — formal (educational) vs casual (friendly).
function ToneToggle({ tone, onChange, variant }) {
  const accent = variant === 'museum' ? '#8b2920' : variant === 'notebook' ? '#5a6b4a' : '#1e3a5f';
  const options = [
    { key: 'formal',  label: 'かしこまる', sub: 'Formal' },
    { key: 'casual',  label: 'ざっくばらん', sub: 'Casual' },
  ];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14,
      fontFamily: '"Noto Serif JP", serif',
    }}>
      <div style={{
        fontFamily: 'ui-monospace, monospace', fontSize: 10, letterSpacing: 2,
        color: accent, flexShrink: 0,
      }}>TONE</div>
      <div style={{ display: 'flex', border: `0.5px solid ${accent}`, flex: 1 }}>
        {options.map((o, i) => {
          const active = o.key === tone;
          return (
            <button key={o.key} onClick={() => onChange(o.key)} style={{
              flex: 1, padding: '6px 8px', border: 'none', cursor: 'pointer',
              background: active ? accent : 'transparent',
              color: active ? '#f4ecdc' : accent,
              borderLeft: i > 0 ? `0.5px solid ${accent}` : 'none',
              fontFamily: 'inherit', fontSize: 12, letterSpacing: 1,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>
              <span>{o.label}</span>
              <span style={{
                fontFamily: 'ui-monospace, monospace', fontSize: 8,
                letterSpacing: 1, opacity: 0.7,
              }}>{o.sub}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}
window.ToneToggle = ToneToggle;
