/* global React, window */
const { NOTES, Sketch, FieldLine, CoordStrip } = window;

/* split body into paragraphs / blockquotes / inline stamps */
function renderBlocks(body) {
  if (!body) return null;
  return body.split("\n\n").map((b, i) => {
    if (b.startsWith("> ")) return <blockquote key={i}>{b.slice(2)}</blockquote>;
    const m = b.trim().match(/^\{\{sketch:([a-z]+)\}\}$/);
    if (m) {
      return (
        <div key={i} style={{ margin: '28px 0', display: 'flex', justifyContent: 'center' }}>
          <Sketch kind={m[1]} height={180} />
        </div>
      );
    }
    /* paragraph that may contain inline {{sketch:x}} markers */
    if (/\{\{sketch:[a-z]+\}\}/.test(b)) {
      const parts = b.split(/(\{\{sketch:[a-z]+\}\})/g);
      return (
        <p key={i}>
          {parts.map((p, j) => {
            const mm = p.match(/^\{\{sketch:([a-z]+)\}\}$/);
            if (mm) return <span key={j} style={{ display: 'inline-block', verticalAlign: 'middle', margin: '0 8px' }}><Sketch kind={mm[1]} height={90} /></span>;
            return <span key={j}>{p}</span>;
          })}
        </p>
      );
    }
    return <p key={i}>{b}</p>;
  });
}

function NotePage({ id, go }) {
  /* Look up first in saved field-desk entries (id like "field-…"), then seeded NOTES */
  const saved = (window.LGStore?.list("entries") || []).find(e => e.id === id);
  const seedNote = NOTES.find(n => n.id === id);
  const isSaved = !!saved;
  const note = isSaved
    ? {
        ...saved,
        no: "FN-" + (saved.id || "").slice(-3).toUpperCase(),
        category: saved.category || "Field Note",
        excerpt: saved.preview || (saved.body ? saved.body.slice(0, 160) + "…" : ""),
        location: saved.location || "n/a",
        coords: saved.coords || "n/a",
        weather: saved.weather || "n/a",
        wordCount: (saved.wordCount != null)
          ? saved.wordCount
          : (saved.body ? saved.body.split(/\s+/).filter(Boolean).length : 0),
        tags: saved.tags || [],
        body: saved.body || "",
      }
    : (seedNote || NOTES[0]);

  const idx = NOTES.findIndex(n => n.id === note.id);
  const next = idx >= 0 ? NOTES[(idx + 1) % NOTES.length] : NOTES[0];
  const prev = idx >= 0 ? NOTES[(idx - 1 + NOTES.length) % NOTES.length] : NOTES[NOTES.length - 1];

  // Render the user's actual writing. For seed entries that don't have a
  // saved body, fall back to the excerpt so we always show *something*
  // intentional rather than canned filler.
  const blocks = renderBlocks(note.body || note.excerpt || "");

  return (
    <main>
      {/* Masthead */}
      <section className="container" style={{ paddingTop: 56, paddingBottom: 32 }}>
        <div onClick={() => go("notes")} style={{ display: 'inline-flex', gap: 10, alignItems: 'center', cursor: 'pointer', fontFamily: 'var(--f-mono)', fontSize: 11, letterSpacing: '0.3em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>
          ← Back to Goat Notes
        </div>
      </section>

      <section className="container" style={{ paddingBottom: 32 }}>
        <CoordStrip note={note} />
        <div style={{ marginTop: 18 }}>
          <span className="eyebrow" style={{ color: 'var(--clay)' }}>{note.category}</span>
        </div>
        <h1 className="display" style={{ fontSize: 'clamp(48px, 8vw, 120px)', lineHeight: 0.95, margin: '14px 0 24px', maxWidth: 1100 }}>
          {note.title}
        </h1>
        <p className="serif" style={{ fontStyle: 'italic', fontSize: 24, color: 'var(--ink-soft)', maxWidth: 760, lineHeight: 1.55, margin: 0 }}>
          {note.excerpt}
        </p>
      </section>

      {/* Optional hero photo — disposable-camera styling */}
      {note.heroImage && (
        <section className="container" style={{ paddingTop: 8, paddingBottom: 16 }}>
          <figure className="lg-hero-photo">
            <img src={note.heroImage} alt={note.title || ""} />
            {note.location && note.location !== "n/a" && (
              <figcaption>{note.location}</figcaption>
            )}
          </figure>
        </section>
      )}

      {/* Body — simplified two-column layout. Just the writing, the inline
          stamps the user dropped in, the field card, and the sign-off. */}
      <section className="container" style={{ paddingTop: 40, paddingBottom: 64 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 56 }} className="article-grid">
          {/* Field Card (left) */}
          <aside style={{ borderRight: '1px solid var(--rule)', paddingRight: 28 }}>
            <div className="eyebrow" style={{ marginBottom: 12 }}>Field Card</div>
            <FieldLine label="Date" value={note.date} />
            <FieldLine label="Loc." value={note.location} />
            <FieldLine label="Coord." value={note.coords} />
            <FieldLine label="Wx." value={note.weather} />
            <FieldLine
              label="Words"
              value={
                typeof note.wordCount === "number"
                  ? `${note.wordCount.toLocaleString()} words`
                  : "n/a"
              }
            />
            {note.tags && note.tags.length > 0 && (
              <div style={{ marginTop: 22, fontFamily: 'var(--f-mono)', fontSize: 10, letterSpacing: '0.3em', textTransform: 'uppercase', color: 'var(--ink-faint)' }}>
                tags
                <div style={{ marginTop: 10, color: 'var(--ink-soft)', lineHeight: 1.6, textTransform: 'none', letterSpacing: 0, fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontSize: 14 }}>
                  {note.tags.map(t => <div key={t}>· {t}</div>)}
                </div>
              </div>
            )}
          </aside>

          {/* The writing + the user's inline sketch stamps + sign-off */}
          <div className="prose">
            {blocks}
            <div style={{
              marginTop: 64,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'flex-end',
              paddingRight: 8
            }}>
              {/* "Stay Lonesome" — sits above the signature, shifted slightly
                  to the left of where Lonesome Goat ends. The leading mark is
                  a hand-drawn flourish (single SVG arc) instead of a hyphen. */}
              <span style={{
                fontFamily: '"Caveat", cursive',
                fontSize: 24,
                color: 'var(--ink-soft)',
                lineHeight: 1,
                display: 'inline-flex',
                alignItems: 'center',
                gap: 10,
                marginRight: 72,
                whiteSpace: 'nowrap'
              }}>
                <svg viewBox="0 0 56 12" width="46" height="10" aria-hidden="true" style={{ flexShrink: 0 }}>
                  <path d="M 2 8 Q 14 2 28 6 T 54 4"
                    fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
                </svg>
                <span>Stay Lonesome</span>
              </span>
              {/* The Lonesome Goat signature, full size, slight rotation */}
              <span style={{
                fontFamily: '"Homemade Apple", "Caveat", cursive',
                fontSize: 44,
                color: 'var(--ink)',
                display: 'inline-block',
                transform: 'rotate(-3deg)',
                transformOrigin: 'right center',
                lineHeight: 1,
                marginTop: 14,
                whiteSpace: 'nowrap'
              }}>
                Lonesome Goat
              </span>
            </div>
          </div>
        </div>
      </section>

      <hr className="rule rule--double" style={{ margin: '0 32px' }} />

      {/* Prev / Next */}
      <section className="container" style={{ paddingTop: 64, paddingBottom: 80 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48 }} className="prev-next">
          <article onClick={() => go("note:" + prev.id)} style={{ cursor: 'pointer', borderRight: '1px solid var(--rule)', paddingRight: 32 }}>
            <div className="eyebrow">← Previous Entry</div>
            <h3 className="display" style={{ fontSize: 32, margin: '12px 0 8px' }}>{prev.title}</h3>
            <p className="serif" style={{ fontStyle: 'italic', color: 'var(--ink-soft)' }}>{prev.location} · {prev.date}</p>
          </article>
          <article onClick={() => go("note:" + next.id)} style={{ cursor: 'pointer', textAlign: 'right' }}>
            <div className="eyebrow">Next Entry →</div>
            <h3 className="display" style={{ fontSize: 32, margin: '12px 0 8px' }}>{next.title}</h3>
            <p className="serif" style={{ fontStyle: 'italic', color: 'var(--ink-soft)' }}>{next.location} · {next.date}</p>
          </article>
        </div>
      </section>
    </main>
  );
}

window.NotePage = NotePage;
