/* global React, useTweaks, TweaksPanel, TweakSection, TweakColor, TweakRadio, TweakToggle */
const { useState, useEffect, useCallback } = React;
const SITE = window.SITE;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "profundo",
  "display": "cormorant",
  "paperTexture": true
}/*EDITMODE-END*/;

const DISPLAY_FONTS = {
  cormorant: "'Cormorant Garamond', Georgia, serif",
  playfair:  "'Playfair Display', Georgia, serif",
  lora:      "'Lora', Georgia, serif"
};

const ACCENTS = {
  profundo: "#0f3f5c",
  marea:    "#115e63",
  niebla:   "#3a5566"
};
const accentToKey = (hex) =>
  hex === ACCENTS.marea ? "marea" : hex === ACCENTS.niebla ? "niebla" : "profundo";

/* ---------- Ornamento (ola) ---------- */
function Ornament() {
  return (
    <div className="ornament">
      <span className="line left"></span>
      <svg className="wave" width="36" height="10" viewBox="0 0 36 10" fill="none" aria-hidden="true">
        <path d="M1 5 C 4.5 0.8, 9.5 0.8, 13 5 S 21.5 9.2, 25 5 S 31.5 1.2, 35 5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" />
      </svg>
      <span className="line"></span>
    </div>
  );
}

/* ---------- Olas al pie de la portada ---------- */
function HomeWaves() {
  return (
    <svg className="home-waves" viewBox="0 0 1440 130" preserveAspectRatio="none" aria-hidden="true">
      <path d="M0 70 C 240 30, 480 110, 720 70 S 1200 30, 1440 70 L1440 130 L0 130 Z" fill="currentColor" opacity="0.06" />
      <path d="M0 92 C 260 58, 520 124, 720 92 S 1180 58, 1440 92 L1440 130 L0 130 Z" fill="currentColor" opacity="0.09" />
      <path d="M0 110 C 280 84, 540 134, 720 110 S 1200 86, 1440 110 L1440 130 L0 130 Z" fill="currentColor" opacity="0.13" />
    </svg>
  );
}

/* ---------- Header ---------- */
function Header({ view, go }) {
  if (view === "home") return null;
  return (
    <header className="site-header">
      <button className="site-mark" onClick={() => go("home")}>
        Mis <span className="amp">Reflexiones</span>
      </button>
      <nav className="site-nav">
        <button className={"nav-link" + (view === "library" || view === "story" ? " active" : "")} onClick={() => go("library")}>Biblioteca</button>
        <button className={"nav-link" + (view === "about" ? " active" : "")} onClick={() => go("about")}>El proyecto</button>
      </nav>
    </header>
  );
}

/* ---------- Inicio ---------- */
function Home({ go }) {
  return (
    <section className="view home">
      <div className="home-inner">
        <Ornament />
        <h1 className="home-title">Mis Reflexiones</h1>
        <p className="home-sub">{SITE.subtitle}</p>
        <p className="home-intro">{SITE.intro}</p>
        <div className="home-cta">
          <button className="btn" onClick={() => go("library")}>{SITE.ctaLabel || "Entrar a la biblioteca"}</button>
        </div>
        <p className="home-foot">
          <span className="link-quiet" onClick={() => go("about")}>Sobre este proyecto</span>
        </p>
      </div>
      <HomeWaves />
    </section>
  );
}

/* ---------- Biblioteca ---------- */
function StatusBadge({ status }) {
  const pub = status === "publicado";
  return <span className={"status " + (pub ? "pub" : "proc")}>{pub ? "Publicado" : "En proceso"}</span>;
}

function StoryCard({ story, open }) {
  return (
    <article className="story-card" onClick={() => open(story.id)}>
      <div className="card-top">
        <span className="theme-tag">{story.theme}</span>
        <StatusBadge status={story.status} />
      </div>
      <h3 className="card-title">{story.title}</h3>
      <p className="card-desc">{story.desc}</p>
      <span className="card-read">Leer <span className="arrow">→</span></span>
    </article>
  );
}

function Collection({ collection, stories, open }) {
  if (!stories.length) return null;
  return (
    <section className="collection">
      <div className="collection-head">
        <h3 className="collection-title">{collection.title}</h3>
        <p className="collection-desc">{collection.desc}</p>
        <span className="collection-count">{stories.length} {stories.length === 1 ? "cuento" : "cuentos"}</span>
      </div>
      <div className="library-grid">
        {stories.map((s) => <StoryCard key={s.id} story={s} open={open} />)}
      </div>
    </section>
  );
}

function Library({ open }) {
  return (
    <section className="view page">
      <div className="page-head">
        <Ornament />
        <h2 className="page-title">Biblioteca</h2>
        <p className="page-lede">Cuentos, cartas y procesos para leer despacio.</p>
      </div>
      {SITE.collections.map((c) => (
        <Collection
          key={c.id}
          collection={c}
          stories={SITE.stories.filter((s) => s.collection === c.id)}
          open={open}
        />
      ))}
    </section>
  );
}

/* ---------- Hash routing (enlaces compartibles) ---------- */
function parseHash() {
  const h = (window.location.hash || "").replace(/^#\/?/, "");
  const parts = h.split("/").filter(Boolean);
  if (parts[0] === "cuento" && parts[1]) {
    const found = SITE.stories.find((s) => s.id === decodeURIComponent(parts[1]));
    if (found) return { view: "story", storyId: found.id };
  }
  if (parts[0] === "biblioteca") return { view: "library", storyId: null };
  if (parts[0] === "proyecto") return { view: "about", storyId: null };
  if (parts[0] === "inicio") return { view: "home", storyId: null };
  return null;
}
function hashFor(view, storyId) {
  if (view === "story" && storyId) return "#/cuento/" + encodeURIComponent(storyId);
  if (view === "library") return "#/biblioteca";
  if (view === "about") return "#/proyecto";
  return "#/inicio";
}

/* ---------- Página de cuento ---------- */
function Story({ story, go, open }) {
  const [copied, setCopied] = useState(false);
  const idx = SITE.stories.findIndex((s) => s.id === story.id);
  const next = SITE.stories[(idx + 1) % SITE.stories.length];
  const col = SITE.collections.find((c) => c.id === story.collection);

  const share = useCallback(async () => {
    const url = window.location.origin + window.location.pathname + hashFor("story", story.id);
    const shareData = { title: story.title + " · Mis Reflexiones", text: story.title, url };
    try {
      if (navigator.share) { await navigator.share(shareData); return; }
    } catch (e) { /* el usuario canceló: caemos a copiar */ }
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 2400);
    } catch (e) {
      window.prompt("Copia este enlace para compartir el cuento:", url);
    }
  }, [story.id, story.title]);

  return (
    <section className="view page" style={{ "--max": "var(--read-w)" }}>
      <article className="story">
        <button className="story-back" onClick={() => go("library")}>← Volver a la biblioteca</button>
        <div className="story-meta">
          {col && <div className="story-collection">{col.title}</div>}
          <span className="theme-tag">{story.theme}</span>
        </div>
        <h1 className="story-title">{story.title}</h1>
        <blockquote className="epigraph">
          “{story.epigraph}”
          <cite>{story.epigraphCite}</cite>
        </blockquote>
        <Ornament />
        <div className="story-body">
          {story.body.map((p, i) => <p key={i}>{p}</p>)}
        </div>
        <div className="reflection">
          <div className="reflection-label"><span className="eyebrow">Reflexión final</span></div>
          {story.reflection.map((p, i) => <p key={i}>{p}</p>)}
        </div>
        <div className="story-share">
          <button className={"share-btn" + (copied ? " copied" : "")} onClick={share}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <circle cx="18" cy="5" r="3"></circle><circle cx="6" cy="12" r="3"></circle><circle cx="18" cy="19" r="3"></circle>
              <line x1="8.6" y1="10.5" x2="15.4" y2="6.5"></line><line x1="8.6" y1="13.5" x2="15.4" y2="17.5"></line>
            </svg>
            {copied ? "Enlace copiado" : "Compartir este cuento"}
          </button>
          <span className="share-hint">Se compartirá solo este cuento, no toda la biblioteca.</span>
        </div>
        <div className="story-nav">
          <button className="btn btn-ghost" onClick={() => go("library")}>← Biblioteca</button>
          <div className="next-wrap">
            <div className="nav-cap">Siguiente cuento</div>
            <button className="nav-name" onClick={() => open(next.id)}>{next.title} →</button>
          </div>
        </div>
      </article>
    </section>
  );
}

/* ---------- Sobre el proyecto ---------- */
function About() {
  const a = SITE.about;
  return (
    <section className="view page" style={{ "--max": "var(--read-w)" }}>
      <div className="about">
        <div className="page-head">
          <Ornament />
          <h2 className="page-title">Sobre este proyecto</h2>
        </div>
        <div className="about-body">
          {[a.lead, ...a.paragraphs].map((p, i) => (
            <p key={i}>
              {p.split("\n").map((line, j) => (
                <React.Fragment key={j}>{j > 0 ? <br /> : null}{line}</React.Fragment>
              ))}
            </p>
          ))}
        </div>
        <div className="signature">
          <Ornament />
          <div className="name" style={{ marginTop: 22 }}>{a.name}</div>
          <div className="role">{a.role}</div>
        </div>
      </div>
    </section>
  );
}

/* ---------- App ---------- */
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useState("home");
  const [storyId, setStoryId] = useState(SITE.stories[0].id);

  useEffect(() => {
    const r = document.documentElement;
    r.setAttribute("data-accent", t.accent);
    r.style.setProperty("--font-display", DISPLAY_FONTS[t.display] || DISPLAY_FONTS.cormorant);
    r.style.setProperty("--paper-texture", t.paperTexture ? "1" : "0");
  }, [t.accent, t.display, t.paperTexture]);

  // Al cargar: el enlace (hash) manda; si no hay, restaura la última posición guardada.
  useEffect(() => {
    const fromHash = parseHash();
    if (fromHash) {
      setView(fromHash.view);
      if (fromHash.storyId) setStoryId(fromHash.storyId);
      return;
    }
    try {
      const saved = JSON.parse(localStorage.getItem("mr_nav") || "{}");
      if (saved.view) setView(saved.view);
      if (saved.storyId) setStoryId(saved.storyId);
    } catch (e) {}
  }, []);

  // Reaccionar a cambios del hash (botones atrás/adelante, enlace pegado).
  useEffect(() => {
    const onHash = () => {
      const fromHash = parseHash();
      if (!fromHash) return;
      setView(fromHash.view);
      if (fromHash.storyId) setStoryId(fromHash.storyId);
      window.scrollTo({ top: 0, behavior: "auto" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Mantener URL + localStorage sincronizados con la vista actual.
  useEffect(() => {
    const want = hashFor(view, storyId);
    if (window.location.hash !== want) {
      try { history.replaceState(null, "", want); } catch (e) { window.location.hash = want; }
    }
    try { localStorage.setItem("mr_nav", JSON.stringify({ view, storyId })); } catch (e) {}
  }, [view, storyId]);

  const go = useCallback((v) => {
    setView(v);
    window.scrollTo({ top: 0, behavior: "auto" });
  }, []);
  const open = useCallback((id) => {
    setStoryId(id);
    setView("story");
    window.scrollTo({ top: 0, behavior: "auto" });
  }, []);

  const story = SITE.stories.find((s) => s.id === storyId) || SITE.stories[0];

  let content;
  if (view === "library") content = <Library open={open} />;
  else if (view === "story") content = <Story story={story} go={go} open={open} />;
  else if (view === "about") content = <About />;
  else content = <Home go={go} />;

  return (
    <React.Fragment>
      <Header view={view} go={go} />
      <main key={view + storyId}>{content}</main>

      <TweaksPanel>
        <TweakSection label="Paleta del mar" />
        <TweakColor
          label="Tono"
          value={ACCENTS[t.accent] || ACCENTS.profundo}
          options={[ACCENTS.profundo, ACCENTS.marea, ACCENTS.niebla]}
          onChange={(v) => setTweak("accent", accentToKey(v))}
        />
        <TweakSection label="Tipografía" />
        <TweakRadio
          label="Títulos"
          value={t.display}
          options={["cormorant", "playfair", "lora"]}
          onChange={(v) => setTweak("display", v)}
        />
        <TweakSection label="Textura" />
        <TweakToggle
          label="Luz en el agua"
          value={t.paperTexture}
          onChange={(v) => setTweak("paperTexture", v)}
        />
      </TweaksPanel>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
