/* cst-sharesheet.jsx — the share loop UI. Generates the branded result card
   (1:1 + 9:16), previews it live, and distributes via system share / download /
   X / LinkedIn / copy, with copy-pasteable caption tones. Exported as ShareSheet. */

const { useState: _ssS, useEffect: _ssE, useRef: _ssR } = React;
const _SS = window.CST;
const { FONT: _ssF, TEXT: _ssT, HAZE: _ssH, HAZE_DIM: _ssHD, HAIR: _ssHR, GLASS: _ssG, GLASS_HI: _ssGH, INK: _ssI, INK_DEEP: _ssID } = _SS;

const TONES = [{ k: 'bold', label: 'Bold' }, { k: 'humble', label: 'Humble' }, { k: 'challenger', label: 'Challenger' }];

function SegToggle({ value, options, accent, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 4, padding: 4, borderRadius: 12, background: _ssID, border: `1px solid ${_ssHR}` }}>
      {options.map((o) => {
        const on = o.value === value;
        return (
          <button key={o.value} onClick={() => onChange(o.value)} style={{
            flex: 1, cursor: 'pointer', border: 'none', borderRadius: 9, padding: '9px 8px',
            fontFamily: _ssF, fontSize: 12, fontWeight: 700, letterSpacing: 0.3,
            color: on ? _ssI : _ssH, background: on ? accent : 'transparent', transition: 'all .15s',
          }}>{o.label}</button>);
      })}
    </div>);
}

function ActionBtn({ icon, label, onClick, accent, filled }) {
  return (
    <button onClick={onClick} style={{
      flex: 1, cursor: 'pointer', borderRadius: 11, padding: '11px 8px', display: 'flex',
      flexDirection: 'column', alignItems: 'center', gap: 6, fontFamily: _ssF, fontSize: 11, fontWeight: 700,
      color: filled ? _ssI : _ssH, background: filled ? accent : _ssG, border: `1px solid ${filled ? accent : _ssHR}`,
    }}>{icon}<span>{label}</span></button>);
}

function ShareSheet({ spec, onClose }) {
  const accent = (spec && spec.accent) || '#FFB454';
  const [story, setStory] = _ssS(false);
  const [tone, setTone] = _ssS('bold');
  const [msg, setMsg] = _ssS('');
  const [rendering, setRendering] = _ssS(true);
  const canvasRef = _ssR(null);
  const url = window.location.href;
  const caption = (spec && spec.captions && spec.captions[tone]) || '';

  _ssE(() => {
    let alive = true;
    setRendering(true);
    if (canvasRef.current && spec) {
      window.CST_CARD.drawCard(canvasRef.current, spec, { story }).then(() => { if (alive) setRendering(false); });
    }
    return () => { alive = false; };
  }, [story, spec]);

  const flash = (m) => { setMsg(m); setTimeout(() => setMsg(''), 1700); };

  const getBlob = () => window.CST_CARD.toBlob(canvasRef.current);

  const doSystemShare = async () => {
    try {
      const blob = await getBlob();
      const file = new File([blob], 'cs-tech-result.png', { type: 'image/png' });
      if (navigator.canShare && navigator.canShare({ files: [file] })) {
        await navigator.share({ files: [file], text: caption, title: 'CS Tech' }); return;
      }
      if (navigator.share) { await navigator.share({ text: caption, url, title: 'CS Tech' }); return; }
    } catch (e) { if (e && e.name === 'AbortError') return; }
    doDownload(); flash('Card downloaded');
  };
  const doDownload = async () => {
    try {
      const blob = await getBlob();
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = `cs-tech-${(spec.tool || 'result').toLowerCase().replace(/\W+/g, '-')}${story ? '-story' : ''}.png`;
      document.body.appendChild(a); a.click(); a.remove();
      setTimeout(() => URL.revokeObjectURL(a.href), 4000);
      flash('Card downloaded');
    } catch (e) { flash('Couldn’t save — try a screenshot'); }
  };
  const copy = async (text, what) => { try { await navigator.clipboard.writeText(text); flash(what + ' copied'); } catch (e) { flash('Copy failed'); } };
  const openIntent = (href) => window.open(href, '_blank', 'noopener,width=600,height=640');
  const xHref = `https://twitter.com/intent/tweet?text=${encodeURIComponent(caption)}&url=${encodeURIComponent(url)}`;
  const liHref = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`;

  if (!spec) return null;

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 300, display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      background: 'rgba(7,9,12,0.7)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
      animation: 'cstFadeIn .2s ease',
    }}>
      <div onClick={(e) => e.stopPropagation()} className="cst-scroll" style={{
        width: '100%', maxWidth: 520, maxHeight: '94vh', overflowY: 'auto',
        background: 'linear-gradient(180deg, #14171D 0%, #0F1115 100%)',
        borderTop: `1px solid ${accent}44`, borderLeft: `1px solid ${_ssHR}`, borderRight: `1px solid ${_ssHR}`,
        borderRadius: '20px 20px 0 0', padding: '14px 18px calc(env(safe-area-inset-bottom, 0px) + 22px)',
        boxShadow: '0 -20px 60px -20px rgba(0,0,0,0.7)', animation: 'cstSheetUp .32s cubic-bezier(.22,.9,.3,1)',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 99, background: 'rgba(236,237,241,0.18)', margin: '0 auto 14px' }} />

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div>
            <div style={{ fontFamily: _ssF, fontWeight: 800, fontSize: 17, color: _ssT, letterSpacing: -0.3 }}>Share your result</div>
            <div style={{ fontFamily: _ssF, fontSize: 11, color: _ssH, marginTop: 2 }}>Drops people straight into the tool.</div>
          </div>
          <button onClick={onClose} style={{ cursor: 'pointer', width: 32, height: 32, borderRadius: 9, background: _ssG, border: `1px solid ${_ssHR}`, color: _ssH, fontFamily: _ssF, fontSize: 15 }}>✕</button>
        </div>

        <div style={{ marginBottom: 13 }}>
          <SegToggle value={story ? 'story' : 'square'} accent={accent}
            options={[{ value: 'square', label: 'Square 1:1' }, { value: 'story', label: 'Story 9:16' }]}
            onChange={(v) => setStory(v === 'story')} />
        </div>

        {/* live card preview */}
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14, position: 'relative' }}>
          <div style={{ position: 'relative', height: story ? 380 : 300, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <canvas ref={canvasRef} style={{
              maxHeight: '100%', maxWidth: '100%', height: 'auto', width: 'auto', display: 'block',
              borderRadius: 16, boxShadow: `0 18px 50px -18px rgba(0,0,0,0.8), 0 0 0 1px ${accent}33`,
              opacity: rendering ? 0.4 : 1, transition: 'opacity .25s',
            }} />
            {rendering && <div style={{ position: 'absolute', fontFamily: _ssF, fontSize: 11, letterSpacing: 2, color: accent }}>RENDERING…</div>}
          </div>
        </div>

        {/* primary distribution */}
        <button onClick={doSystemShare} style={{
          width: '100%', border: 'none', borderRadius: 13, cursor: 'pointer', padding: '15px',
          fontFamily: _ssF, fontSize: 15, fontWeight: 800, color: _ssI, background: accent, letterSpacing: 0.3,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, marginBottom: 9,
          boxShadow: `0 10px 28px -10px ${accent}`,
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={_ssI} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="18" cy="5" r="3" /><circle cx="6" cy="12" r="3" /><circle cx="18" cy="19" r="3" />
            <line x1="8.6" y1="10.7" x2="15.4" y2="6.3" /><line x1="8.6" y1="13.3" x2="15.4" y2="17.7" />
          </svg>
          Share card
        </button>

        <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
          <ActionBtn accent={accent} onClick={doDownload} label="Save image"
            icon={<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke={_ssH} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3" /></svg>} />
          <ActionBtn accent={accent} onClick={() => openIntent(xHref)} label="Post to X"
            icon={<svg width="16" height="16" viewBox="0 0 24 24" fill={_ssH}><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231 5.45-6.231Zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77Z" /></svg>} />
          <ActionBtn accent={accent} onClick={() => openIntent(liHref)} label="LinkedIn"
            icon={<svg width="16" height="16" viewBox="0 0 24 24" fill={_ssH}><path d="M4.98 3.5C4.98 4.88 3.87 6 2.5 6S0 4.88 0 3.5 1.12 1 2.5 1s2.48 1.12 2.48 2.5zM.5 8h4V23h-4V8zm7.5 0h3.8v2.05h.05c.53-1 1.83-2.05 3.77-2.05 4.03 0 4.78 2.65 4.78 6.1V23h-4v-6.4c0-1.53-.03-3.5-2.13-3.5-2.14 0-2.47 1.67-2.47 3.39V23h-4V8z" /></svg>} />
          <ActionBtn accent={accent} onClick={() => copy(url, 'Link')} label="Copy link"
            icon={<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke={_ssH} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 13a5 5 0 0 0 7.07 0l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.07 0l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" /></svg>} />
        </div>

        {/* copy-pasteable caption with identity tones */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
          <span style={{ fontFamily: _ssF, fontSize: 10, letterSpacing: 2, color: _ssHD }}>CAPTION — PICK A VIBE</span>
          <div style={{ display: 'flex', gap: 5 }}>
            {TONES.map((tn) => (
              <button key={tn.k} onClick={() => setTone(tn.k)} style={{
                cursor: 'pointer', padding: '5px 10px', borderRadius: 8, fontFamily: _ssF, fontSize: 11, fontWeight: 700,
                color: tone === tn.k ? _ssI : _ssH, background: tone === tn.k ? accent : _ssG, border: `1px solid ${tone === tn.k ? accent : _ssHR}`,
              }}>{tn.label}</button>
            ))}
          </div>
        </div>
        <div style={{ background: _ssID, border: `1px solid ${_ssHR}`, borderRadius: 12, padding: 12 }}>
          <p style={{ margin: '0 0 10px', fontFamily: _ssF, fontSize: 13, lineHeight: 1.5, color: _ssT }}>{caption}</p>
          <button onClick={() => copy(`${caption}\n${url}`, 'Caption')} style={{
            width: '100%', cursor: 'pointer', borderRadius: 9, padding: '10px', fontFamily: _ssF, fontSize: 12.5, fontWeight: 700,
            color: accent, background: accent + '14', border: `1px solid ${accent}44`,
          }}>Copy caption + link</button>
        </div>

        {msg && <div style={{ textAlign: 'center', marginTop: 12, fontFamily: _ssF, fontSize: 12, fontWeight: 700, color: accent }}>✓ {msg}</div>}
      </div>
    </div>);
}

window.ShareSheet = ShareSheet;
