// concept-read.jsx — Clean reading mode. Essence at top as conclusion.
// Perspectives grouped visually under their patterns.

function ConceptRead({ concept, allConcepts = [], onSwitchMode, onBack, onOpenSolar, onOpenConcept, onOpenGraph }) {
  const c = concept;

  // Build the grouped view: essences → patterns → perspectives.
  const groups = c.essences.map(e => ({
    essence: e,
    patterns: c.patterns
      .filter(p => p.essenceId === e.id)
      .map(p => ({ pattern: p, perspectives: c.perspectives.filter(x => x.patternId === p.id) }))
  }));
  const orphanPatterns = c.patterns
    .filter(p => !p.essenceId)
    .map(p => ({ pattern: p, perspectives: c.perspectives.filter(x => x.patternId === p.id) }));
  const soloPerspectives = c.perspectives.filter(p => !p.patternId);

  return (
    <div className="page" data-screen-label="Concept · Read" style={{ maxWidth: 760 }}>
      <div className="view-toolbar" style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 36 }}>
        <button className="btn ghost tiny" onClick={onBack}>{window.Icons.ArrowL(13)} Library</button>
        <div style={{ flex: 1 }} />
        <div className="view-mode-sw" style={{ display: "flex", gap: 4, background: "var(--bg-sunk)", padding: 3, borderRadius: 9, border: "1px solid var(--border-soft)" }}>
          <button className="btn tiny" style={modeStyle(false)} onClick={() => onSwitchMode("edit")}>{window.Icons.Edit(13)} Edit</button>
          <button className="btn tiny" style={modeStyle(true)}>{window.Icons.Eye(13)} Read</button>
          <button className="btn tiny" style={modeStyle(false)} onClick={onOpenSolar}>{window.Icons.Planet(13)} System</button>
          <button className="btn tiny" style={modeStyle(false)} onClick={onOpenGraph}>{window.Icons.Graph(13)} Graph</button>
        </div>
      </div>

      <div className="tag-flat" style={{ marginBottom: 14 }}>{c.category}</div>
      <h1 className="concept-title cr-title" style={{ fontSize: 96, margin: "0 0 36px", lineHeight: 0.95 }}>{c.title}</h1>

      {/* Essence as the headline conclusion */}
      {c.essences.length > 0 && (
        <div style={{ marginBottom: 56, paddingLeft: 18, borderLeft: "2px solid var(--c-essence)" }}>
          <div className="tag-flat" style={{ marginBottom: 10, color: "var(--c-essence)" }}>Essence</div>
          {c.essences.map(e => (
            <p key={e.id} style={{
              fontFamily: "var(--font-serif)",
              fontSize: 34, lineHeight: 1.25, color: "var(--fg)", margin: "0 0 14px",
              fontStyle: "italic"
            }}>
              {e.body || <span style={{ color: "var(--fg-3)" }}>(no essence yet)</span>}
            </p>
          ))}
        </div>
      )}

      {/* Consist + Function — quiet constants */}
      {(() => {
        const fns = (c.functions && c.functions.length > 0) ? c.functions : (c.function ? [{ id: "f0", body: c.function }] : []);
        const hasManyFns = fns.filter(f => f.body).length > 1;
        return (
          <div className="cr-const-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, marginBottom: 48 }}>
            <Block label="Consist" body={c.consist} kind="constant" />
            {hasManyFns ? (
              <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                {fns.filter(f => f.body).map((fn, i) => (
                  <Block key={fn.id} label={i === 0 ? "Function" : `Function ${i + 1}`} body={fn.body} kind="function" />
                ))}
              </div>
            ) : (
              <Block label="Function" body={fns[0]?.body || c.function} kind="function" />
            )}
          </div>
        );
      })()}

      {/* Grouped perspectives */}
      {groups.length === 0 && orphanPatterns.length === 0 && soloPerspectives.length === 0 && c.essences.length === 0 && (
        <p style={{ color: "var(--fg-3)", fontStyle: "italic", fontFamily: "var(--font-serif)", fontSize: 22 }}>
          This concept has no body yet. Switch to Edit and begin.
        </p>
      )}

      {groups.map(({ essence, patterns }, gi) => (
        <div key={essence.id} style={{ marginBottom: 56 }}>
          {gi > 0 && <hr className="rule" style={{ marginBottom: 36 }} />}
          {patterns.length > 0 && patterns.map(({ pattern, perspectives }, pi) => (
            <PatternBlock key={pattern.id} pattern={pattern} perspectives={perspectives} style={{ marginBottom: pi < patterns.length - 1 ? 32 : 0 }} />
          ))}
        </div>
      ))}

      {orphanPatterns.length > 0 && (
        <div style={{ marginBottom: 56 }}>
          <div className="solo-mark" style={{ marginBottom: 14 }}>· patterns not yet leading to essence</div>
          {orphanPatterns.map(({ pattern, perspectives }) => (
            <div key={pattern.id} style={{ opacity: 0.85 }}>
              <PatternBlock pattern={pattern} perspectives={perspectives} solo style={{ marginBottom: 32 }} />
            </div>
          ))}
        </div>
      )}

      {soloPerspectives.length > 0 && (
        <div style={{ marginBottom: 56 }}>
          <div className="solo-mark" style={{ marginBottom: 14 }}>· solo perspectives — not grouped, kept honest</div>
          <div style={{ display: "grid", gap: 16, paddingLeft: 14, borderLeft: "1px dashed var(--c-perspective)" }}>
            {soloPerspectives.map(p => <PerspectiveBlock key={p.id} p={p} solo />)}
          </div>
        </div>
      )}

      {/* Connections */}
      {allConcepts.length > 1 && (
        <div style={{ marginTop: 48 }}>
          <window.MiniGraph concept={c} allConcepts={allConcepts} onOpen={onOpenConcept} />
        </div>
      )}

      <hr className="rule" style={{ margin: "48px 0 24px" }} />
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", color: "var(--fg-3)", fontSize: 11.5, fontFamily: "var(--font-mono)", letterSpacing: ".06em" }}>
        <span>updated {c.updated}</span>
        <button className="btn ghost tiny" onClick={onOpenSolar}>{window.Icons.Planet(13)} see as system →</button>
      </div>
    </div>
  );
}

function Block({ label, body, kind = "constant" }) {
  return (
    <div>
      <div className={`tag ${kind}`} style={{ marginBottom: 10 }}>{label}</div>
      <p style={{
        margin: 0, color: body ? "var(--fg)" : "var(--fg-3)",
        fontStyle: body ? "normal" : "italic",
        fontSize: 14.5, lineHeight: 1.6
      }}>
        {body || "—"}
      </p>
    </div>
  );
}

function PatternBlock({ pattern, perspectives, solo, style }) {
  return (
    <div style={{ display: "flex", gap: 0, ...style }}>
      {/* Left column: circle anchored at top, vertical line below */}
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flexShrink: 0, width: 22 }}>
        <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--c-pattern)", marginTop: 6, flexShrink: 0 }} />
        <div style={solo
          ? { width: 0, flex: 1, marginTop: 6, borderLeft: "1px dashed color-mix(in oklab, var(--c-pattern) 30%, transparent)" }
          : { width: 1, flex: 1, marginTop: 6, background: "color-mix(in oklab, var(--c-pattern) 30%, transparent)" }
        } />
      </div>
      {/* Right content */}
      <div style={{ flex: 1, paddingLeft: 12 }}>
        <div style={{ marginBottom: 18 }}>
          <div className="tag-flat" style={{ marginBottom: 8 }}>Pattern</div>
          <h3 className="concept-title" style={{ fontSize: 28, margin: "0 0 6px", lineHeight: 1.15 }}>
            {pattern.title || <span style={{ color: "var(--fg-3)" }}>(unnamed)</span>}
          </h3>
          {pattern.body && <p style={{ margin: 0, color: "var(--fg-2)", fontSize: 15, lineHeight: 1.6 }}>{pattern.body}</p>}
        </div>
        <div style={{ display: "grid", gap: 16 }}>
          {perspectives.map(p => <PerspectiveBlock key={p.id} p={p} />)}
          {perspectives.length === 0 && (
            <div style={{ color: "var(--fg-3)", fontStyle: "italic", fontSize: 13 }}>no perspectives grouped here yet</div>
          )}
        </div>
      </div>
    </div>
  );
}

function PerspectiveBlock({ p, solo }) {
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
        <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--c-perspective)" }} />
        <div style={{ fontSize: 13, fontWeight: 500, color: "var(--fg)" }}>{p.title || "untitled"}</div>
        {solo && <span className="solo-mark" style={{ marginLeft: "auto" }}>· solo</span>}
      </div>
      <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.6, color: "var(--fg-2)", fontFamily: "var(--font-serif)", fontStyle: "italic" }}>
        {p.body || <span style={{ color: "var(--fg-3)" }}>—</span>}
      </p>
    </div>
  );
}

function modeStyle(active) {
  return {
    border: 0,
    background: active ? "var(--bg-elev)" : "transparent",
    boxShadow: active ? "0 1px 2px rgba(0,0,0,.05)" : "none",
    color: active ? "var(--fg)" : "var(--fg-3)",
  };
}

Object.assign(window, { ConceptRead });
