// GhostFallback.jsx — Try loading an unknown slug as a Ghost blog post
// Handles Ghost editor preview which loads posts at /{slug}/ instead of /blog/{slug}/
// Also handles draft posts via Admin API preview endpoint at /p/{uuid}/

var GhostFallback = function (props) {
  var slug = props.slug;
  var navigate = props.navigate;
  var isPreview = props.isPreview; // true when route was /p/{uuid}/

  var _state = React.useState('loading'); // loading | found | notfound
  var state = _state[0], setState = _state[1];

  var _post = React.useState(null);
  var previewPost = _post[0], setPreviewPost = _post[1];

  React.useEffect(function () {
    if (!slug) {
      setState('notfound');
      return;
    }

    // Step 1: Try Content API (published posts only)
    var tryContentApi = function () {
      if (!window.IBA_GHOST) return Promise.resolve(null);
      return window.IBA_GHOST.getPost(slug)
        .then(function (data) {
          var posts = data && data.posts ? data.posts : [];
          var post = posts[0] || (data && data.post ? data.post : null);
          if (post && post.title) return post;
          return null;
        })
        .catch(function () { return null; });
    };

    // Step 2: Try Admin API preview endpoint (drafts + published)
    var tryPreviewApi = function () {
      var params = isPreview ? 'uuid=' + encodeURIComponent(slug) : 'slug=' + encodeURIComponent(slug);
      return fetch('/api/ghost-preview?' + params)
        .then(function (res) {
          if (!res.ok) return null;
          return res.json();
        })
        .then(function (data) {
          if (data && data.posts && data.posts.length > 0) return data.posts[0];
          return null;
        })
        .catch(function () { return null; });
    };

    tryContentApi().then(function (post) {
      if (post) {
        // Found via Content API — use BlogPost component (it can refetch by slug)
        setState('found');
        return;
      }
      // Not in Content API — try Admin API for drafts
      return tryPreviewApi().then(function (draft) {
        if (draft && draft.title) {
          setPreviewPost(draft);
          setState('preview');
        } else {
          setState('notfound');
        }
      });
    });
  }, [slug, isPreview]);

  if (state === 'loading') {
    return React.createElement('div', {
      style: {
        minHeight: '40vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        fontFamily: 'var(--font-mono)',
        fontSize: '13px',
        color: 'var(--text-muted)',
      }
    }, '$ loading...');
  }

  // Published post found via Content API — delegate to BlogPost
  if (state === 'found' && window.BlogPost) {
    return React.createElement(window.BlogPost, { slug: slug, navigate: navigate });
  }

  // Draft post found via Admin API — render inline
  if (state === 'preview' && previewPost) {
    var post = previewPost;
    var draftBanner = post.status !== 'published' ? React.createElement('div', {
      style: {
        background: 'rgba(212,168,75,0.15)',
        border: '1px solid var(--amber-dim, #6b5a2e)',
        borderRadius: '4px',
        padding: '8px 16px',
        marginBottom: '24px',
        fontFamily: 'var(--font-mono, monospace)',
        fontSize: '12px',
        color: 'var(--amber, #d4a84b)',
      }
    }, '⚠ DRAFT PREVIEW — this post is not yet published') : null;

    var authorName = post.primary_author ? post.primary_author.name : (post.authors && post.authors[0] ? post.authors[0].name : '');
    var dateStr = post.published_at || post.updated_at || post.created_at || '';
    var displayDate = '';
    if (dateStr) {
      try {
        var d = new Date(dateStr);
        displayDate = d.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
      } catch (e) { displayDate = ''; }
    }

    return React.createElement('article', {
      style: {
        maxWidth: '800px',
        margin: '0 auto',
        padding: '48px 28px',
        minHeight: '60vh',
      }
    },
      draftBanner,
      post.feature_image ? React.createElement('img', {
        src: post.feature_image,
        alt: post.title || '',
        style: {
          width: '100%',
          maxHeight: '400px',
          objectFit: 'cover',
          borderRadius: '4px',
          marginBottom: '24px',
          border: '1px solid var(--border, #2a2a20)',
        }
      }) : null,
      React.createElement('h1', {
        style: {
          fontFamily: 'var(--font-mono, monospace)',
          fontSize: '28px',
          fontWeight: 700,
          color: 'var(--amber, #d4a84b)',
          marginBottom: '12px',
          lineHeight: 1.3,
        }
      }, post.title),
      React.createElement('div', {
        style: {
          fontFamily: 'var(--font-mono, monospace)',
          fontSize: '12px',
          color: 'var(--text-muted, #8a8070)',
          marginBottom: '32px',
          display: 'flex',
          gap: '16px',
          flexWrap: 'wrap',
        }
      },
        authorName ? React.createElement('span', null, authorName) : null,
        displayDate ? React.createElement('span', null, displayDate) : null,
        post.tags && post.tags.length > 0 ? React.createElement('span', null, post.tags.map(function (t) { return t.name; }).join(', ')) : null
      ),
      React.createElement('div', {
        className: 'ib-blog-content',
        style: {
          fontFamily: 'var(--font-body, sans-serif)',
          fontSize: '16px',
          lineHeight: 1.7,
          color: 'var(--text, #e8e0cc)',
        },
        dangerouslySetInnerHTML: { __html: post.html || '' },
      })
    );
  }

  // Not a blog post — show 404
  return window.NotFound
    ? React.createElement(window.NotFound, { navigate: navigate })
    : React.createElement('div', null, '404 — Not Found');
};

window.GhostFallback = GhostFallback;
