/* portfolio-evolution.jsx — v5 sections
   - Engineering Evolution (phase diagram)
   - Dynamic Resume Engine (5 variants, live preview)
   - Social Studio (1200×630 OG cards)
*/

const { useState: useStateE } = React;

// =========================================================
// ENGINEERING EVOLUTION — 6-phase horizontal flow
// =========================================================
const EngineeringEvolution = ({ data, onEdit }) => {
  const e = data.evolution;
  if (!e || !e.phases) return null;
  const [active, setActive] = useStateE(e.phases.length - 1); // last phase active by default

  return (
    <Section
      id="evolution"
      eyebrow="11 · Engineering Evolution"
      title="From a Monday-morning macro"
      italic="to a framework platform."
      sub={e.lead}
    >
      <Editable onEdit={() => onEdit("evolution")}>
        <div className="evo-track">
          {e.phases.map((ph, i) => {
            const next = e.phases[i + 1];
            return (
              <React.Fragment key={ph.id}>
                <button
                  className={`evo-node${active === i ? " active" : ""}${i <= active ? " complete" : ""}`}
                  onClick={() => setActive(i)}
                  onMouseEnter={() => setActive(i)}
                >
                  <div className="evo-num">0{i + 1}</div>
                  <div className="evo-ic"><Icon name={ph.icon || "blueprint"} size={18} /></div>
                  <div className="evo-label">{ph.label}</div>
                  <div className="evo-years">{ph.years}</div>
                </button>
                {next && (
                  <div className={`evo-arrow${i < active ? " complete" : ""}`}>
                    <Icon name="arrow-right" size={14} />
                  </div>
                )}
              </React.Fragment>
            );
          })}
        </div>

        <div className="evo-card">
          {e.phases.map((ph, i) =>
            i === active && (
              <div className="evo-active" key={ph.id}>
                <div className="evo-active-l">
                  <div className="evo-active-num">PHASE 0{i + 1}</div>
                  <h3>{ph.label}</h3>
                  <div className="evo-active-years">{ph.years}</div>
                  <p>{ph.summary}</p>
                </div>
                <div className="evo-active-r">
                  <div className="evo-exemplar-lab">Exemplar work</div>
                  <div className="evo-exemplar-list">{ph.exemplars}</div>
                </div>
              </div>
            )
          )}
        </div>
      </Editable>
    </Section>
  );
};

// =========================================================
// DYNAMIC RESUME ENGINE — 5 variants, single source
// =========================================================
const ResumeATS = ({ engine }) => {
  const s = engine.shared;
  const body = engine.atsBody;
  const v = engine.variants.find(x => x.id === "ats");
  return (
    <div className="resume-doc resume-ats">
      <div className="rd-head">
        <h1>{s.name.toUpperCase()}</h1>
        <div className="rd-subhead">{s.headline}</div>
        <div className="rd-contact">
          <span>{s.location}</span><span>·</span>
          <span>{s.contact.email}</span><span>·</span>
          <span>{s.contact.phone}</span><span>·</span>
          <span>linkedin.com/in/{s.contact.linkedin}</span>
        </div>
      </div>

      <section className="rd-section">
        <h2>PROFESSIONAL SUMMARY</h2>
        <p>{v.summary}</p>
      </section>

      <section className="rd-section">
        <h2>CORE TECHNICAL SKILLS</h2>
        {(body.skillTiers || []).map((t, i) => (
          <div className="rd-tier" key={i}>
            <strong>{t.tier}</strong>
            <div>{(t.items || []).join(" · ")}</div>
          </div>
        ))}
      </section>

      <section className="rd-section">
        <h2>PROFESSIONAL EXPERIENCE</h2>
        {(body.experience || []).map((r, i) => (
          <div className="rd-job" key={i}>
            <div className="rd-job-head">
              <strong>{r.role}</strong>
              <span>{r.when}</span>
            </div>
            <div className="rd-job-where">{r.where}</div>
            <ul>{r.bullets.map((b, j) => <li key={j}>{b}</li>)}</ul>
          </div>
        ))}
      </section>
    </div>
  );
};

const ResumeProductEng = ({ engine, data }) => {
  const s = engine.shared;
  const v = engine.variants.find(x => x.id === "product-eng");
  const products = (data.products?.items || []).filter(p => p.featured);
  return (
    <div className="resume-doc resume-product">
      <div className="rd-product-head" style={{ '--rd-c': v.color }}>
        <div>
          <div className="rd-eyebrow">{v.kicker}</div>
          <h1>{s.name}</h1>
          <div className="rd-subhead">{s.headline}</div>
        </div>
        <div className="rd-product-meta">
          <div className="m"><span className="num">{s.yearsExperience}</span><span className="lab">years engineering</span></div>
          <div className="m"><span className="num">{products.length}</span><span className="lab">products shipped</span></div>
          <div className="m"><span className="num">$3M+</span><span className="lab">value unlocked</span></div>
        </div>
      </div>

      <section className="rd-section">
        <h2>The thesis</h2>
        <p style={{ fontSize: "15px" }}>{v.summary}</p>
      </section>

      <section className="rd-section">
        <h2>Products owned</h2>
        <div className="rd-product-grid">
          {products.map(p => (
            <div className="rd-product-card" key={p.id} style={{ '--prod-c': p.color }}>
              <div className="rdpc-head">
                <span className="rdpc-logo">{p.logo}</span>
                <div>
                  <strong>{p.name}</strong>
                  <span className="rdpc-domain">{p.domain}</span>
                </div>
              </div>
              <p>{p.tagline}</p>
              <div className="rdpc-stack">
                {(p.stack || []).slice(0, 4).map((t, i) => <span key={i}>{t}</span>)}
              </div>
            </div>
          ))}
        </div>
      </section>

      <section className="rd-section">
        <h2>Selected case studies</h2>
        <div className="rd-case-list">
          {(data.projects || []).filter(pr => pr.caseStudy).slice(0, 3).map(pr => (
            <div className="rd-case" key={pr.id}>
              <div className="rd-case-head">
                <strong>{pr.name}</strong>
                <span>{pr.category}</span>
              </div>
              <p>{pr.tagline}</p>
              <div className="rd-case-impact">
                {(pr.caseStudy.impact || []).slice(0, 3).map((m, i) => (
                  <span key={i}><strong>{m.num}</strong> {m.lab}</span>
                ))}
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
};

const ResumeOperationalIntel = ({ engine, data }) => {
  const s = engine.shared;
  const v = engine.variants.find(x => x.id === "operational-intel");
  return (
    <div className="resume-doc resume-oi">
      <div className="rd-band" style={{ '--rd-c': v.color }}>
        <div className="rd-eyebrow">{v.kicker}</div>
        <h1>{s.name}</h1>
        <div className="rd-subhead">{s.headline}</div>
      </div>
      <section className="rd-section">
        <h2>The signature</h2>
        <p>{v.summary}</p>
      </section>
      <section className="rd-section">
        <h2>Business outcomes</h2>
        <div className="rd-outcome-grid">
          <div className="oc"><span className="num">$3M+</span><span className="lab">cost savings unlocked</span><span className="dom">Logistics · Procurement · AP</span></div>
          <div className="oc"><span className="num">95%</span><span className="lab">error reduction in TSP automation</span><span className="dom">Carrier Tech · Logistics</span></div>
          <div className="oc"><span className="num">70%</span><span className="lab">invoices auto-cleared (AP)</span><span className="dom">AP Anatomy · Finance</span></div>
          <div className="oc"><span className="num">50K+</span><span className="lab">supplier records normalised</span><span className="dom">Entity Resolution</span></div>
        </div>
      </section>
      <section className="rd-section">
        <h2>Operational workflows owned</h2>
        <ol className="rd-flow">
          <li><strong>AP Invoice Lifecycle</strong> — OCR extract → 3-way match → exception routing → posting</li>
          <li><strong>Parcel Cost Intelligence</strong> — multi-carrier ingest → anomaly tiering → exec narrative</li>
          <li><strong>Supplier Master</strong> — multi-language normalisation → audit log → cross-company consolidation</li>
          <li><strong>TSP Pipeline</strong> — Outlook capture → fuzzy dedup → rule-tagged outputs</li>
        </ol>
      </section>
    </div>
  );
};

const ResumeArchitecture = ({ engine, data }) => {
  const s = engine.shared;
  const v = engine.variants.find(x => x.id === "architecture");
  const frameworks = data.frameworks?.items || [];
  return (
    <div className="resume-doc resume-arch">
      <div className="rd-arch-head" style={{ '--rd-c': v.color }}>
        <h1>{s.name}</h1>
        <div className="rd-subhead">{s.headline}</div>
        <div className="rd-eyebrow">{v.kicker}</div>
      </div>
      <section className="rd-section">
        <h2>System posture</h2>
        <p>{v.summary}</p>
      </section>
      <section className="rd-section">
        <h2>Frameworks authored</h2>
        <div className="rd-fw-grid">
          {frameworks.slice(0, 6).map(f => (
            <div className="rd-fw" key={f.id}>
              <Icon name={f.icon || "blueprint"} size={14} />
              <strong>{f.name}</strong>
              <span>{f.summary}</span>
            </div>
          ))}
        </div>
      </section>
      <section className="rd-section">
        <h2>Scale numbers</h2>
        <div className="rd-scale">
          <div><strong>500K+</strong><span>rate combinations modelled (Carrier Rate)</span></div>
          <div><strong>100K+</strong><span>records / cycle (Parcel Intelligence)</span></div>
          <div><strong>50K+</strong><span>supplier entities resolved across 4 languages</span></div>
        </div>
      </section>
    </div>
  );
};

const ResumeAIAssisted = ({ engine, data }) => {
  const s = engine.shared;
  const v = engine.variants.find(x => x.id === "ai-assisted");
  return (
    <div className="resume-doc resume-ai">
      <div className="rd-ai-head" style={{ '--rd-c': v.color }}>
        <div className="rd-ai-orbit" aria-hidden="true">
          <span></span><span></span><span></span>
        </div>
        <div>
          <div className="rd-eyebrow">{v.kicker}</div>
          <h1>{s.name}</h1>
          <div className="rd-subhead">{s.headline}</div>
        </div>
      </div>
      <section className="rd-section">
        <h2>The method</h2>
        <p>{v.summary}</p>
      </section>
      <section className="rd-section">
        <h2>Prompt patterns I use</h2>
        <div className="rd-ai-cards">
          <div className="rd-ai-c"><strong>Architecture Validation</strong><span>"Given this data flow + these constraints, surface the failure modes I'd ship past."</span></div>
          <div className="rd-ai-c"><strong>Failure-Mode Review</strong><span>"Three ways this design quietly breaks under 10× load. Then a mitigation for each."</span></div>
          <div className="rd-ai-c"><strong>Design Partner Pair</strong><span>"You're a senior architect. Push back on my assumptions before validating any of them."</span></div>
          <div className="rd-ai-c"><strong>Governance Lens</strong><span>"Audit trail, rollback, approval gate. What's missing from this transformation?"</span></div>
        </div>
      </section>
      <section className="rd-section">
        <h2>AI-assisted products shipped</h2>
        <ul className="rd-flow">
          <li><strong>FinWise</strong> — architecture validated with Claude as design partner</li>
          <li><strong>Maatru Sankalpam</strong> — content engine designed via AI-assisted UX exploration</li>
          <li><strong>AI Architect</strong> — the framework itself: codified prompt patterns</li>
        </ul>
      </section>
    </div>
  );
};

const DynamicResume = ({ data, onEdit, currentVariant, setVariant }) => {
  const e = data.resumeEngine;
  if (!e) return null;
  const v = e.variants.find(x => x.id === currentVariant) || e.variants[0];

  const renderResume = () => {
    switch (v.id) {
      case "ats":              return <ResumeATS engine={e} />;
      case "product-eng":      return <ResumeProductEng engine={e} data={data} />;
      case "operational-intel":return <ResumeOperationalIntel engine={e} data={data} />;
      case "architecture":     return <ResumeArchitecture engine={e} data={data} />;
      case "ai-assisted":      return <ResumeAIAssisted engine={e} data={data} />;
      default:                 return <ResumeATS engine={e} />;
    }
  };

  return (
    <Section
      id="resume"
      eyebrow="14 · Dynamic Resume Engine"
      title="One source of truth,"
      italic="five resumes."
      sub={e.lead}
    >
      <Editable onEdit={() => onEdit("resumeEngine")}>
        <div className="re-shell">
          <aside className="re-aside">
            <div className="re-aside-lab">Choose audience</div>
            <div className="re-variants">
              {e.variants.map(variant => (
                <button
                  key={variant.id}
                  className={"re-variant" + (variant.id === currentVariant ? " active" : "")}
                  onClick={() => setVariant(variant.id)}
                  style={{ '--rv-c': variant.color }}
                >
                  <div className="re-variant-head">
                    <span className="re-variant-dot"></span>
                    <strong>{variant.name}</strong>
                  </div>
                  <div className="re-variant-kicker">{variant.kicker}</div>
                  <div className="re-variant-aud">For: {variant.audience}</div>
                </button>
              ))}
            </div>

            <div className="re-actions">
              <a className="btn btn-accent" href="LAKSHMAN_OPTIMIZED_RESUME_2026.html" target="_blank" rel="noreferrer">
                <Icon name="external" size={13} /> Open print version
              </a>
              <button className="btn" onClick={() => window.print()}>
                <Icon name="download" size={13} /> Save as PDF
              </button>
            </div>

            <div className="re-emphasis">
              <div className="re-emphasis-lab">This variant emphasises</div>
              <ul>
                {(v.emphasis || []).map((em, i) => <li key={i}>{em}</li>)}
              </ul>
            </div>
          </aside>

          <div className="re-preview">
            <div className="re-preview-bar">
              <span className="re-preview-tag">{v.name}</span>
              <span className="re-preview-sub">{v.kicker}</span>
            </div>
            <div className="re-preview-page">
              {renderResume()}
            </div>
          </div>
        </div>
      </Editable>
    </Section>
  );
};

// =========================================================
// SOCIAL STUDIO — 1200×630 OG cards, screenshot-friendly
// =========================================================
const SocialCard = ({ card, idx }) => {
  // Grid-composed card: fixed regions (header · content · footer) so the
  // layout is stable regardless of headline/body length — never content-
  // stretched. Actions live inside the footer region, not floating below.
  const copy = () =>
    navigator.clipboard.writeText(`${card.headline}\n\n${card.body}\n\n— Lakshman Bazarla · Operational Intelligence`);
  const share = () => {
    const t = encodeURIComponent(`${card.headline}\n\n${card.body}`);
    window.open(`https://www.linkedin.com/sharing/share-offsite/?text=${t}`, "_blank");
  };
  return (
    <div className={`og-card og-${card.kind}`} data-og-id={card.id}>
      <div className="og-meta">
        <span className="og-tag">{card.tag}</span>
        <span className="og-channel">{card.channel}</span>
      </div>
      <div className="og-content">
        <div className="og-headline">{card.headline}</div>
        <div className="og-body">{card.body}</div>
      </div>
      <div className="og-footer">
        <div className="og-foot">
          <div className="og-brand">
            <span className="og-mark">LB</span>
            <div>
              <strong>Lakshman Bazarla</strong>
              <span>Operational Intelligence Engineering</span>
            </div>
          </div>
          <div className="og-num">0{idx + 1}</div>
        </div>
        <div className="og-actions">
          <button className="og-action" onClick={copy}>
            <Icon name="copy" size={11} /> Copy
          </button>
          <button className="og-action" onClick={share}>
            <Icon name="linkedin" size={11} /> Share on LinkedIn
            <Icon name="external" size={10} />
          </button>
        </div>
      </div>
    </div>
  );
};

const SocialStudio = ({ data, onEdit }) => {
  const s = data.social;
  if (!s) return null;
  return (
    <Section
      id="social"
      eyebrow="12 · Social Studio"
      title="Share-ready blocks,"
      italic="LinkedIn-sized."
      sub={s.lead}
      action={
        <div className="og-badge">
          <Icon name="image" size={16} />
          <div>
            <strong>1200×630</strong>
            <span>LinkedIn optimized</span>
          </div>
        </div>
      }
    >
      <Editable onEdit={() => onEdit("social")}>
        <div className="og-grid">
          {(s.cards || []).map((card, i) => (
            <SocialCard card={card} idx={i} key={card.id} />
          ))}
        </div>
      </Editable>
    </Section>
  );
};

Object.assign(window, {
  EngineeringEvolution, DynamicResume, SocialStudio, SocialCard
});
