// UBP sub-page: Storage Hosting node.
// User pledges disk space → earns UBR via pin / retrieve / proof-of-storage rewards.
// Editorial-instrument hybrid (paper top, dark monitoring strip).

function StorageHostingDapp() {
  // 24h utilization sparkline values (each is "% of pledged capacity used")
  const util24 = [42, 44, 46, 48, 51, 53, 56, 58, 61, 63, 64, 66, 67, 69, 71, 72, 73, 73, 72, 71, 70, 69, 68, 68];
  const earn30d = [3.8, 4.1, 3.9, 4.4, 4.7, 4.5, 4.8, 5.1, 4.9, 5.3, 5.6, 5.4, 5.8, 6.1, 5.9, 6.2, 6.5, 6.4, 6.7, 7.0, 6.8, 7.2, 7.5, 7.3, 7.8, 8.1, 7.9, 8.4, 8.7, 9.1];

  // Pledged disks
  const disks = [
    { name: 'attic-nvme-01', kind: 'NVMe',  pledged: 2.0, used: 1.42, region: 'Home · UK-S',     class: 'HOT',  yield: 4.20, status: 'ACTIVE',   tone: 'ok' },
    { name: 'attic-hdd-04',  kind: 'HDD',   pledged: 8.0, used: 5.10, region: 'Home · UK-S',     class: 'WARM', yield: 6.80, status: 'ACTIVE',   tone: 'ok' },
    { name: 'colo-r2-12',    kind: 'HDD',   pledged: 22.0, used: 17.4, region: 'Colo · DE-FRA',   class: 'WARM', yield: 18.40, status: 'PROVING', tone: 'accent' },
    { name: 'archive-tape',  kind: 'Tape',  pledged: 96.0, used: 84.2, region: 'Cold · US-E',     class: 'COLD', yield: 12.10, status: 'ACTIVE',   tone: 'ok' },
    { name: 'edge-pi5-bath', kind: 'SSD',   pledged: 0.5, used: 0.18, region: 'Home · UK-S',     class: 'HOT',  yield: 0.42, status: 'IDLE',     tone: 'warn' },
  ];

  // Pinned datasets (live)
  const pins = [
    { cid: 'Qmf8…2c3a', name: 'murine-cortex-2P-cohort1',     size: 482, repl: '14×', dur: '184d', class: 'WARM', earn: 24.10, on: 'colo-r2-12' },
    { cid: 'QmZ7…91fe', name: 'glia-pruning-rawimg-v3',        size: 128, repl: '8×',  dur: '96d',  class: 'WARM', earn: 18.20, on: 'colo-r2-12' },
    { cid: 'QmA1…d804', name: 'astro-ablation-electrophys',    size: 64,  repl: '12×', dur: '54d',  class: 'WARM', earn: 5.40,  on: 'attic-hdd-04' },
    { cid: 'QmK9…0b78', name: 'open-spike-sort-bench',         size: 14,  repl: '24×', dur: '218d', class: 'HOT',  earn: 4.80,  on: 'attic-nvme-01' },
    { cid: 'QmH4…aa18', name: 'preprint-figures-archive',      size: 8,   repl: '14×', dur: '342d', class: 'COLD', earn: 1.40,  on: 'archive-tape' },
    { cid: 'QmN0…8c44', name: 'rnaseq-2026q1',                 size: 210, repl: '8×',  dur: '32d',  class: 'WARM', earn: 9.80,  on: 'colo-r2-12' },
  ];

  const recent = [
    ['+0.420', 'Storage proof · sector 0x18ac…',   '17:04', 'PROOF',     'accent'],
    ['+0.180', 'Retrieval · QmZ7…91fe · 412 MB',   '17:01', 'RETRIEVE',  'ok'],
    ['+1.840', 'Pin reward epoch 4,219',            '16:50', 'PIN',       'ok'],
    ['+0.060', 'Retrieval · QmK9…0b78 · 28 MB',    '16:48', 'RETRIEVE',  'ok'],
    ['+0.120', 'Storage proof · sector 0x21f3…',   '16:42', 'PROOF',     'accent'],
    ['+2.140', 'New pin accepted · QmN0…8c44',     '16:32', 'NEW PIN',   'info'],
    ['−0.040', 'Bandwidth gas',                     '16:28', 'COST',      'warn'],
    ['+0.220', 'Retrieval · Qmf8…2c3a · 1.2 GB',   '16:21', 'RETRIEVE',  'ok'],
  ];

  const totalPledged = disks.reduce((a, d) => a + d.pledged, 0);
  const totalUsed = disks.reduce((a, d) => a + d.used, 0);

  // Sparkline for the dark instrument strip
  const SparkBig = ({ values, color }) => {
    const w = 240, h = 40;
    const max = Math.max(...values), min = Math.min(...values);
    const dx = w / (values.length - 1);
    const norm = v => h - ((v - min) / (max - min || 1)) * (h - 4) - 2;
    const path = values.map((v, i) => `${i === 0 ? 'M' : 'L'}${i * dx},${norm(v)}`).join(' ');
    return (
      <svg width={w} height={h} style={{ display: 'block' }}>
        <path d={path} fill="none" stroke={color || UB.accent} strokeWidth="1.4" />
      </svg>
    );
  };

  const Cell = ({ v, w, mono = true, color, end }) => (
    <span style={{
      width: w, fontFamily: mono ? UB.mono : UB.sans, fontSize: 11, color: color || UB.ink2,
      textAlign: end ? 'right' : 'left',
      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
    }}>{v}</span>
  );

  return (
    <Dapp>
      <ChromeBar dapp="PERSONAL" code="UBP / STORAGE·HOSTING" />
      <Layout rail={typeof PRMRail === 'function' ? <PRMRail active="host" /> : null}>
        <PageHead
          eyebrow={<><span style={{ marginRight: 8 }}>UBP · Storage hosting</span><Tag tone="accent">DePIN · UB-CHAIN</Tag></>}
          title="Earn UBR by hosting science data"
          sub="Pledge storage from any disk you own. The chain replicates papers, datasets, and notebooks across your space and pays you per byte-day, retrieval, and successful storage proof."
          actions={<>
            <Btn small icon={Icon.search}>Browse pin demand</Btn>
            <Btn small icon={Icon.cog}>Node settings</Btn>
            <Btn small primary icon={Icon.plus}>Pledge a new disk</Btn>
          </>}
        />

        {/* DARK INSTRUMENT STRIP — earnings + capacity */}
        <div style={{ background: UB.ink, color: UB.paper, padding: '18px 24px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr 1.4fr', gap: 18, alignItems: 'center', borderTop: `1px solid ${UB.rule2}`, borderBottom: `1px solid ${UB.rule2}` }}>
          <div>
            <div style={{ fontFamily: UB.mono, fontSize: 9, letterSpacing: '0.18em', color: '#aaa', marginBottom: 6 }}>EARNING NOW</div>
            <div style={{ fontFamily: UB.serif, fontSize: 36, lineHeight: 0.95, letterSpacing: '-0.02em' }}>0.82</div>
            <div style={{ fontFamily: UB.mono, fontSize: 9, color: '#aaa', letterSpacing: '0.1em', marginTop: 3 }}>UBR / HOUR · ↑6.4%</div>
          </div>
          <div>
            <div style={{ fontFamily: UB.mono, fontSize: 9, letterSpacing: '0.18em', color: '#aaa', marginBottom: 6 }}>30D EARNINGS</div>
            <div style={{ fontFamily: UB.serif, fontSize: 36, lineHeight: 0.95, letterSpacing: '-0.02em' }}>184.2</div>
            <div style={{ fontFamily: UB.mono, fontSize: 9, color: '#aaa', letterSpacing: '0.1em', marginTop: 3 }}>UBR · 4 EPOCHS</div>
          </div>
          <div>
            <div style={{ fontFamily: UB.mono, fontSize: 9, letterSpacing: '0.18em', color: '#aaa', marginBottom: 6 }}>PLEDGED · USED</div>
            <div style={{ fontFamily: UB.serif, fontSize: 32, lineHeight: 0.95, letterSpacing: '-0.02em' }}>{totalUsed.toFixed(1)}<span style={{ fontSize: 18, color: '#888' }}> / {totalPledged.toFixed(0)} TB</span></div>
            <div style={{ height: 4, background: '#222', marginTop: 8 }}>
              <div style={{ width: `${(totalUsed / totalPledged) * 100}%`, height: '100%', background: UB.accent }} />
            </div>
          </div>
          <div>
            <div style={{ fontFamily: UB.mono, fontSize: 9, letterSpacing: '0.18em', color: '#aaa', marginBottom: 6 }}>PROOFS · 24H</div>
            <div style={{ fontFamily: UB.serif, fontSize: 36, lineHeight: 0.95, letterSpacing: '-0.02em' }}>2,184</div>
            <div style={{ fontFamily: UB.mono, fontSize: 9, color: '#aaa', letterSpacing: '0.1em', marginTop: 3 }}>0 FAIL · 99.99% UPTIME</div>
          </div>
          <div>
            <div style={{ fontFamily: UB.mono, fontSize: 9, letterSpacing: '0.18em', color: '#aaa', marginBottom: 6 }}>30D EARNINGS · UBR</div>
            <SparkBig values={earn30d} />
            <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: UB.mono, fontSize: 9, color: '#aaa', letterSpacing: '0.08em', marginTop: 2 }}>
              <span>04 APR</span><span>NOW</span>
            </div>
          </div>
        </div>

        <div style={{ flex: 1, padding: 24, overflow: 'auto', display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 16 }}>

          {/* LEFT — pledged disks + pinned datasets */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

            {/* Pledged disks */}
            <Card title="My pledged storage" code={`${disks.length} DISKS · ${totalPledged.toFixed(0)} TB`} pad={false}>
              <Row head cells={[
                { v: 'Disk', w: '160px' },
                { v: 'Type', w: '64px' },
                { v: 'Region', w: '120px' },
                { v: 'Pledged', w: '90px' },
                { v: 'Used', w: '110px' },
                { v: 'Class', w: '74px' },
                { v: 'Yield 30d', w: '90px' },
                { v: 'Status', w: '90px' },
              ]} />
              {disks.map((d, i) => (
                <div key={d.name} style={{
                  display: 'flex', alignItems: 'center', padding: '10px 12px',
                  borderBottom: i < disks.length - 1 ? `1px solid ${UB.rule3}` : 'none',
                  fontFamily: UB.mono, fontSize: 11, color: UB.ink2,
                }}>
                  <Cell v={<><span style={{ color: UB.ink, fontFamily: UB.sans, fontWeight: 500 }}>{d.name}</span></>} w="160px" mono={false} />
                  <Cell v={d.kind} w="64px" />
                  <Cell v={d.region} w="120px" />
                  <Cell v={`${d.pledged} TB`} w="90px" color={UB.ink} />
                  <span style={{ width: 110, paddingRight: 14 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: UB.mono, fontSize: 9, color: UB.ink3, marginBottom: 2 }}>
                      <span>{d.used} TB</span><span>{Math.round((d.used / d.pledged) * 100)}%</span>
                    </div>
                    <div style={{ height: 4, background: UB.paperDeep }}>
                      <div style={{ width: `${(d.used / d.pledged) * 100}%`, height: '100%', background: d.status === 'PROVING' ? UB.accent : UB.ink }} />
                    </div>
                  </span>
                  <span style={{ width: 74 }}><Tag>{d.class}</Tag></span>
                  <Cell v={`+${d.yield.toFixed(2)} UBR`} w="90px" color={UB.accent} />
                  <span style={{ width: 90 }}><Tag tone={d.tone}>{d.status}</Tag></span>
                </div>
              ))}
              <div style={{ padding: '10px 14px', background: UB.paperDeep, display: 'flex', justifyContent: 'space-between', fontFamily: UB.mono, fontSize: 10, color: UB.ink3 }}>
                <span>TOTAL · {totalPledged.toFixed(1)} TB pledged · {totalUsed.toFixed(1)} TB used · 4 active disks</span>
                <span style={{ color: UB.accent }}>+ ADD DISK</span>
              </div>
            </Card>

            {/* Pin demand */}
            <Card title="Datasets I'm pinning" code={`${pins.length} ACTIVE · 906 GB`} pad={false}>
              <Row head cells={[
                { v: 'CID', w: '110px' },
                { v: 'Dataset' },
                { v: 'Size', w: '70px' },
                { v: 'Repl', w: '54px' },
                { v: 'Class', w: '74px' },
                { v: 'On disk', w: '120px' },
                { v: 'Earn', w: '78px' },
              ]} />
              {pins.map((p, i) => (
                <Row key={i} cells={[
                  { v: p.cid, w: '110px', style: { color: UB.ink3 } },
                  { v: <span style={{ color: UB.ink, fontFamily: UB.sans, fontSize: 12 }}>{p.name}</span> },
                  { v: `${p.size} GB`, w: '70px' },
                  { v: p.repl, w: '54px', style: { color: UB.ink3 } },
                  { v: <Tag>{p.class}</Tag>, w: '74px' },
                  { v: <span style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink2 }}>{p.on}</span>, w: '120px' },
                  { v: <span style={{ color: UB.accent }}>+{p.earn.toFixed(2)}</span>, w: '78px', style: { textAlign: 'right' } },
                ]} />
              ))}
            </Card>

            {/* Reward feed */}
            <Card title="Reward feed" code="LIVE">
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                {recent.map((r, i) => (
                  <div key={i} style={{ display: 'grid', gridTemplateColumns: '70px 1fr 60px 70px', alignItems: 'center', padding: '7px 0', borderBottom: i < recent.length - 1 ? `1px solid ${UB.rule3}` : 'none', fontFamily: UB.mono, fontSize: 11 }}>
                    <span style={{ color: r[0].startsWith('−') ? UB.warn : UB.accent }}>{r[0]} UBR</span>
                    <span style={{ color: UB.ink2 }}>{r[1]}</span>
                    <span style={{ color: UB.ink3, fontSize: 10 }}>{r[2]}</span>
                    <span style={{ textAlign: 'right' }}><Tag tone={r[4]}>{r[3]}</Tag></span>
                  </div>
                ))}
              </div>
            </Card>
          </div>

          {/* RIGHT — pledge wizard, economics, proof health */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

            {/* Pledge wizard */}
            <Card title="Pledge a new disk" code="3-STEP">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                {/* Step 1 — capacity */}
                <div style={{ borderLeft: `2px solid ${UB.accent}`, paddingLeft: 12 }}>
                  <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.12em', marginBottom: 4 }}>STEP 01 · CAPACITY</div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 6 }}>
                    <div style={{ fontFamily: UB.serif, fontSize: 32, letterSpacing: '-0.02em' }}>4.0</div>
                    <div style={{ fontFamily: UB.mono, fontSize: 11, color: UB.ink3 }}>TB pledged</div>
                  </div>
                  {/* Slider */}
                  <div style={{ position: 'relative', height: 6, background: UB.paperDeep, marginBottom: 6 }}>
                    <div style={{ width: '20%', height: '100%', background: UB.ink }} />
                    <div style={{ position: 'absolute', left: '20%', top: -3, width: 10, height: 12, background: UB.accent, transform: 'translateX(-50%)' }} />
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.06em' }}>
                    <span>0.5 TB</span><span>4.0 / 20 TB</span><span>20 TB</span>
                  </div>
                </div>

                {/* Step 2 — class */}
                <div style={{ borderLeft: `2px solid ${UB.accent}`, paddingLeft: 12 }}>
                  <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.12em', marginBottom: 6 }}>STEP 02 · STORAGE CLASS</div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 }}>
                    {[
                      ['HOT',  'NVMe / SSD', '×3.2', false],
                      ['WARM', 'HDD · always-on', '×1.0', true],
                      ['COLD', 'Tape / archive', '×0.4', false],
                    ].map(c => (
                      <div key={c[0]} style={{
                        padding: '8px 10px', border: `1px solid ${c[3] ? UB.ink : UB.rule2}`,
                        background: c[3] ? UB.paperDeep : '#fff', cursor: 'pointer',
                      }}>
                        <div style={{ fontFamily: UB.mono, fontSize: 11, fontWeight: 600, color: UB.ink }}>{c[0]}</div>
                        <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, marginTop: 2 }}>{c[1]}</div>
                        <div style={{ fontFamily: UB.mono, fontSize: 11, color: UB.accent, marginTop: 4 }}>{c[2]}</div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Step 3 — bond */}
                <div style={{ borderLeft: `2px solid ${UB.accent}`, paddingLeft: 12 }}>
                  <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.12em', marginBottom: 4 }}>STEP 03 · COLLATERAL BOND</div>
                  <div style={{ fontSize: 11, color: UB.ink2, lineHeight: 1.5, marginBottom: 6 }}>
                    Lock 12 UBR / TB as bond. Slashed only if you fail storage proofs. Returns when you decommission.
                  </div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                    <div style={{ fontFamily: UB.serif, fontSize: 22, letterSpacing: '-0.02em' }}>48 UBR</div>
                    <div style={{ fontFamily: UB.mono, fontSize: 10, color: UB.ink3 }}>· wallet 12,840 UBR</div>
                  </div>
                </div>

                {/* Estimator */}
                <div style={{ background: UB.paperDeep, padding: 12, marginTop: 4 }}>
                  <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.12em', marginBottom: 6 }}>EST. EARNINGS · 4 TB · WARM</div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
                    <div>
                      <div style={{ fontFamily: UB.serif, fontSize: 22 }}>2.40</div>
                      <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.08em' }}>UBR / DAY</div>
                    </div>
                    <div>
                      <div style={{ fontFamily: UB.serif, fontSize: 22 }}>72</div>
                      <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.08em' }}>UBR / MO</div>
                    </div>
                    <div>
                      <div style={{ fontFamily: UB.serif, fontSize: 22 }}>5.4%</div>
                      <div style={{ fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.08em' }}>EFF. APY</div>
                    </div>
                  </div>
                </div>

                <div style={{ display: 'flex', gap: 6 }}>
                  <Btn small style={{ flex: 1 }}>Run healthcheck</Btn>
                  <Btn small primary icon={Icon.shield} style={{ flex: 1 }}>Pledge &amp; bond</Btn>
                </div>
              </div>
            </Card>

            {/* Economics */}
            <Card title="Reward formula" code="HOW YOU EARN">
              <div style={{ fontSize: 11, color: UB.ink2, lineHeight: 1.55, marginBottom: 10 }}>
                Three reward streams settle every epoch (≈6h). Slashing applies if you miss a proof window.
              </div>
              {[
                ['PIN',      'Per byte-day stored · paid by dataset DAO', '×1.0', UB.ok],
                ['RETRIEVE', 'Per GB served on demand', '×2.4', UB.ok],
                ['PROOF',    'Per successful storage-proof challenge', '×1.0', UB.accent],
                ['SLASH',    'Failed proof window > 6h', '×0.8 bond', UB.bad || '#b6362a'],
              ].map((r, i, arr) => (
                <div key={r[0]} style={{ display: 'grid', gridTemplateColumns: '70px 1fr 60px', gap: 10, alignItems: 'center', padding: '8px 0', borderBottom: i < arr.length - 1 ? `1px solid ${UB.rule3}` : 'none', fontSize: 11 }}>
                  <span style={{ fontFamily: UB.mono, fontSize: 10, padding: '2px 6px', background: UB.paperDeep, color: r[3], letterSpacing: '0.08em', textAlign: 'center' }}>{r[0]}</span>
                  <span style={{ color: UB.ink2 }}>{r[1]}</span>
                  <span style={{ fontFamily: UB.mono, color: UB.ink, textAlign: 'right' }}>{r[2]}</span>
                </div>
              ))}
            </Card>

            {/* Proof health */}
            <Card title="Proof-of-storage health" code="24H WINDOW">
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
                <Stat label="Challenges" value="2,184" sub="last 24h" />
                <Stat label="Failures" value="0" sub="0.00%" />
                <Stat label="Avg latency" value="184ms" sub="p95 412ms" />
                <Stat label="Bond at risk" value="0 UBR" sub="of 188" />
              </div>
              <div style={{ marginTop: 4, height: 32, display: 'flex', gap: 1, alignItems: 'flex-end' }}>
                {util24.map((v, i) => (
                  <div key={i} style={{ flex: 1, height: `${v}%`, background: i === util24.length - 1 ? UB.accent : UB.ink }} />
                ))}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: UB.mono, fontSize: 9, color: UB.ink3, letterSpacing: '0.08em', marginTop: 4 }}>
                <span>00:00</span><span>UTILIZATION %</span><span>NOW · 68%</span>
              </div>
            </Card>

            {/* Network role */}
            <Card title="Your role in the network" code="DePIN">
              <div style={{ fontSize: 11, color: UB.ink2, lineHeight: 1.55 }}>
                You currently hold <span style={{ color: UB.ink, fontWeight: 600 }}>0.018%</span> of UB-Chain's total pledged storage. Demand for warm research data exceeds supply by <span style={{ color: UB.accent }}>+18.4%</span> — pledging more disk now compounds yield until the next epoch rebalance.
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginTop: 12 }}>
                <Stat label="Network pledged" value="708 PB" sub="14,218 nodes" />
                <Stat label="Network used" value="421 PB" sub="59% utilized" />
                <Stat label="Demand 24h" value="+18.4%" sub="warm class" />
              </div>
            </Card>

          </div>
        </div>
      </Layout>
    </Dapp>
  );
}

window.StorageHostingDapp = StorageHostingDapp;
