/* global React, IMG, KxHero, KxMarquee, KxSection, KxSectionHead,
   KxPillars, KxSplit, KxStrip, KxQuote, KxInsights, KxPills,
   KxPeople, KxSubHero, KxStrategy, KxContact */
const { useState } = React;

// ====================================================================
// Shared data
// ====================================================================
const PILLARS = [
  {
    num: "01 / Pillar",
    name: "Listed <em>Equities</em>",
    desc: "Core holdings in resilient banks, industry, and energy. Focused on dividends and long-term value. Quality businesses through cycles.",
    image: IMG.equities,
    key: "equities",
  },
  {
    num: "02 / Pillar",
    name: "Real <em>Estate</em> & Land",
    desc: "Prime apartments, commercial offices, and leased agricultural land. Stable income and inflation protection across urban and rural holdings.",
    image: IMG.realEstate,
    key: "real-estate",
  },
  {
    num: "03 / Pillar",
    name: "Plantations & <em>Agriculture</em>",
    desc: "Tea, rubber, and specialty export crops; long-duration timber assets; smart greenhouse and hydroponics ventures. Diversification with sustainability.",
    image: IMG.tea1,
    key: "plantations",
  },
  {
    num: "04 / Pillar",
    name: "Fixed Income & <em>Alternatives</em>",
    desc: "Deposits, treasury, commercial paper, plus select private equity and REITs. Stability and disciplined growth in any market.",
    image: IMG.finance,
    key: "fixed-income",
  },
];

const PLANTATIONS = [
  {
    num: "Specialty",
    name: "Rare & <em>valuable</em> resources",
    desc: "Strategic investments in plantations that cultivate rare natural resources with strong global demand — long-term value, built for generations.",
    image: IMG.specialty,
  },
  {
    num: "Modern Ag",
    name: "Smart greenhouse & <em>hydroponics</em>",
    desc: "Sustainable greenhouse ventures combining hydroponics, AI-driven fertigation, and advanced techniques. Export-quality, year-round, no pollution.",
    image: IMG.greenhouse,
  },
  {
    num: "Forestry",
    name: "Long-term <em>legacy</em> assets",
    desc: "Plantations of high-demand export crops like vanilla, alongside long-duration timber: teak, mahogany, sandalwood. Sustainability and enduring value.",
    image: IMG.forestry,
  },
];

const INSIGHTS = [
  { date: "Apr 2026",  type: "Letter to Investors", title: "On the price of <em>patience</em>" },
  { date: "Mar 2026",  type: "Field Note",          title: "Bogawantalawa: a season of measured yields" },
  { date: "Feb 2026',", type: "Strategy Note",      title: "Why we lengthened duration in fixed income" },
  { date: "Jan 2026",  type: "Letter to Investors", title: "An <em>inventory</em> of conviction" },
  { date: "Dec 2025",  type: "White Paper",         title: "Vanilla, sandalwood, and the long compound" },
  { date: "Nov 2025",  type: "Field Note",          title: "Greenhouse trials, second harvest" },
  { date: "Oct 2025",  type: "Press",               title: "Keltra closes Real Assets Fund III" },
  { date: "Q3 2025",   type: "Letter to Investors", title: "Listed equities through a softening cycle" },
];

const LEADERSHIP = [
  { name: "Reidar Halvorsen",     title: "Founder · Chairman" },
  { name: "Anjali Wickremesinghe", title: "Managing Partner · Equities" },
  { name: "Marcus Bellweather",    title: "Managing Partner · Real Estate" },
  { name: "Lakshman de Silva",     title: "Managing Partner · Plantations" },
  { name: "Eleanor Whitfield",     title: "Head of Research" },
  { name: "Priya Raghavan",        title: "Head of Risk" },
  { name: "Daniel O'Connor",       title: "Chief Operating Officer" },
  { name: "Camilla Strand",        title: "Head of Investor Relations" },
];

// ====================================================================
// HOME
// ====================================================================
function HomePage({ onNav }) {
  return (
    <div data-screen-label="Site — Home">
      <KxHero
        image={IMG.tea1}
        eyebrow="EST. MCMLXXXVII · A PRIVATE INVESTMENT FIRM"
        headHtml="Stewarding wealth.<br/>Building <em>legacies</em>."
        lede="Disciplined capital allocation across financial, real, and alternative assets — transparent, diversified, and built for long-term value."
        ctas={<>
          <button className="kx-btn kx-btn--primary" onClick={() => onNav("Strategies")}>Discover our approach</button>
          <button className="kx-btn kx-btn--outline" onClick={() => onNav("Firm")}>Our philosophy</button>
        </>}
        chrome={["EST. MCMLXXXVII", "Stewarding wealth", "Compounding value"]}
      />

      <KxMarquee stats={[
        { label: "AUM",           figure: "$24.3<sup>B</sup>" },
        { label: "Pillars",       figure: "4" },
        { label: "Plantations",   figure: "12<sup>est.</sup>" },
        { label: "Family of investors", figure: "180+" },
        { label: "Years compounding",   figure: "39" },
      ]} />

      {/* Story split */}
      <KxSection tone="ivory">
        <KxSplit
          image={IMG.tea1}
          caption="Tea estate · Bogawantalawa · 2024"
          eyebrow="Our Story"
          title="A family firm, written across <em>four generations</em>."
          lede="Founded in 1987, Keltra Capital is a private investment house practicing patient, multi-sector allocation. The firm is owned by its working partners and has never accepted external capital it could not steward for at least a generation."
          body={[
            "From its origins in tea and rubber, the firm has grown into a diversified investment platform spanning listed equities, real estate, modern agriculture, fixed income, and alternatives. The portfolio is built one decision at a time — never built on a thesis we cannot defend in person.",
            "We measure performance over decades, not quarters. We measure success in stewardship — the durable assets, families, and institutions we leave behind."
          ]}
          cta={<button className="kx-btn kx-btn--ghost kx-btn--ghost-dark" onClick={() => onNav("Firm")}>Read our story</button>}
        />
      </KxSection>

      {/* Pillars */}
      <KxSection>
        <KxSectionHead
          eyebrow="Strategies"
          title="Four pillars. <em>One</em> philosophy."
          intro="Listed equities, real estate, plantations, and fixed income are run as distinct mandates with shared underwriting standards. Capital flows where conviction is highest."
        />
        <KxPillars items={PILLARS} onPick={(p) => onNav(p.key === "plantations" ? "Plantations" : "Strategies")} />
      </KxSection>

      <KxQuote
        tone="forest"
        body="Someone is sitting in the shade today because someone <em>planted a tree</em> a long time ago."
        attr="Warren Buffett · invoked by the founder, 1989"
      />

      {/* Plantations strip */}
      <KxSection tone="ivory">
        <KxSectionHead
          eyebrow="Plantation Investments"
          title="Sustainable agriculture. <em>Enduring</em> value."
          intro="The plantation portfolio is the most distinctive chapter of the firm — a working bridge between heritage agriculture and modern, sustainable food systems."
        />
        <KxStrip items={PLANTATIONS} />
        <div style={{marginTop: 56, display: "flex", justifyContent: "center"}}>
          <button className="kx-btn kx-btn--ink" onClick={() => onNav("Plantations")}>Tour the estates</button>
        </div>
      </KxSection>

      {/* Insights teaser */}
      <KxSection tone="paper">
        <KxSectionHead
          eyebrow="From the Desk"
          title="Legacy insights, applied with <em>modern discipline</em>."
          intro="Quarterly letters, field notes from the estates, and long-form thinking on portfolio construction. Written for an audience who reads them in full."
        />
        <KxInsights items={INSIGHTS.slice(0, 4)} />
        <div style={{marginTop: 40}}>
          <button className="kx-btn kx-btn--ghost kx-btn--ghost-dark" onClick={() => onNav("Insights")}>All writing</button>
        </div>
      </KxSection>
    </div>
  );
}

// ====================================================================
// FIRM
// ====================================================================
function FirmPage() {
  return (
    <div data-screen-label="Site — Firm">
      <KxSubHero
        texture
        eyebrow="The Firm"
        title="A study in <em>duration</em>."
        lede="Forty years of compounding require forty years of discipline. Keltra is built on shared underwriting, durable capital, and a partnership culture designed to outlast its founders."
        meta={[
          { label: "Founded",   value: "1987" },
          { label: "Owned by",  value: "Working partners" },
          { label: "Offices",   value: "Colombo · Hatton · Singapore" },
          { label: "Capital",   value: "$24.3B AUM" },
        ]}
      />

      <KxSection tone="paper">
        <KxSplit
          image={IMG.exec}
          caption="Boardroom · Colombo"
          eyebrow="Philosophy"
          title="Build something a generation can <em>inherit</em>."
          lede="The firm exists to compound capital across decades, while building real businesses that contribute to the regions in which they operate."
          body={[
            "Three operating principles govern every allocation. First: we own what we understand. Second: we never finance ourselves into a position we cannot hold. Third: we measure stewardship — of capital, of land, of the people who work with us — alongside any financial return.",
            "These principles produce a portfolio that is concentrated by intent, diversified by asset class, and patient by construction.",
          ]}
        />
      </KxSection>

      <KxSection tone="ivory">
        <KxSectionHead
          eyebrow="Underwriting"
          title="What we will not own."
          intro="A short list, but a binding one."
        />
        <ul style={{
          listStyle: "none", padding: 0, margin: 0, columns: 2, columnGap: 80,
          fontFamily: "var(--font-display)", fontSize: 24, lineHeight: 1.55, color: "var(--forest-900)", fontWeight: 300,
        }}>
          <li style={{breakInside: "avoid", marginBottom: 20}}>Businesses we do not understand.</li>
          <li style={{breakInside: "avoid", marginBottom: 20}}>Capital structures that require refinancing to survive.</li>
          <li style={{breakInside: "avoid", marginBottom: 20}}>Management teams who cannot answer the question.</li>
          <li style={{breakInside: "avoid", marginBottom: 20}}>Land we cannot visit and improve.</li>
          <li style={{breakInside: "avoid", marginBottom: 20}}>Trades that require us to be right twice.</li>
          <li style={{breakInside: "avoid", marginBottom: 20}}>Liquidity we do not have.</li>
        </ul>
      </KxSection>

      <KxSection tone="paper">
        <KxSectionHead
          eyebrow="Leadership"
          title="Partners and operators."
          intro="The firm is owned by its working partners. The Operating Committee meets weekly in Colombo."
        />
        <KxPeople items={LEADERSHIP} />
      </KxSection>
    </div>
  );
}

// ====================================================================
// STRATEGIES (long form, one block per pillar)
// ====================================================================
function StrategiesPage() {
  return (
    <div data-screen-label="Site — Strategies">
      <KxSubHero
        eyebrow="Strategies"
        title="Four books. <em>One</em> philosophy."
        lede="Each strategy is a separate mandate with its own team and its own accountability. The underwriting standard is shared."
      />

      <KxStrategy
        num="01 / Listed Equities"
        title="<em>Concentrated</em>, long-duration equity."
        intro="Quality businesses in financial services, industry, and energy — held with intent through cycles."
        image={IMG.stockEx}
        body={[
          "Keltra's listed equity book is a concentrated portfolio of resilient businesses across financial services, industrial manufacturing, and energy. The strategy underwrites cash generation, capital discipline, and management quality before price. Holdings average seven years.",
          "We invest in quality compounders with strong fundamentals — businesses with durable competitive positions, conservative balance sheets, and managements we have known for years.",
        ]}
        facts={[
          { label: "Vintage",      value: "Open since 1996" },
          { label: "Target hold",  value: "7+ years" },
          { label: "Concentration",value: "Fewer than 40 names" },
          { label: "AUM",          value: "$13.1B" },
          { label: "Since inception", value: "+14.2% p.a. net" },
        ]}
      />

      <KxStrategy
        num="02 / Real Estate & Land"
        title="Prime <em>property</em> and productive land."
        intro="Apartments, commercial offices, and leased agricultural land. Cornerstone of multi-generational compounding."
        image={IMG.property}
        body={[
          "Our real estate investments include prime apartments, commercial offices, and leased agricultural land. These assets provide recurring income streams, capital appreciation, and reliable protection against inflation.",
          "By diversifying across both urban and rural holdings, we balance stability with growth potential. Real estate remains a cornerstone of our strategy for building enduring generational wealth.",
        ]}
        facts={[
          { label: "Properties",       value: "42 across 4 cities" },
          { label: "Agricultural land", value: "18,400 acres" },
          { label: "Occupancy",         value: "97% (residential)" },
          { label: "Net rental yield",  value: "6.4%" },
        ]}
      />

      <KxStrategy
        num="03 / Plantations & Agriculture"
        title="Heritage agriculture, <em>modern</em> systems."
        intro="Tea and rubber estates, specialty plantations, and smart-greenhouse ventures across the central highlands."
        image={IMG.tea2}
        body={[
          "We invest in plantation ventures focused on high-demand export crops, greenhouse farming, and long-term forestry assets. These opportunities are structured for steady yields while supporting sustainable practices.",
          "From specialty crops to timber, plantations offer both diversification and compounding returns. Our approach secures financial growth and lasting value for future generations — alongside the rural communities that operate the estates.",
        ]}
        facts={[
          { label: "Estates",        value: "12 active operations" },
          { label: "Total acreage",  value: "9,640 hectares" },
          { label: "Crops",          value: "Tea · Rubber · Vanilla · Teak" },
          { label: "Workforce",      value: "2,400 employees" },
        ]}
      />

      <KxStrategy
        num="04 / Fixed Income & Alternatives"
        title="Stability, <em>liquidity</em>, and selected venture."
        intro="A disciplined fixed income allocation alongside a small, curated book of private equity and alternatives."
        image={IMG.alternatives}
        body={[
          "Our fixed income allocation includes deposits, treasury bonds, and commercial papers that provide security and steady income. Alongside this, we selectively allocate to private equity, REITs, and alternative investments for higher growth potential.",
          "This mix of stability and opportunity creates a disciplined portfolio structure. It ensures liquidity, capital protection, and consistent performance across varying market conditions.",
        ]}
        facts={[
          { label: "Duration",         value: "4.2 years (weighted)" },
          { label: "Investment grade", value: "100% rated AA+ or better" },
          { label: "Alternatives book", value: "8 active mandates" },
          { label: "Liquidity reserve", value: "$1.4B" },
        ]}
      />
    </div>
  );
}

// ====================================================================
// PLANTATIONS (dedicated page — showcase of estates)
// ====================================================================
function PlantationsPage() {
  const estates = [
    { name: "Bogawantalawa Tea Estate",  crop: "Ceylon Tea",    acres: "1,840 ha", established: "1898", image: IMG.tea1 },
    { name: "Diyathilake Greenhouse",    crop: "Hydroponic veg",acres: "62 ha",    established: "2018", image: IMG.greenhouse },
    { name: "Hatton Forestry Block",     crop: "Teak / Mahogany",acres: "2,200 ha",established: "2005", image: IMG.forestry },
    { name: "Matale Vanilla Plantation", crop: "Vanilla bourbon",acres: "180 ha",  established: "2014", image: IMG.specialty },
    { name: "Kandy Estate",              crop: "Rubber",         acres: "1,420 ha",established: "1937", image: IMG.farm },
    { name: "Nuwara Eliya High-Country", crop: "Tea",            acres: "980 ha",  established: "1922", image: IMG.heroHills },
  ];
  return (
    <div data-screen-label="Site — Plantations">
      <KxSubHero
        eyebrow="Plantations"
        title="A working chapter of the <em>portfolio</em>."
        lede="Twelve estates across Sri Lanka's central highlands, totalling 9,640 hectares. From legacy Ceylon tea to modern hydroponics, each estate is operated by Keltra and reports against shared sustainability standards."
        meta={[
          { label: "Estates",   value: "12" },
          { label: "Hectares",  value: "9,640" },
          { label: "Workforce", value: "2,400" },
          { label: "Crops",     value: "Tea · Rubber · Vanilla · Teak" },
        ]}
      />

      <KxSection tone="paper" padTop={80}>
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 32,
        }}>
          {estates.map(e => (
            <article key={e.name} style={{cursor: "pointer"}}>
              <div style={{position: "relative"}}>
                <img src={e.image} alt="" style={{width: "100%", aspectRatio: "4/5", objectFit: "cover", display: "block"}} />
                <div style={{position: "absolute", top: 0, left: 0, background: "var(--brass-600)", color: "var(--forest-900)", padding: "8px 14px", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase"}}>{e.crop}</div>
              </div>
              <div style={{paddingTop: 20, display: "flex", flexDirection: "column", gap: 12}}>
                <h3 style={{fontFamily: "var(--font-display)", fontSize: 26, fontWeight: 400, color: "var(--forest-900)", margin: 0, letterSpacing: "-0.012em"}}>{e.name}</h3>
                <div style={{display: "flex", gap: 24, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--graphite-700)", letterSpacing: "0.06em", textTransform: "uppercase"}}>
                  <span>{e.acres}</span>
                  <span>·</span>
                  <span>Established {e.established}</span>
                </div>
              </div>
            </article>
          ))}
        </div>
      </KxSection>

      <KxQuote
        body="Our plantations are not a portfolio decision. <em>They are how the firm keeps faith with the next forty years.</em>"
        attr="Lakshman de Silva · Managing Partner, Plantations"
      />

      <KxSection tone="ivory">
        <KxSplit
          image={IMG.greenhouse}
          caption="Diyathilake greenhouse · 2025"
          eyebrow="Modern Agriculture"
          title="Hydroponics, fertigation, and a <em>second</em> harvest economy."
          lede="A 62-hectare greenhouse complex applying AI-driven fertigation to export-grade fruits and vegetables. Year-round yield, no soil, no pesticide runoff."
          body={[
            "The Diyathilake complex was commissioned in 2018 as the firm's pilot for soilless agriculture. It now supplies export-grade tomatoes, peppers, and leafy crops to retailers in the Gulf and Singapore, with twelve growing cycles per year.",
            "The complex employs 180 people, runs on solar and biomass, and discharges no agricultural runoff into the surrounding catchment. It is the template for two further facilities in development.",
          ]}
        />
      </KxSection>
    </div>
  );
}

// ====================================================================
// INSIGHTS
// ====================================================================
function InsightsPage() {
  const [filter, setFilter] = useState("All Writing");
  const filters = ["All Writing", "Letters", "Field Notes", "Strategy Notes", "Press"];
  const visible = filter === "All Writing"
    ? INSIGHTS
    : INSIGHTS.filter(i => {
        if (filter === "Letters")        return i.type.includes("Letter");
        if (filter === "Field Notes")    return i.type === "Field Note";
        if (filter === "Strategy Notes") return i.type.includes("Strategy") || i.type.includes("White");
        if (filter === "Press")          return i.type === "Press";
        return true;
      });
  return (
    <div data-screen-label="Site — Insights">
      <KxSubHero
        eyebrow="Insights"
        title="Writing from <em>the desk</em>."
        lede="Long-form thinking on portfolio construction, capital cycles, and the small number of things that compound over forty years."
      />
      <KxSection tone="paper">
        <KxPills options={filters} value={filter} onChange={setFilter} />
        <KxInsights items={visible} />
      </KxSection>
    </div>
  );
}

// ====================================================================
// CONTACT
// ====================================================================
function ContactPage() {
  return (
    <div data-screen-label="Site — Contact">
      <KxSubHero
        eyebrow="Contact"
        title="Begin a <em>conversation</em>."
        lede="The firm accepts a small number of new institutional partnerships each year. Reach out and the IR desk will be in touch within two business days."
      />
      <KxContact />
    </div>
  );
}

Object.assign(window, { HomePage, FirmPage, StrategiesPage, PlantationsPage, InsightsPage, ContactPage });
