/* global React */
/* DocumentPreview — renders a SOP doc faithfully to the Google Doc reference. */

const { useMemo: useMemoDP } = React;

/* ---- inline rich-text: **bold** + paragraphs + bullets ---- */
function renderRichText(text, key = "rt") {
  if (!text) return null;
  const lines = String(text).split(/\n/);
  const nodes = [];
  let buf = [];   // paragraph buffer (string lines)
  let listBuf = []; // bullet buffer (string lines)
  let idx = 0;

  const flushPara = () => {
    if (!buf.length) return;
    const txt = buf.join(" ").trim();
    if (txt) {
      nodes.push(<p key={`${key}-p-${idx++}`} className="lead">{renderInlineBold(txt)}</p>);
    }
    buf = [];
  };
  const flushList = () => {
    if (!listBuf.length) return;
    nodes.push(
      <ul key={`${key}-ul-${idx++}`}>
        {listBuf.map((l, i) => <li key={i}>{renderInlineBold(l)}</li>)}
      </ul>
    );
    listBuf = [];
  };

  for (const raw of lines) {
    const line = raw.trim();
    if (!line) {
      flushList();
      flushPara();
      continue;
    }
    const bullet = line.match(/^[•\-\*]\s+(.*)$/);
    if (bullet) {
      flushPara();
      listBuf.push(bullet[1]);
    } else {
      flushList();
      buf.push(line);
    }
  }
  flushList();
  flushPara();
  return nodes;
}

function renderInlineBold(s) {
  const parts = String(s).split(/(\*\*[^*]+\*\*)/g);
  return parts.map((p, i) => {
    const m = p.match(/^\*\*(.+)\*\*$/);
    if (m) return <strong key={i}>{m[1]}</strong>;
    return <React.Fragment key={i}>{p}</React.Fragment>;
  });
}

/* ---- date formatter (preserves YYYY-MM-DD) ---- */
function fmtDate(d) {
  if (!d) return "";
  // Already YYYY-MM-DD? keep as-is to match the reference.
  if (/^\d{4}-\d{2}-\d{2}$/.test(d)) return d;
  return d;
}

function SectionH2({ children, num }) {
  return (
    <h2 className="sop-doc__h2">
      {num != null && <span style={{ color: "var(--doc-fg)", opacity: 0.55, marginRight: 8, fontWeight: 700 }}>{num}.</span>}
      {children}
    </h2>
  );
}

function DocumentPreview({ doc }) {
  const hasIntro = !!(doc.intro && doc.intro.trim());
  const hasObjective = !!(doc.objective && doc.objective.trim());
  const hasScope = !!(doc.scope && doc.scope.trim());
  const hasFlow = doc.flow && doc.flow.filter(s => s && s.trim()).length > 0;
  const hasRoles = doc.roles && doc.roles.some(r => r.name || r.desc);
  const hasResources = doc.resources && doc.resources.some(r => r.name || r.desc);
  const hasPhases = doc.phases && doc.phases.some(p => p.title || (p.steps && p.steps.some(s => s.title || s.body)));
  const hasDefs = doc.definitions && doc.definitions.some(d => d.term || d.meaning);
  const hasRefs = doc.references && doc.references.some(r => r.term || r.meaning);

  // Section auto-numbering (matches user's outline)
  let secNum = 0;
  const nextNum = () => ++secNum;

  return (
    <article className="sop-doc">
      {/* ----- COVER ----- */}
      <header className="sop-doc__cover">
        <img
          src="assets/wordmark-teal.png"
          alt="Ads&Law"
          className="sop-doc__cover-logo"
        />
        <h1 className="sop-doc__title">{doc.title || <span className="sop-doc__empty">Sin título — añade un título arriba</span>}</h1>
        <p className="sop-doc__meta">
          Versión {doc.version || "1.0"}
          <span className="sop-doc__meta-sep">·</span>
          {fmtDate(doc.date) || "—"}
        </p>
      </header>

      {/* ----- INTRO ----- */}
      {hasIntro && <div>{renderRichText(doc.intro, "intro")}</div>}

      {/* ----- OBJECTIVE + SCOPE (inline lead-style, matches reference) ----- */}
      {(hasObjective || hasScope) && (
        <div style={{ margin: "10px 0 4px" }}>
          {hasObjective && (
            <p className="lead"><strong>Objetivo.</strong> {doc.objective}</p>
          )}
          {hasScope && (
            <p className="lead"><strong>Alcance.</strong> {doc.scope}</p>
          )}
        </div>
      )}

      {/* ----- RESUMEN DEL FLUJO ----- */}
      {hasFlow && (
        <>
          <h2 className="sop-doc__h2">Resumen del flujo</h2>
          <div className="sop-doc__flow">
            {doc.flow.filter(Boolean).map((step, i, arr) => (
              <React.Fragment key={i}>
                <div className="sop-doc__flow-row">
                  <span className="sop-doc__flow-num">{i + 1}.</span>
                  <span className="sop-doc__flow-text">{step}</span>
                </div>
                {i < arr.length - 1 && <div className="sop-doc__flow-arrow">↓</div>}
              </React.Fragment>
            ))}
          </div>
        </>
      )}

      {/* ----- ROLES ----- */}
      {hasRoles && (() => { const n = nextNum(); return (
        <>
          <SectionH2 num={n}>Roles y responsabilidades</SectionH2>
          {doc.roles.filter(r => r.name || r.desc).map(r => (
            <div key={r.id} className="sop-doc__role">
              <div className="sop-doc__role-name">{r.name}</div>
              <div className="sop-doc__role-desc">{r.desc}</div>
            </div>
          ))}
        </>
      ); })()}

      {/* ----- RESOURCES ----- */}
      {hasResources && (() => { const n = nextNum(); return (
        <>
          <SectionH2 num={n}>Recursos y herramientas</SectionH2>
          {doc.resources.filter(r => r.name || r.desc).map(r => (
            <div key={r.id} className="sop-doc__resource">
              <div className="sop-doc__resource-name">{r.name}</div>
              <div className="sop-doc__resource-desc">{r.desc}</div>
            </div>
          ))}
        </>
      ); })()}

      {/* ----- PROCEDURE ----- */}
      {hasPhases && (() => { const n = nextNum(); return (
        <>
          <SectionH2 num={n}>Procedimiento paso a paso</SectionH2>
          {doc.phases.map(phase => {
            const hasContent = phase.title || (phase.steps && phase.steps.some(s => s.title || s.body));
            if (!hasContent) return null;
            return (
              <div key={phase.id} className="sop-doc__phase">
                <div className="sop-doc__phase-title">
                  <span className="sop-doc__phase-tag">Fase {phase.num}</span>
                  <span>{phase.title}</span>
                </div>
                {(phase.steps || []).filter(s => s.title || s.body || (s.substeps && s.substeps.length)).map(step => (
                  <div key={step.id} className="sop-doc__step">
                    <div className="sop-doc__step-head">
                      <span className="sop-doc__step-num">
                        {step.done && <span className="sop-doc__check sop-doc__check--done" />}
                        Paso {step.num}
                      </span>
                      <span className="sop-doc__step-title">{step.title}</span>
                      {step.time && (
                        <span className="sop-doc__step-meta">· {step.time}</span>
                      )}
                    </div>
                    {step.body && (
                      <div className="sop-doc__step-body">
                        {renderRichText(step.body, `step-${step.id}`)}
                      </div>
                    )}
                    {step.image && (
                      <figure className="sop-doc__step-img">
                        <img src={step.image} alt="" />
                      </figure>
                    )}
                    {step.substeps && step.substeps.filter(ss => ss.text).map(ss => (
                      <div key={ss.id} className="sop-doc__substep">
                        <span className="sop-doc__substep-num">{ss.num}.</span>
                        <span className="sop-doc__substep-text">{ss.text}</span>
                      </div>
                    ))}
                  </div>
                ))}
              </div>
            );
          })}
        </>
      ); })()}

      {/* ----- DEFINITIONS ----- */}
      {hasDefs && (() => { const n = nextNum(); return (
        <>
          <SectionH2 num={n}>Definiciones</SectionH2>
          {doc.definitions.filter(d => d.term || d.meaning).map(d => (
            <div key={d.id} className="sop-doc__def">
              <div className="sop-doc__def-term">{d.term}</div>
              <div className="sop-doc__def-meaning">{d.meaning}</div>
            </div>
          ))}
        </>
      ); })()}

      {/* ----- REFERENCES ----- */}
      {hasRefs && (() => { const n = nextNum(); return (
        <>
          <SectionH2 num={n}>Referencias</SectionH2>
          {doc.references.filter(r => r.term || r.meaning).map(r => (
            <div key={r.id} className="sop-doc__def">
              <div className="sop-doc__def-term">{r.term}</div>
              <div className="sop-doc__def-meaning">{r.meaning}</div>
            </div>
          ))}
        </>
      ); })()}

      {/* ----- empty state ----- */}
      {!hasIntro && !hasObjective && !hasScope && !hasFlow && !hasRoles && !hasResources && !hasPhases && !hasDefs && !hasRefs && (
        <p className="sop-doc__empty">
          Empieza rellenando los campos en el panel de la izquierda — el documento se actualizará aquí en tiempo real. Si tienes notas en bruto, pulsa <strong>Estructurar con IA</strong> y la app te lo organiza.
        </p>
      )}

      {/* ----- FOOTER ----- */}
      <div className="sop-doc__footer">
        <span className="sop-doc__footer-mark">Ads&amp;Law</span>
        <span>SOP · {doc.title ? doc.title.slice(0, 60) : "Sin título"} · v{doc.version || "1.0"}</span>
      </div>
    </article>
  );
}

window.DocumentPreview = DocumentPreview;
