// ============================================================
// Chapter I — The Crown is Hollow (current story)
// Chapter II — An Old World (world + map)
// ============================================================

const Cw = window.CAMPAIGN;

// -------- Divider --------
function Divider({ glyph = "✦ · ✦ · ✦" }) {
  return (
    <div className="divider">
      <span className="divider-glyph">{glyph}</span>
    </div>
  );
}

// -------- Pull Quote --------
function PullQuote({ children, attr }) {
  return (
    <div className="pullquote">
      <div>{children}</div>
      {attr && <span className="pullquote-attr">— {attr}</span>}
    </div>
  );
}

// ============================================================
// CHAPTER I — The Crown is Hollow
// ============================================================
function StoryChapter() {
  const s = Cw.currentStory;
  return (
    <section className="chapter" id="story">
      <div className="chapter-num">Section I</div>
      <h2 className="chapter-title">The First <em>Tax</em></h2>
      <p className="chapter-deck">
        Where the party stands, what is pressing on them, and the things watching from just outside the light.
      </p>

      <div className="story-grid">
        <div className="story-prose">
          <p>
            <Editable path="story.where" multiline>{s.where}</Editable>. <Editable path="story.summary.0" multiline>{s.summary[0]}</Editable>
          </p>
          {s.summary.slice(1).map((para, i) => (
            <Editable as="p" key={i + 1} path={`story.summary.${i + 1}`} multiline>{para}</Editable>
          ))}

          <DMBlock title="What's actually happening">
            {s.dmSummary.map((p, i) => <p key={i}>{p}</p>)}
          </DMBlock>
        </div>

        <aside className="story-sidebar">
          <div className="fact-tile">
            <div className="fact-tile-label">The quest, restated</div>
            <div className="fact-tile-value">{s.quest}</div>
          </div>

          <div className="threads-box">
            <div className="threads-label">Open threads</div>
            {s.threads.map((t, i) => (
              <div key={i} className="thread-row">
                <div className="thread-title">
                  <Editable path={`story.threads.${i}.title`}>{t.title}</Editable>
                </div>
                <Editable as="div" path={`story.threads.${i}.note`} multiline className="thread-note">{t.note}</Editable>
              </div>
            ))}
          </div>

          <DMBlock title="DM-only hooks">
            <ul>
              {s.dmHooks.map((h, i) => <li key={i}>{h}</li>)}
            </ul>
          </DMBlock>

          <DMBlock title="Next session prep">
            <p>{s.nextSession}</p>
          </DMBlock>
        </aside>
      </div>

      <PullQuote attr="Oswin Dray, not quite joking">
        "Town's fine. Always been fine."
      </PullQuote>
    </section>
  );
}

// ============================================================
// CHAPTER II — An Old World (world banner + regions + map)
// ============================================================
function WorldChapter() {
  const dm = window.useDM();
  const regions = Cw.world.regions.filter((r) => dm || !r.dmOnly);
  return (
    <>
      <section id="world">
        <div className="chapter" style={{paddingBottom: 60}}>
          <div className="chapter-num">Section II</div>
          <h2 className="chapter-title">An Old <em>World</em></h2>
          <p className="chapter-deck">
            Thoria. Old enough that the roads forgot who first walked them; ordinary enough that most people still worry more about grain than gods.
          </p>
        </div>

        <div className="world-banner">
          <div className="world-banner-inner">
            <div className="world-prose">
              <p style={{margin: 0}}>
                <Editable path="world.blurb" multiline>{Cw.world.blurb}</Editable>
              </p>
            </div>
            <div className="almanac">
              {Cw.world.facts.map((f, i) => (
                <div key={i} className="fact-tile">
                  <div className="fact-tile-label">{f.label}</div>
                  <div className="fact-tile-value">
                    <Editable path={`world.facts.${i}.value`}>{f.value}</Editable>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="chapter">
          <h3 className="chapter-title" style={{fontSize: "clamp(28px, 4vw, 44px)", marginBottom: 12}}>The Regions</h3>
          <p className="chapter-deck" style={{marginBottom: 32}}>Where the company has been, where they have not yet, and the corners of the map drawn in lighter ink.</p>
          <div className="region-grid">
            {regions.map((r, i) => (
              <div key={i} className="region-card">
                <h4 className="region-name">
                  <Editable path={`world.regions.${i}.name`}>{r.name}</Editable>
                </h4>
                <p className="region-desc">
                  <Editable path={`world.regions.${i}.desc`} multiline>{r.desc}</Editable>
                </p>
              </div>
            ))}
          </div>

          <DMBlock title="The truth of the kingdom">
            <p>{Cw.world.dmTruth}</p>
          </DMBlock>
        </div>
      </section>

      {/* Map section */}
      <section id="map">
        <div className="chapter chapter--wide">
          <div className="chapter-num">Cartography</div>
          <h2 className="chapter-title">The <em>Map</em></h2>
          <p className="chapter-deck">
            A working campaign map: approximate, symbolic, and good enough to get everyone into trouble. Click the pins.
          </p>
          <MapView />
        </div>
      </section>
    </>
  );
}

function MapView() {
  const dm = window.useDM();
  const [active, setActive] = useState(null);
  const visible = Cw.map.pins.filter((p) => dm || !p.dmOnly);

  const pinColor = (t) => ({
    capital: "#d05a5a", town: "#d4a857", village: "#6ba070",
    wilderness: "#4a7a55", hold: "#8a8a8a", ruin: "#7aa9d4", secret: "#b18fd9",
  }[t] || "#a8a395");

  return (
    <>
      <div className="map-wrap">
        <svg viewBox="0 0 1000 625" preserveAspectRatio="xMidYMid slice">
          <defs>
            <pattern id="hatch" patternUnits="userSpaceOnUse" width="6" height="6" patternTransform="rotate(45)">
              <line x1="0" y1="0" x2="0" y2="6" stroke="var(--text-fade)" strokeWidth="1" opacity="0.4"/>
            </pattern>
            <linearGradient id="seagrad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="var(--bg-rise)"/>
              <stop offset="100%" stopColor="var(--bg-deep)"/>
            </linearGradient>
          </defs>

          <rect width="1000" height="625" fill="url(#seagrad)"/>

          {/* Continent */}
          <path d="M 80,90 C 160,60 280,80 360,100 C 460,80 580,90 680,120 C 780,110 880,140 950,200 C 970,300 940,420 880,520 C 800,580 700,590 600,560 C 500,580 380,560 280,520 C 200,500 130,440 100,360 C 70,280 60,170 80,90 Z"
                fill="var(--bg-card)" stroke="var(--border-strong)" strokeWidth="1.5"/>

          {/* Mountains east */}
          <path d="M 760,160 L 820,200 L 880,180 L 920,240 L 870,290 L 810,260 L 760,290 L 720,250 Z"
                fill="var(--bg-card-2)" stroke="var(--border-strong)" strokeWidth="1"/>
          <g stroke="var(--text-dim)" strokeWidth="1.2" fill="none">
            <path d="M 770,200 l 12,-20 l 14,18"/>
            <path d="M 800,210 l 14,-26 l 18,22"/>
            <path d="M 840,200 l 12,-18 l 16,20"/>
            <path d="M 820,250 l 14,-20 l 14,18"/>
            <path d="M 860,260 l 12,-18 l 14,20"/>
          </g>
          <text x="840" y="158" fontFamily="Cormorant Garamond, serif" fontStyle="italic" fontSize="15" fill="var(--text-soft)" textAnchor="middle">Iron Reaches</text>

          {/* Forests west */}
          <g fill="var(--bg-card-2)" stroke="var(--border-strong)" strokeWidth="0.8">
            <circle cx="160" cy="220" r="14"/><circle cx="190" cy="200" r="11"/><circle cx="220" cy="225" r="13"/>
            <circle cx="180" cy="250" r="12"/><circle cx="240" cy="245" r="10"/><circle cx="150" cy="270" r="11"/>
            <circle cx="200" cy="285" r="13"/>
          </g>
          <text x="195" y="190" fontFamily="Cormorant Garamond, serif" fontStyle="italic" fontSize="14" fill="var(--text-soft)" textAnchor="middle">The Greenward</text>

          {/* Glasswolds north */}
          <g fill="var(--bg-card-2)" stroke="var(--azure)" strokeWidth="0.8" opacity="0.7">
            <polygon points="360,130 366,142 372,130 378,142 384,130"/>
            <polygon points="400,150 406,162 412,150 418,162 424,150"/>
            <polygon points="440,135 446,147 452,135 458,147 464,135"/>
            <polygon points="380,165 386,177 392,165 398,177 404,165"/>
            <polygon points="500,145 506,157 512,145 518,157 524,145"/>
          </g>
          <text x="450" y="118" fontFamily="Cormorant Garamond, serif" fontStyle="italic" fontSize="15" fill="var(--text-soft)" textAnchor="middle">The Glasswolds</text>

          {/* Marrowfens south */}
          <path d="M 480,490 C 540,470 620,485 680,510 C 720,540 700,570 640,565 C 580,575 520,560 480,540 Z"
                fill="url(#hatch)" stroke="var(--border-strong)" strokeWidth="1"/>
          <text x="580" y="540" fontFamily="Cormorant Garamond, serif" fontStyle="italic" fontSize="15" fill="var(--text-soft)" textAnchor="middle">The Marrowfens</text>

          {/* Sunder coast label */}
          <text x="790" y="450" fontFamily="Cormorant Garamond, serif" fontStyle="italic" fontSize="14" fill="var(--text-soft)" textAnchor="middle">Sunder Coast</text>

          {/* Sea wave decoration */}
          <g transform="translate(120, 540)" stroke="var(--text-fade)" strokeWidth="1" fill="none" opacity="0.4">
            <path d="M 0,0 q 10,-10 20,0 q 10,10 20,0 q 10,-10 20,0"/>
            <path d="M 0,8 q 10,-10 20,0 q 10,10 20,0 q 10,-10 20,0"/>
          </g>

          {/* Compass rose */}
          <g transform="translate(910, 540)">
            <circle cx="0" cy="0" r="22" fill="none" stroke="var(--text-dim)" strokeWidth="1"/>
            <polygon points="0,-22 4,0 0,22 -4,0" fill="var(--gold)"/>
            <polygon points="-22,0 0,4 22,0 0,-4" fill="var(--text-dim)"/>
            <text x="0" y="-28" fontSize="10" textAnchor="middle" fontFamily="JetBrains Mono" fill="var(--text-dim)">N</text>
          </g>

          {/* Title cartouche */}
          <g transform="translate(500, 50)">
            <text x="0" y="0" fontFamily="Cormorant Garamond, serif" fontSize="22" fontWeight="400" fill="var(--text-soft)" textAnchor="middle" fontStyle="italic">— Thoria · Act 1 —</text>
          </g>
        </svg>

        {visible.map((p) => (
          <button
            key={p.id}
            className={"map-pin" + (p.dmOnly ? " dm-pin" : "")}
            style={{ left: `${p.x}%`, top: `${p.y}%` }}
            onClick={() => setActive(p)}
            aria-label={p.name}
          >
            <svg viewBox="0 0 22 22" width="22" height="22" style={{display: "block"}}>
              <path d="M 11,1 C 16,1 19,5 19,9 C 19,13 11,21 11,21 C 11,21 3,13 3,9 C 3,5 6,1 11,1 Z"
                    fill={pinColor(p.type)} stroke="#fff" strokeWidth="1.5"/>
              <circle cx="11" cy="9" r="3" fill="#fff"/>
            </svg>
            <span className="map-pin-label">{p.name}</span>
          </button>
        ))}
      </div>

      <div className="map-legend">
        <span><i style={{background: "#d05a5a"}}></i>Capital</span>
        <span><i style={{background: "#d4a857"}}></i>Town</span>
        <span><i style={{background: "#6ba070"}}></i>Village</span>
        <span><i style={{background: "#8a8a8a"}}></i>Hold</span>
        <span><i style={{background: "#4a7a55"}}></i>Wilderness</span>
        <span><i style={{background: "#7aa9d4"}}></i>Ruin</span>
        {dm && <span><i style={{background: "#b18fd9", boxShadow: "0 0 6px #b18fd9"}}></i>DM only</span>}
      </div>

      {active && (
        <Modal onClose={() => setActive(null)}>
          <div className="modal-head">
            <div className="modal-portrait" style={{background: pinColor(active.type) + "22", color: pinColor(active.type), borderColor: pinColor(active.type)}}>✦</div>
            <div>
              <div className="modal-name">{active.name}</div>
              <div className="modal-meta">{active.type === "secret" ? "DM-only location" : active.type}</div>
            </div>
          </div>
          <div className="modal-body">
            <p className="lead">{active.desc}</p>
            {active.dmOnly && (
              <div className="dm-block">
                <h4>Hidden on the player map</h4>
                <p>This pin is visible only in DM view.</p>
              </div>
            )}
          </div>
        </Modal>
      )}
    </>
  );
}

Object.assign(window, { Divider, PullQuote, StoryChapter, WorldChapter });
