Ifekahub News β€’ Business β€’ Real Estate β€’ Electronics β€’ More
WELCOME TO IFEKA INTEGRATED VENTURES

We Find It For You.

Your trusted partner for Electronics, Real Estate, Land Surveying, Furniture and General Services.

πŸ’Ό Jobs & Opportunities

Find jobs, grants, scholarships, training and business opportunities on IfekaHub.

πŸ’Ό Job VacanciesDiscover current job opportunities.
πŸŽ“ Scholarships & TrainingFind education and skills opportunities.
πŸ’° Grants & FundingExplore legitimate funding opportunities.
πŸš€ Business OpportunitiesDiscover opportunities to grow your business.
CONNECT WITH US

Follow Ifeka on Social Media

Stay updated with trending news, business opportunities, real estate, sofas and new products.

πŸ”΅πŸ¦πŸŽ΅β–ΆοΈπŸŸ’

Our Core Services

πŸ“±

Electronics

Quality electronics and home appliances.

Learn More β†’
🏠

Real Estate

Land, houses and property sales made easy.

Learn More β†’
πŸ“

Surveying

Professional land surveying services.

Learn More β†’
πŸ›‹οΈ

Sofas & Furniture

Stylish sofas and quality furniture for your space.

Learn More β†’
πŸ› οΈ

General Services

We find and deliver what you need.

Learn More β†’

Professional Surveying Services

πŸ“

Land Surveying

Accurate land measurement and mapping services.

🏠

Property Evaluation

Professional property valuation and advisory services.

πŸ—ΊοΈ

Topographic Survey

Detailed topographic mapping and analysis.

πŸ“‹

Site Planning

Site analysis and planning for development projects.

Trusted Service Providers

πŸŽ‚

Cakes & Decorations

Delicious cakes and beautiful event decorations.

πŸŽ‰

Event Planning

Professional event planning and management.

πŸ–¨οΈ

Printing & Branding

Quality printing and branding services.

🚚

Logistics & Delivery

Reliable logistics and delivery services.

πŸ‘·

Construction

Building and construction solutions.

ELECTRONICS

Electronics

πŸ“±

Phones & Accessories

Phones and accessories from local sellers.

πŸ’»

Laptops

New and fairly-used laptops.

β˜€οΈ

Solar & Inverters

Solar panels, batteries and inverter systems.

REAL ESTATE

Find Your Next Property

🌳

Land For Sale

Discover land and estate opportunities.

🏑

Houses

Homes available for sale or rent.

🏘️

Featured Estates

Explore property investment opportunities.

SOFAS & FURNITURE

Find Quality Sofas & Furniture

πŸ›‹οΈ

Living Room Sofas

Modern sofa sets for homes and offices.

Request Sofa β†’
πŸͺ‘

Chairs & Accent Seats

Comfortable and stylish seating.

Request Furniture β†’
πŸ›οΈ

Bedroom Furniture

Beds, wardrobes and bedroom sets.

Request Set β†’
πŸͺ΅

Custom Furniture

Custom designs and sizes from furniture makers.

Request Custom β†’
IFEKA NEWSROOM

πŸ“° IfekaHub News

Verified news, original reports, business, sports and entertainment stories.

Loading published news...

IFEKA VIDEO

πŸŽ₯ Video News

Loading videos...

IFEKA ADMIN

News Administration

Only the authenticated Ifeka admin can publish and manage news.

πŸ” Admin Login

IFEKA OPPORTUNITIES HUB

πŸš€ Jobs, Grants & Opportunities

Discover opportunities from trusted external sources. IfekaHub sends users to the original website to view details and apply.

⭐ Verified Active Opportunities

Official-source listings checked by IfekaHub on 2 September 2026. Always confirm requirements before applying.

βœ“ OFFICIAL SOURCE CHECKED
Showing active verified opportunitiesπŸ”΄ Urgent deadlines firstβœ“ Official links
πŸ”„ Live verified database listings
Checking the IfekaHub opportunities database…
πŸ”΄ URGENT Β· INTERNATIONAL SCHOLARSHIP

Schwarzman Scholars 2027–28

Provider: Schwarzman Scholars / Tsinghua University

Location: Beijing, China Β· Global applicants

Eligibility: Applicants 18–28 as of 1 Aug 2027, with an undergraduate degree by then and required English proficiency.

Deadline: 9 Sept 2026 Β· 3:00 PM EDT

πŸ”΄ Closes soon🌍 International
Apply Officially β†’

Official admissions/application portal

πŸ’Ά HIGH VALUE Β· GRANT

AU–EU Youth Action Lab Entrepreneurship Grant

Provider: AU–EU Youth Lab

Location: Nigeria + 11 other eligible African countries

Eligibility: Formally registered youth-led organisations operating for at least 12 months; activities must be in an eligible country.

Funding: €31,500 for a 12-month project.

Deadline: 23 Sept 2026 Β· 13:00 CAT

⏰ Deadline approaching🌍 International
Apply / Details β†’

Official AU–EU Youth Lab grant page

πŸŽ“ SCHOLARSHIP Β· NIGERIA

Indomie Scholarship Programme 2026

Provider: Indomie Nigeria / Dufil Prima Foods

Location: Nationwide, Nigeria

Eligibility: Nigerian students entering tertiary education in the 2026/2027 session and admitted to a public or state-owned institution.

Benefit: Full tuition, renewable subject to programme requirements.

Deadline: 30 Sept 2026

🟒 OpenπŸ‡³πŸ‡¬ Nigeria
Apply Officially β†’

Official Indomie scholarship page

πŸ› οΈ GOVERNMENT Β· SKILLS

Skill-Up Artisans (SUPA)

Provider: Industrial Training Fund (ITF)

Location: Nigeria

Eligibility: Nigerian citizens/legal residents; intending and skilled artisans can register subject to programme requirements.

Benefit: Skills training, certification/licensing and artisan development pathways.

Status: Registration portal currently available.

🟒 Registration availableπŸ‡³πŸ‡¬ Nigeria
Register Officially β†’

Official ITF SUPA registration portal

πŸ’» GOVERNMENT Β· DIGITAL SKILLS

3 Million Technical Talent (3MTT)

Provider: Federal Ministry of Communications, Innovation & Digital Economy

Location: Nationwide, Nigeria

Skills: Cybersecurity, software development, AI/ML, cloud, data, UI/UX, DevOps and more.

Status: Official programme platform active; opportunities include training and talent placement pathways.

🟒 Active programmeπŸ‡³πŸ‡¬ Nigeria
Visit Official Portal β†’

Official 3MTT programme website

πŸ€– ADVANCED TRAINING

DeepTech_Ready Upskilling Programme

Provider: 3MTT / Google.org-supported programme

Location: Nigeria

Eligibility: 3MTT fellows and individuals with basic-to-intermediate knowledge in relevant technical fields; course prerequisites apply.

Focus: Data science, AI, geospatial data science, computer vision, NLP and advanced ML.

🟒 Programme page activeπŸ‡³πŸ‡¬ Nigeria
Check Official Programme β†’

Official 3MTT DeepTech_Ready page

How it works: choose a category, search if needed, then open a source. IfekaHub does not copy another site's listings; the user goes to the original source. Sports and entertainment sources are included as external opportunity directories. Always verify eligibility, deadline and application requirements on the source website.

πŸ’Ό Job Platforms

Search current vacancies through external job platforms.

🟒 Verified live content
Loading approved Jobs, News and Opportunities from IfekaHub.

πŸ’Ό Latest Jobs on IfekaHub

Approved job listings stored in the IfekaHub database.

Loading jobs...

🟒 Latest Opportunities on IfekaHub

These listings come from the IfekaHub database and can be updated from the Admin Dashboard.

πŸ”— Live listings are loaded from the IfekaHub opportunities table in Supabase.
Loading opportunities...

πŸ”Œ Plugin Categories

πŸ’Ό JobsJob boards and career platforms.
πŸ’° Government GrantsGovernment-backed MSME and public funding programmes.
πŸŽ“ ScholarshipsNigerian and international education opportunities.
🏦 Business FundingLoans, intervention funds and enterprise finance.
πŸ“š TrainingSkills, courses, certifications and development programmes.
⚽ SportsSports careers, programmes and opportunities.
🎬 EntertainmentFilm, television and creative opportunities.
REQUEST ANYTHING

Can't Find What You Need?

Tell Ifeka what you are looking for and we'll help connect you with a seller, property owner or service provider.

ADVERTISE WITH IFEKA

Put Your Business In Front Of Customers

Choose the package that gives your business the level of visibility you need.

Basic

₦5,000

Per Month


What you get

  • Business listed on the Ifeka platform
  • Business name, category, location and contact details
  • Customers can find your business through Ifeka
  • WhatsApp enquiry option

Best for: small businesses that want an affordable online presence.

Premium

₦20,000

Per Month


What you get

  • Everything in Standard
  • Premium/high-visibility placement
  • Dedicated promotional feature
  • Promotion across selected Ifeka channels
  • Priority visibility for your products or services

Best for: businesses ready for maximum exposure on Ifeka.

πŸ’‘ Why pay for advertising?

You are paying for visibility. Instead of waiting for customers to discover your business by chance, your paid listing helps put your business, products or services in front of people who are already looking for what you offer.

Note: Advertising fees cover placement and promotion on Ifeka. Actual sales are not guaranteed, because results depend on your offer, price, customer demand and the quality of your business information.

Choose a Package
IFEKA BUSINESS OPPORTUNITIES

πŸ“’ Promote on IfekaHub

Recruiters, businesses and legitimate organisations can promote approved opportunities and services.

⭐

Featured Opportunity

Give an approved job, grant-related service, training or business opportunity extra visibility.

From ₦2,000
Promote an Opportunity β†’
πŸ’Ό

Post a Job

Employers can submit a vacancy for review. Free basic posting can be combined with paid featured placement.

Free / Featured
Post a Job β†’
πŸ“£

Advertise With Us

Promote a legitimate business, product, service or training programme to IfekaHub visitors.

₦5,000+
Advertise β†’
πŸ”—

Partner / Affiliate

Use disclosed referral links only where a source provides an approved partner programme.

Commission-based
Partner With Us β†’
SUBMIT FOR REVIEW

πŸ’Ό Post a Job or Opportunity

Choose what you are posting, provide the details, select how people should apply, preview it, then submit for IfekaHub review.

πŸ“¨ Public submission: Anyone can submit a job or opportunity. Every submission is kept pending until an IfekaHub administrator verifies the official source, eligibility, deadline and application details.
1. Details 2. Application 3. Preview

1️⃣ Opportunity details

ADMIN CONTROL

πŸ› οΈ Opportunity Approval Center

Private admin area: review submissions, publish verified opportunities, feature strong listings and remove expired items.

πŸ” Admin access required

Only an authenticated IfekaHub administrator can approve, publish, feature or delete opportunity listings.

Loading...
πŸ›‘οΈ Verification rule: only publish a listing after checking the provider's original/official source, application URL, eligibility and deadline.
βž• Add an officially verified opportunity manually
Loading opportunity submissions...

About IfekaHub

Your trusted Nigerian platform for news, opportunities, services and useful information.

Who We Are

IfekaHub is a Nigerian digital platform created to connect people with useful information, opportunities, services and trusted local businesses. We bring together news, business information, real estate, land surveying, electronics, furniture and other helpful services in one place.

What We Do

Our platform publishes news and informative content, highlights jobs, grants, scholarships, training and other opportunities, and helps visitors discover property, land surveying, electronics, furniture and general services.

Our Approach to News

We aim to provide useful, clear and timely information for our readers. Where we report information from an external source, we use the source for verification and editorial reference while presenting content for the IfekaHub audience. We encourage readers to check official sources for applications, deadlines and other important decisions.

Our Mission

Our mission is to make useful information easier to find and help individuals and businesses discover opportunities, products, properties and services that can improve their lives and work.

Contact IfekaHub

If you have a question, business enquiry, correction, advertising request or suggestion, please use our Contact Us and Advertise With Us options.

Privacy Policy

Last updated: August 27, 2026

1. Introduction

Welcome to Ifekahub.com (β€œwe”, β€œour”, or β€œus”). Your privacy is important to us. This Privacy Policy explains how we collect, use, disclose, and safeguard information when you visit or use our website and services.

2. Information We Collect

We may collect information you voluntarily provide, such as your name, email address, phone number, business information, property or service enquiries, and information submitted through our forms. We may also collect basic technical information such as browser type, device information, pages visited, and approximate usage data.

3. How We Use Your Information

  • Provide, operate, and maintain the Ifekahub website.
  • Respond to requests and enquiries.
  • Improve, personalize, and expand our services.
  • Send updates or promotional information where permitted and where you have opted in.
  • Protect the website against abuse, fraud, and security threats.

4. How We Share Your Information

We may share information with service providers that help us operate the website, process requests, host data, or provide technical services. We may also disclose information where required by law or to protect our rights and users.

5. Cookies and Tracking Technologies

If cookies or similar technologies are used, they may help the website remember preferences, understand usage, and improve performance.

6. Data Security

We use reasonable administrative and technical safeguards designed to protect information. However, no internet transmission or storage system can be guaranteed to be completely secure.

7. Your Rights

Depending on applicable law, you may have rights to request access to, correction of, or deletion of certain personal information and to withdraw consent where consent is the basis for processing.

Our website may contain links to third-party websites or social platforms. Their privacy practices are governed by their own policies.

9. Children's Privacy

Our services are not directed at children under the age required by applicable law, and we do not knowingly collect personal information from children without appropriate authorization.

10. Changes to This Policy

We may update this Privacy Policy from time to time. The updated version will be posted on this page with a revised β€œLast updated” date.

11. Contact Us

If you have questions about this Privacy Policy, contact Ifekahub through the contact details published on the website.

πŸ’¬ WhatsApp ${p.source_url ? `
Read Full Story β†’ Original Source
` : ''}${articleImagesMarkup(p.content||'')} ${renderMoreNewsForArticle(p)}
πŸ“˜ Share on Facebook πŸ’¬ Share on WhatsApp
`; document.body.appendChild(overlay); overlay.querySelectorAll('.more-news-read').forEach(btn=>{ btn.addEventListener('click',()=>{ const id=btn.dataset.moreNewsId; const next=(Array.isArray(allNewsPosts)?allNewsPosts:[]).find(x=>String(x.id)===String(id)); if(next) openArticle(next); }); }); document.documentElement.classList.add('article-open'); document.body.classList.add('article-open'); document.body.style.overflow='hidden'; overlay.scrollTop=0; const likeButton=overlay.querySelector('.like-btn'); const likeState=getLikeCount(p); likeButton.classList.toggle('liked',likeState.liked); likeButton.innerHTML=`πŸ‘ Like (${likeState.count})`; likeButton.onclick=()=>toggleArticleLike(p,likeButton); const commentPanel=overlay.querySelector('.comment-panel'); const commentButton=overlay.querySelector('.comment-btn'); const commentList=overlay.querySelector('.comment-list'); renderArticleComments(p,commentList); commentButton.onclick=()=>{ commentPanel.style.display=commentPanel.style.display==='none'?'block':'none'; if(commentPanel.style.display==='block') overlay.querySelector('.comment-input').focus(); }; const nameInput=overlay.querySelector('.comment-name'); const emailInput=overlay.querySelector('.comment-email'); const anonymousInput=overlay.querySelector('.comment-anonymous'); anonymousInput.onchange=()=>{ const anon=anonymousInput.checked; nameInput.disabled=anon; emailInput.disabled=anon; nameInput.required=!anon; emailInput.required=!anon; if(anon){ nameInput.value=''; emailInput.value=''; } }; overlay.querySelector('.submit-comment').onclick=()=>{ const input=overlay.querySelector('.comment-input'); const text=input.value.trim(); if(!text) return; const anonymous=anonymousInput.checked; const name=nameInput.value.trim(); const email=emailInput.value.trim(); if(!anonymous && (!name || !email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))){ alert('Please enter your full name and a valid email address, or select Anonymous.'); return; } saveArticleComment(p,text,{name,email,anonymous}); input.value=''; renderArticleComments(p,commentList); commentPanel.style.display='block'; }; let closed=false; function closeArticle(){ if(closed) return; closed=true; overlay.remove(); document.documentElement.classList.remove('article-open'); document.body.classList.remove('article-open'); document.body.style.overflow=''; window.scrollTo(0,previousScrollY); if(window.location.hash==='news' || new URLSearchParams(window.location.search).has('news')){ history.replaceState({},document.title,window.location.pathname+window.location.hash.replace('news','')); } } overlay.querySelector('.article-close').onclick=closeArticle; overlay.addEventListener('click',e=>{if(e.target===overlay) closeArticle();}); document.addEventListener('keydown',function escClose(e){ if(e.key==='Escape'){ closeArticle(); document.removeEventListener('keydown',escClose); } },{once:false}); overlay.querySelector('.share-copy').onclick=()=>{ const status=overlay.querySelector('.share-status'); if(!articleUrl){ status.textContent='⚠️ Host the website first to create a public article link.'; setTimeout(()=>{status.textContent='';},3500); return; } copyArticleLink(articleUrl,status); }; } function openArticleFromUrl(){ const id=new URLSearchParams(window.location.search).get('news'); if(!id || !allNewsPosts.length) return; const post=allNewsPosts.find(p=>String(p.id)===String(id)); if(post) setTimeout(()=>openArticle(post),250); } function renderFeatured(posts){ const box=document.getElementById('featuredNews'); if(!posts.length){box.innerHTML='';return;} const p=posts[0]; const side=posts.slice(1,4).map(x=>`
${esc(x.category||'News')} β€’ ${esc(new Date(x.created_at).toLocaleDateString())}

${esc(x.title)}

`).join(''); box.innerHTML=` `; } function openVideoViewer(p){ const viewer=document.createElement('div'); viewer.className='video-viewer'; const articleUrl=getArticleShareUrl(p); const shareText=encodeURIComponent(getArticleShareText(p)); const waText=encodeURIComponent( getArticleShareText(p) + (articleUrl ? `\n\nRead/watch on Ifekahub: ${articleUrl}` : '\n\nβ€” Ifekahub News') ); const fbUrl=`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(articleUrl || IFEKA_PUBLIC_URL)}"e=${shareText}&hashtag=%23IfekaNews`; viewer.innerHTML=``; document.body.appendChild(viewer); document.documentElement.classList.add('video-open'); document.body.style.overflow='hidden'; let closed=false; function close(){ if(closed) return; closed=true; const v=viewer.querySelector('video'); if(v){ v.pause(); v.removeAttribute('src'); v.load(); } viewer.remove(); document.documentElement.classList.remove('video-open'); document.body.style.overflow=''; document.removeEventListener('keydown',escVideo); } function escVideo(e){ if(e.key==='Escape') close(); } const videoEl=viewer.querySelector('video'); const videoErr=viewer.querySelector('.video-viewer-error'); if(videoEl && videoErr){ videoEl.addEventListener('error',()=>{ videoErr.hidden=false; }); } viewer.querySelector('.video-viewer-close').onclick=close; viewer.addEventListener('click',e=>{ if(e.target===viewer) close(); }); viewer.querySelector('.video-share.copy').onclick=async()=>{ const status=viewer.querySelector('.video-share-status'); if(!articleUrl){ status.textContent='⚠️ Host Ifekahub first to create a public link.'; return; } await copyArticleLink(articleUrl,status); }; document.addEventListener('keydown',escVideo); } function renderVideoNews(posts){ const box=document.getElementById('videoNews'); const videos=posts.filter(p=>p.video_url).slice(0,6); if(!videos.length){ box.innerHTML='
πŸŽ₯ No video news published yet.
'; return; } box.innerHTML=videos.map(p=>`
${p.image_url ? `${esc(p.title)}` : `
πŸŽ₯VIDEO NEWS
`} β–Ά
${esc(p.category||'News')} β€’ ${esc(new Date(p.created_at).toLocaleDateString())}

${esc(p.title)}

`).join(''); } function renderNews(posts){ const box=document.getElementById('blogPosts'); if(!posts.length){ box.innerHTML='
πŸ”Ž No news matched your search.
'; return; } box.innerHTML=posts.map(p=>{ const media=p.image_url ? `
${esc(p.title)}
` : p.video_url ? `
${p.image_url ? `${esc(p.title)}` : `
πŸŽ₯
VIDEO NEWS
`} β–Ά
` : `
πŸ“° ${esc((p.category||'NEWS').toUpperCase())}
`; return `
${media}
${esc(new Date(p.created_at).toLocaleDateString())} β€’ ${esc(p.category||'News')}

${esc(p.title)}

${esc(cleanArticleText(p.content||'').slice(0,220))}${String(p.content||'').length>220?'...':''}

`; }).join(''); } function filterNews(){ const q=(document.getElementById('newsSearch')?.value||'').toLowerCase().trim(); const cat=document.getElementById('newsCategoryFilter')?.value||'all'; const filtered=allNewsPosts.filter(p=>{ const hay=`${p.title||''} ${p.content||''} ${p.category||''} ${p.author||''}`.toLowerCase(); return (!q || hay.includes(q)) && (cat==='all' || p.category===cat); }); renderNews(filtered); renderFeatured(filtered); renderVideoNews(filtered); } function renderHomeNewsPreview(posts){ const section=document.getElementById('homeNewsPreview'); const grid=document.getElementById('homeNewsPreviewGrid'); if(!section || !grid) return; const items=(posts||[]).slice(0,4); if(!items.length){ section.style.display='none'; return; } section.style.display=''; grid.innerHTML=items.map(p=>{ const img=p.image_url ? `${esc(p.title)}` : `
πŸ“°
`; const excerpt=cleanArticleText(p.content||'').replace(/\s+/g,' ').trim(); const short=excerpt.length>105 ? excerpt.slice(0,105)+'…' : excerpt; return `
${img}
${esc(p.category||'NEWS')}

${esc(p.title||'Untitled news')}

${esc(short)}

`; }).join(''); } async function loadBlogPosts(){ const box=el('blogPosts'); const {data,error}=await db.from('blog_posts') .select('id,title,content,image_url,video_url,category,author,published,created_at,source_name,source_url') .eq('published',true) .order('created_at',{ascending:false}); if(error){ if(box) box.innerHTML='

Unable to load news.

'; console.error(error); return; } allNewsPosts=data||[]; renderHomeNewsPreview(allNewsPosts); if(!allNewsPosts.length){ renderHomeNewsPreview([]); renderNews([]); renderFeatured([]); renderVideoNews([]); setText('breakingText','No breaking news yet.'); return; } setText('breakingText',allNewsPosts[0].title); filterNews(); openArticleFromUrl(); } async function publishPost(e){ e.preventDefault(); const b=document.getElementById('publishButton'); const m=document.getElementById('publishMessage'); b.disabled=true; b.textContent='Publishing...'; m.className='notice'; m.textContent='Checking admin login...'; try{ const {data:sd,error:sessionError}=await db.auth.getSession(); if(sessionError) throw sessionError; if(!sd.session){ throw new Error('Please log in first.'); } const title=document.getElementById('postTitle').value.trim(); const category=document.getElementById('postCategory').value; const author=document.getElementById('postAuthor').value.trim()||'Ifeka'; const content=document.getElementById('postContent').value.trim(); const file=document.getElementById('postImage').files[0]||null; const videoFile=document.getElementById('postVideo').files[0]||null; if(!title||!content) throw new Error('Enter headline and content.'); if(file && !file.type.startsWith('image/')){ throw new Error('The News Photo field must contain an image file.'); } if(videoFile && !videoFile.type.startsWith('video/')){ throw new Error('The News Video field must contain a video file.'); } /* Keep the browser upload practical. These are deliberately generous, but protect against accidental phone uploads of very large files. */ const MAX_IMAGE=10*1024*1024; const MAX_VIDEO=100*1024*1024; if(file && file.size>MAX_IMAGE){ throw new Error(`Photo is too large (${formatBytes(file.size)}). Maximum is 10 MB.`); } if(videoFile && videoFile.size>MAX_VIDEO){ throw new Error(`Video is too large (${formatBytes(videoFile.size)}). Maximum is 100 MB.`); } let image_url=null,video_url=null; if(file){ m.textContent='Uploading photo to Ifekahub...'; const safe=file.name.replace(/[^a-zA-Z0-9._-]/g,'_'); const path=`${sd.session.user.id}/${Date.now()}-image-${safe}`; const up=await db.storage.from(BUCKET).upload(path,file,{ upsert:false, contentType:file.type, cacheControl:'3600' }); if(up.error){ throw new Error(`Photo upload failed: ${storageErrorText(up.error,BUCKET)}`); } const pub=db.storage.from(BUCKET).getPublicUrl(path); if(pub.error || !pub.data?.publicUrl){ throw new Error(`Photo uploaded but its public URL could not be created. Make "${BUCKET}" a public bucket in Supabase Storage.`); } image_url=pub.data.publicUrl; } if(videoFile){ m.textContent='Uploading video to Ifekahub...'; const safeVideo=videoFile.name.replace(/[^a-zA-Z0-9._-]/g,'_'); const videoPath=`${sd.session.user.id}/${Date.now()}-video-${safeVideo}`; const vup=await db.storage.from(VIDEO_BUCKET).upload(videoPath,videoFile,{ upsert:false, contentType:videoFile.type||'video/mp4', cacheControl:'3600' }); if(vup.error){ throw new Error(`Video upload failed: ${storageErrorText(vup.error,VIDEO_BUCKET)}`); } const vpub=db.storage.from(VIDEO_BUCKET).getPublicUrl(videoPath); if(vpub.error || !vpub.data?.publicUrl){ throw new Error(`Video uploaded but its public URL could not be created. Make "${VIDEO_BUCKET}" a public bucket in Supabase Storage.`); } video_url=vpub.data.publicUrl; } m.textContent='Saving news to Supabase...'; const ins=await db.from('blog_posts').insert({ title,content,image_url,video_url,category,author,published:true }); if(ins.error){ throw new Error(`News database save failed: ${ins.error.message}`); } m.className='notice'; m.textContent='βœ… News published successfully. Photo/video is stored in Supabase.'; const titleEl=el('postTitle'), contentEl=el('postContent'), imageEl=el('postImage'), videoEl=el('postVideo'); if(titleEl) titleEl.value=''; if(contentEl) contentEl.value=''; if(imageEl) imageEl.value=''; if(videoEl) videoEl.value=''; // Refresh independently: a missing optional homepage element must never // turn a successful upload into a false publishing error. try{ await loadBlogPosts(); }catch(refreshErr){ console.warn('Blog refresh warning:',refreshErr); } try{ await loadAdminPosts(); }catch(refreshErr){ console.warn('Admin refresh warning:',refreshErr); } try{ await checkStorage(); }catch(refreshErr){ console.warn('Storage refresh warning:',refreshErr); } try{ await checkNewContent(true); }catch(alertErr){ console.warn('Alert refresh warning:',alertErr); } }catch(err){ console.error(err); m.className='notice error'; m.textContent='❌ '+(err?.message||'Publishing failed. Please try again.'); }finally{ b.disabled=false; b.textContent='πŸ“° Publish News'; } } function formatBytes(n){ if(!Number.isFinite(n)) return 'unknown size'; const units=['B','KB','MB','GB']; let i=0,v=n; while(v>=1024 && i=10||i===0?0:1)} ${units[i]}`; } function storageErrorText(err,bucket){ const raw=String(err?.message||err||'Unknown storage error'); const lower=raw.toLowerCase(); if(lower.includes('bucket') && (lower.includes('not found')||lower.includes('does not exist'))){ return `Storage bucket "${bucket}" does not exist. Create it in Supabase Storage.`; } if(lower.includes('row-level security')||lower.includes('policy')){ return `Supabase Storage permission was denied for "${bucket}". Add the Storage policies shown in the setup instructions.`; } if(lower.includes('payload')||lower.includes('too large')){ return `The file is too large for the current Storage limits.`; } return raw; } async function checkStorage(){ const box=document.getElementById('storageStatus'); if(!box) return; try{ const {data:sd}=await db.auth.getSession(); if(!sd.session){ box.textContent='Storage: log in to test photo/video uploads.'; return; } const results=await Promise.all([ db.storage.from(BUCKET).list('',{limit:1}), db.storage.from(VIDEO_BUCKET).list('',{limit:1}) ]); const badIndex=results.findIndex(x=>x.error); if(badIndex>=0){ const bad=results[badIndex]; const badBucket=badIndex===0?BUCKET:VIDEO_BUCKET; box.className='notice error'; box.innerHTML=`❌ Storage is not ready. ${esc(storageErrorText(bad.error,badBucket))}
Check the ${esc(badBucket)} bucket and its Storage policies.`; }else{ box.className='notice'; box.textContent='βœ… Photo and video storage is connected.'; } }catch(err){ box.className='notice error'; box.textContent='❌ Storage check failed: '+(err?.message||'Unknown error'); } } async function loadAdminPosts(){ const box=el('adminPosts'); if(!box)return; box.innerHTML='

Loading published news...

'; try{ const {data:sd}=await db.auth.getSession(); const token=sd?.session?.access_token; if(!token) throw new Error('Please log in as the IfekaHub administrator first.'); const [blogRes,publishedRes]=await Promise.all([ db.from('blog_posts').select('id,title,category,created_at').eq('published',true).order('created_at',{ascending:false}), fetch('/api/published-news',{headers:{Authorization:'Bearer '+token},cache:'no-store'}).then(async r=>{const p=await r.json().catch(()=>({})); if(!r.ok||p.ok===false) throw new Error(p.error||('Published news HTTP '+r.status)); return p;}) ]); if(blogRes.error) throw blogRes.error; const incomingData=publishedRes.news||[]; const rows=[ ...(blogRes.data||[]).map(p=>({kind:'manual',id:p.id,title:p.title,category:p.category||'News',time:p.created_at})), ...incomingData.map(p=>({kind:'external',id:p.id,title:p.title,category:p.category||'News',time:p.published_at||p.created_at})) ].sort((a,b)=>new Date(b.time||0)-new Date(a.time||0)); if(!rows.length){box.innerHTML='

No published posts yet.

';return;} box.innerHTML=rows.map(p=>`
${esc(p.title)}
${esc(p.category)} β€’ ${new Date(p.time).toLocaleDateString()} β€’ ${p.kind==='external'?'Published News':'Manual Post'}
`).join(''); }catch(error){ box.innerHTML='
'+esc(error.message||'Unable to load published news.')+'
'; } } async function deletePost(id){if(!confirm('Delete this news post?'))return;const {error}=await db.from('blog_posts').delete().eq('id',id);if(error){alert('Delete failed: '+error.message);return;}await loadAdminPosts();await loadBlogPosts();} async function editPublishedPost(kind,id){ try{ if(kind==='manual'){ const {data,error}=await db.from('blog_posts').select('id,title,content,image_url,video_url,category,author,published').eq('id',id).eq('published',true).single(); if(error) throw error; openIfekaPublishedEditModal({kind:'manual',id:data.id,title:data.title,content:data.content||'',category:data.category||'Nigeria',author:data.author||'Ifeka',image_url:data.image_url||'',video_url:data.video_url||''}); }else{ const {data:sd}=await db.auth.getSession(); const token=sd?.session?.access_token; if(!token){alert('Please log in as the IfekaHub administrator first.');return;} const r=await fetch('/api/published-news',{headers:{Authorization:'Bearer '+token},cache:'no-store'}); const payload=await r.json().catch(()=>({})); if(!r.ok||payload.ok===false)throw new Error(payload.error||('HTTP '+r.status)); const data=(payload.news||[]).find(x=>String(x.id)===String(id)); if(!data) throw new Error('Published news story was not found. Refresh the admin list and try again.'); openIfekaPublishedEditModal({kind:'external',id:data.id,title:data.title,content:cleanArticleText(data.summary||''),category:data.category||'Nigeria',author:'Ifeka',image_url:data.image_url||'',video_url:extractNewsMedia(data.summary||'').video_url||''}); } }catch(e){alert('Could not open editor: '+(e?.message||e));} } function openIfekaPublishedEditModal(post){ const m=document.getElementById('ifekaPublishedEditModal'); if(!m)return; document.getElementById('ifekaEditPostKind').value=post.kind; document.getElementById('ifekaEditPostId').value=post.id; document.getElementById('ifekaEditPostTitle').value=post.title||''; document.getElementById('ifekaEditPostCategory').value=post.category||'Nigeria'; document.getElementById('ifekaEditPostAuthor').value=post.author||'Ifeka'; document.getElementById('ifekaEditPostContent').value=post.content||''; document.getElementById('ifekaEditPostImage').value=post.image_url||''; document.getElementById('ifekaEditPostVideo').value=post.video_url||''; document.getElementById('ifekaEditPostMessage').textContent=''; m.classList.add('open'); } function closeIfekaPublishedEditModal(){const m=document.getElementById('ifekaPublishedEditModal');if(m)m.classList.remove('open');} async function saveIfekaPublishedEdit(){ const kind=document.getElementById('ifekaEditPostKind').value,id=document.getElementById('ifekaEditPostId').value; const title=document.getElementById('ifekaEditPostTitle').value.trim(),category=document.getElementById('ifekaEditPostCategory').value,author=document.getElementById('ifekaEditPostAuthor').value.trim()||'Ifeka',content=document.getElementById('ifekaEditPostContent').value.trim(),image_url=document.getElementById('ifekaEditPostImage').value.trim(),video_url=document.getElementById('ifekaEditPostVideo').value.trim(); const msg=document.getElementById('ifekaEditPostMessage'); const btn=document.getElementById('ifekaEditPostSave'); if(!title||!content){msg.textContent='Headline and news content are required.';return;} if(content.length<50){msg.textContent='Please provide a fuller news brief (at least 50 characters).';return;} if(image_url&&!/^https?:\/\//i.test(image_url)){msg.textContent='Picture URL must start with http:// or https://';return;} if(video_url&&!/^https?:\/\//i.test(video_url)){msg.textContent='Video URL must start with http:// or https://';return;} btn.disabled=true;msg.textContent='Saving changes…'; try{ const {data:sd}=await db.auth.getSession();const token=sd?.session?.access_token;if(!token)throw new Error('Please log in as the IfekaHub administrator first.'); const body={kind,id,action:'edit_published',title,category,author,content,summary:content,image_url,video_url}; const r=await fetch('/api/review-action',{method:'POST',headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},body:JSON.stringify(body)}); const payload=await r.json().catch(()=>({}));if(!r.ok||payload.ok===false)throw new Error(payload.error||('HTTP '+r.status)); msg.textContent='βœ… Changes saved successfully.'; await loadAdminPosts(); if(typeof loadBlogPosts==='function')await loadBlogPosts(); if(typeof loadLiveNews==='function')await loadLiveNews(); setTimeout(closeIfekaPublishedEditModal,500); }catch(e){msg.textContent='❌ Save failed: '+(e?.message||e);}finally{btn.disabled=false;} } async function deletePublishedIncomingNews(id){ if(!confirm('Delete this published news story permanently?'))return; try{ const {data:sd}=await db.auth.getSession(); const token=sd?.session?.access_token; if(!token){alert('Please log in as the IfekaHub administrator first.');return;} const r=await fetch('/api/review-action',{method:'POST',headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},body:JSON.stringify({kind:'news',id:String(id),action:'delete_published'})}); const payload=await r.json().catch(()=>({})); if(!r.ok||payload.ok===false)throw new Error(payload.error||('HTTP '+r.status)); await loadAdminPosts(); await loadBlogPosts(); if(typeof loadLiveNews==='function') await loadLiveNews(); }catch(e){alert('Delete failed: '+(e?.message||e));} } // IFEKAHUB OPPORTUNITIES β€” plugin registry + dynamic Supabase listings const opportunityPlugins=[ {id:'jobberman',name:'Jobberman',icon:'πŸ’Ό',category:'jobs',description:'Nigeria-focused jobs and career opportunities.',url:'https://www.jobberman.com/jobs',search:(q,l)=>'https://www.jobberman.com/jobs'+(q?('?search='+encodeURIComponent(q)):'')}, {id:'myjobmag',name:'MyJobMag',icon:'πŸ“‹',category:'jobs',description:'Nigeria job vacancies and career opportunities.',url:'https://www.myjobmag.com/jobs',search:(q,l)=>'https://www.myjobmag.com/jobs'+(q?('?search='+encodeURIComponent(q)):'')}, {id:'linkedin',name:'LinkedIn Jobs',icon:'πŸ”—',category:'jobs',description:'Professional, remote and international opportunities.',url:'https://www.linkedin.com/jobs/',search:(q,l)=>'https://www.linkedin.com/jobs/search/?keywords='+encodeURIComponent(q||'')+(l?'&location='+encodeURIComponent(l):'')}, {id:'indeed',name:'Indeed Nigeria',icon:'πŸ”Ž',category:'jobs',description:'Search jobs from employers and recruitment sources.',url:'https://ng.indeed.com/',search:(q,l)=>'https://ng.indeed.com/jobs?q='+encodeURIComponent(q||'')+(l?'&l='+encodeURIComponent(l):'')}, {id:'smedan-cgs',name:'SMEDAN Conditional Grant Scheme',icon:'πŸ’°',category:'grants',description:'Official SMEDAN programme information for grant support.',url:'https://smedan.gov.ng/our-programs/cgs/',search:(q,l)=>'https://smedan.gov.ng/our-programs/cgs/'}, {id:'smedan-programs',name:'SMEDAN Programmes',icon:'πŸ‡³πŸ‡¬',category:'grants',description:'Official SMEDAN directory of MSME support programmes.',url:'https://smedan.gov.ng/our-programs/',search:(q,l)=>'https://smedan.gov.ng/our-programs/'}, {id:'smedan-portal',name:'SMEDAN Funding & Support Portal',icon:'πŸ›οΈ',category:'grants',description:'Official MSME support and funding portal.',url:'https://funds.smedan.gov.ng/',search:(q,l)=>'https://funds.smedan.gov.ng/'}, {id:'fme-scholarships',name:'Federal Ministry of Education',icon:'πŸŽ“',category:'scholarships',description:'Official Federal Scholarship Board information.',url:'https://education.gov.ng/federal-scholarships-board/',search:(q,l)=>'https://education.gov.ng/federal-scholarships-board/'}, {id:'fme-scholarship-portal',name:'Federal Scholarship Portal',icon:'πŸ“š',category:'scholarships',description:'Federal Ministry of Education scholarship portal.',url:'https://scholarship.education.gov.ng/scholarships',search:(q,l)=>'https://scholarship.education.gov.ng/scholarships'}, {id:'boi',name:'Bank of Industry (BOI)',icon:'🏦',category:'funding',description:'Official BOI financing and business support.',url:'https://www.boi.ng/',search:(q,l)=>'https://www.boi.ng/'}, {id:'boi-msmes',name:'BOI MSME Support',icon:'πŸ’Ό',category:'funding',description:'BOI MSME lending and business advisory services.',url:'https://www.boi.ng/who-we-serve/msmes/',search:(q,l)=>'https://www.boi.ng/who-we-serve/msmes/'}, {id:'boi-intervention',name:'BOI Intervention Funds',icon:'πŸ’³',category:'funding',description:'Official BOI intervention-fund information.',url:'https://www.boi.ng/impact/intervention-funds/',search:(q,l)=>'https://www.boi.ng/impact/intervention-funds/'}, {id:'smedan-training',name:'SMEDAN Programmes',icon:'πŸ“š',category:'training',description:'Entrepreneurship and business-development programmes.',url:'https://smedan.gov.ng/our-programs/',search:(q,l)=>'https://smedan.gov.ng/our-programs/'}, {id:'fifa-careers',name:'FIFA Careers',icon:'⚽',category:'sports',description:'Official FIFA careers and football-industry opportunities.',url:'https://inside.fifa.com/careers',search:(q,l)=>'https://inside.fifa.com/careers'}, {id:'world-athletics',name:'World Athletics',icon:'πŸƒ',category:'sports',description:'Official global athletics organisation and career opportunities.',url:'https://worldathletics.org/about-iaaf/careers',search:(q,l)=>'https://worldathletics.org/about-iaaf/careers'}, {id:'netflix-jobs',name:'Netflix Jobs',icon:'🎬',category:'entertainment',description:'Official careers across film, television and entertainment technology.',url:'https://jobs.netflix.com/',search:(q,l)=>'https://jobs.netflix.com/'}, {id:'disney-careers',name:'Disney Careers',icon:'🎭',category:'entertainment',description:'Official careers across entertainment, media and creative production.',url:'https://www.disneycareers.com/',search:(q,l)=>'https://www.disneycareers.com/'}, {id:'filmfreeway',name:'FilmFreeway',icon:'πŸŽ₯',category:'entertainment',description:'Film festivals, screen projects and creative opportunities.',url:'https://filmfreeway.com/',search:(q,l)=>'https://filmfreeway.com/'} ]; const opportunityCategoryInfo={ jobs:{title:'πŸ’Ό Job Platforms',desc:'Search current vacancies through external job platforms.'}, grants:{title:'πŸ’° Government Grants & MSME Support',desc:'Official government and public-sector grant/support sources.'}, scholarships:{title:'πŸŽ“ Scholarships',desc:'Official Nigerian scholarship and education opportunity sources.'}, funding:{title:'🏦 Business Funding',desc:'Official finance and enterprise-support sources.'}, training:{title:'πŸ“š Training & Skills',desc:'Training, entrepreneurship and professional development sources.'}, sports:{title:'⚽ Sports Opportunities',desc:'Sports careers, programmes and opportunities from established organisations.'}, entertainment:{title:'🎬 Entertainment & Creative',desc:'Film, television, media and creative-industry opportunities.'}, business:{title:'πŸͺ Business Opportunities',desc:'Business, partnership and enterprise opportunities.'} }; function renderOpportunityPlugins(category='jobs'){ const box=el('oppPluginGrid'); if(!box)return; const info=opportunityCategoryInfo[category]||opportunityCategoryInfo.jobs; setText('oppCategoryHeading',info.title); setText('oppCategoryDescription',info.desc); const items=opportunityPlugins.filter(x=>x.category===category); box.innerHTML=items.map(x=>`
${x.icon}

${esc(x.name)}

EXTERNAL SOURCE

${esc(x.description)}

βœ“ Source link provided by IfekaHub
Open Source
`).join(''); if(!items.length)box.innerHTML='
No source has been added to this category yet.
'; } function openOpportunitySource(id){ const p=opportunityPlugins.find(x=>x.id===id); if(!p)return; const q=(el('oppSearch')?.value||'').trim(), l=(el('oppLocation')?.value||'').trim(); window.open(p.search(q,l),'_blank','noopener,noreferrer'); } function searchOpportunityPlugins(){ const type=el('oppType')?.value||'jobs'; renderOpportunityPlugins(type); const q=(el('oppSearch')?.value||'').trim(), l=(el('oppLocation')?.value||'').trim(); const r=el('oppResults'); if(!r)return; const items=opportunityPlugins.filter(x=>x.category===type); if(!items.length){r.innerHTML='
No plugins are available for this category yet.
';return;} r.innerHTML=items.map(x=>`
${esc(x.name)} β€’ EXTERNAL SOURCE

${esc(q||'Latest opportunities')}

${esc(l||'Any location')} β€” Open the source for current listings, eligibility and application details.

View & Apply β†’
`).join(''); } const ifekaOpportunityDetails = window.ifekaOpportunityDetails = window.ifekaOpportunityDetails || {}; function showOpportunityDetails(id){ const o=ifekaOpportunityDetails[String(id)]; if(!o)return; const existing=document.getElementById('ifekaDetailsOverlay'); if(existing) existing.remove(); const url=o.application_url||o.application_link||''; const deadline=o.deadline?new Date(o.deadline+'T00:00:00'):null; const deadlineText=deadline&&!isNaN(deadline)?deadline.toLocaleDateString():'No deadline listed'; const modal=document.createElement('div'); modal.id='ifekaDetailsOverlay'; modal.className='details-overlay'; modal.innerHTML=``; modal.addEventListener('click',e=>{if(e.target===modal)modal.remove()}); document.body.appendChild(modal); } function renderDynamicOpportunity(o){ const key=String(o.id); ifekaOpportunityDetails[key]=o; const deadline=o.deadline?new Date(o.deadline+'T00:00:00'):null; const deadlineText=deadline?deadline.toLocaleDateString():'No deadline listed'; const featured=(o.promotion_status==='active'||o.featured); const workType=o.employment_type||o.work_mode||''; const salary=o.salary||''; return `
${esc((o.category||'opportunity').toUpperCase())}${featured?'⭐ FEATURED':''}

${esc(o.title||'Opportunity')}

Provider: ${esc(o.provider||'Not specified')}

Location: ${esc(o.location||'Not specified')}

${workType?`

Employment: ${esc(workType)}

`:''} ${salary?`

Salary / Value: ${esc(salary)}

`:''}

${esc(o.description||'')}

Deadline: ${esc(deadlineText)}

`; } async function saveDynamicOpportunity(e){ e.preventDefault(); const msg=el('opportunityAdminMessage'), btn=el('oppSaveButton'); if(msg){msg.className='notice';msg.textContent='Saving opportunity...';} if(btn)btn.disabled=true; const row={ title:el('oppTitleAdmin').value.trim(), provider:el('oppProviderAdmin').value.trim(), category:el('oppCategoryAdmin').value, location:el('oppLocationAdmin').value.trim(), deadline:el('oppDeadlineAdmin').value||null, application_url:el('oppUrlAdmin').value.trim(), source:el('oppSourceAdmin').value.trim()||el('oppProviderAdmin').value.trim(), description:el('oppDescriptionAdmin').value.trim(), featured:el('oppFeaturedAdmin').checked, is_active:true, approval_status:'approved', status:'Active', published:true }; const {error}=await db.from('opportunities').insert(row); if(error){ if(msg){msg.className='notice error';msg.textContent='❌ Save failed: '+error.message;} }else{ if(msg){msg.className='notice';msg.textContent='βœ… Opportunity added successfully.';} document.querySelector('#opportunityAdminBox form')?.reset(); await loadAdminOpportunities(); await loadDynamicOpportunities(); } if(btn)btn.disabled=false; } async function loadAdminOpportunities(){ const box=el('adminOpportunities'); if(!box)return; const {data,error}=await db.from('opportunities').select('id,title,category,provider,deadline,is_active,featured').order('created_at',{ascending:false}); if(error){box.innerHTML='
Run the opportunities SQL setup first: '+esc(error.message)+'
';return;} if(!data?.length){box.innerHTML='

No opportunities have been added yet.

';return;} box.innerHTML=data.map(o=>`
${esc(o.title)}
${esc(o.provider||'')} β€’ ${esc(o.category||'')} β€’ ${o.deadline?esc(o.deadline):'No deadline'} ${o.featured?'β€’ ⭐ Featured':''}
`).join(''); } async function deleteDynamicOpportunity(id){ if(!confirm('Delete this opportunity?'))return; const {error}=await db.from('opportunities').delete().eq('id',id); if(error){alert('Delete failed: '+error.message);return;} await loadAdminOpportunities(); await loadDynamicOpportunities(); } function showJobStep(n){ ['jobFormStep1','jobFormStep2','jobFormStep3'].forEach((id,i)=>{ const x=document.getElementById(id); if(x)x.style.display=(i+1===n?'block':'none'); }); if(n===2) updateApplicationFields(); if(n===3) window.scrollTo({top:document.getElementById('post-opportunity').offsetTop-20,behavior:'smooth'}); } function updateApplicationFields(){ const method=document.getElementById('pubOppApplyMethod')?.value; const ids=['pubOppUrl','pubOppWhatsapp','pubOppEmail','pubOppPhone']; ids.forEach(id=>{const x=document.getElementById(id);if(x)x.style.display='none';}); if(method==='external') document.getElementById('pubOppUrl').style.display='block'; if(method==='whatsapp') document.getElementById('pubOppWhatsapp').style.display='block'; if(method==='email') document.getElementById('pubOppEmail').style.display='block'; if(method==='phone') document.getElementById('pubOppPhone').style.display='block'; } function getApplicationValue(){ const method=document.getElementById('pubOppApplyMethod').value; if(method==='external') return document.getElementById('pubOppUrl').value.trim(); if(method==='whatsapp') return document.getElementById('pubOppWhatsapp').value.trim(); if(method==='email') return document.getElementById('pubOppEmail').value.trim(); if(method==='phone') return document.getElementById('pubOppPhone').value.trim(); return ''; } function previewOpportunity(){ const method=document.getElementById('pubOppApplyMethod').value; const value=getApplicationValue(); if(!method || !value){alert('Please choose an application method and enter the required application detail.');return;} if(method==='external' && !/^https?:\/\//i.test(value)){alert('Please enter a complete URL beginning with https://');return;} if(!document.getElementById('pubOppConsent').checked){alert('Please confirm the submission statement.');return;} const esc2 = s => String(s||'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m])); const preview=document.getElementById('opportunityPreview'); preview.innerHTML = '
'+esc2(document.getElementById('pubOppType').value)+'
'+ '

'+esc2(document.getElementById('pubOppTitle').value)+'

'+ '

Provider: '+esc2(document.getElementById('pubOppProvider').value)+'

'+ '

Location: '+esc2(document.getElementById('pubOppLocation').value||'Not specified')+'

'+ '

Work mode: '+esc2(document.getElementById('pubOppWorkMode').value||'Not specified')+'

'+ '

Salary / value: '+esc2(document.getElementById('pubOppSalary').value||'Not specified')+'

'+ '

Application: '+esc2(method)+' β€” '+esc2(value)+'

'+ '

Deadline: '+esc2(document.getElementById('pubOppDeadline').value||'Not specified')+'

'+ '

'+esc2(document.getElementById('pubOppDescription').value)+'

'; showJobStep(3); } async function submitPublicOpportunity(e){ e.preventDefault(); const msg=document.getElementById('publicOpportunityMessage'); const btn=document.getElementById('pubOppButton'); const method=document.getElementById('pubOppApplyMethod').value; const value=getApplicationValue(); if(!method || !value){showJobStep(2);alert('Please complete the application method.');return;} if(method==='external' && !/^https?:\/\//i.test(value)){showJobStep(2);alert('Please enter a valid https:// URL.');return;} if(btn)btn.disabled=true; if(msg)msg.textContent='Submitting for review...'; const promo=document.getElementById('pubOppPromotion').value; const row={ title:document.getElementById('pubOppTitle').value.trim(), provider:document.getElementById('pubOppProvider').value.trim(), category:document.getElementById('pubOppType').value, location:document.getElementById('pubOppLocation').value.trim(), deadline:document.getElementById('pubOppDeadline').value||null, application_url:value || null, description:document.getElementById('pubOppDescription').value.trim(), source:document.getElementById('pubOppProvider').value.trim(), is_active:false, approval_status:'pending', promotion_status:promo==='free'?'none':'pending_payment', promotion_plan:promo, submitter_contact:document.getElementById('pubOppContact').value.trim(), work_mode:document.getElementById('pubOppWorkMode').value.trim(), salary:document.getElementById('pubOppSalary').value.trim(), requirements:document.getElementById('pubOppQualification').value.trim() + (document.getElementById('pubOppExperience').value.trim() ? '\nExperience: '+document.getElementById('pubOppExperience').value.trim() : '') }; try{ const r=await fetch('/api/submit-opportunity',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(row)}); const payload=await r.json().catch(()=>({})); if(!r.ok||payload.ok===false) throw new Error(payload.error||('HTTP '+r.status)); if(msg)msg.textContent='βœ… Submitted successfully. Your listing is pending IfekaHub approval.'; document.getElementById('publicOpportunityForm').reset(); updateApplicationFields(); showJobStep(1); }catch(err){ if(msg)msg.textContent='❌ Submission failed: '+(err?.message||'Please try again.'); }finally{ if(btn)btn.disabled=false; } } function oppEsc(s){ return String(s ?? '').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m])); } async function loadOpportunityAdmin(){ const list=document.getElementById('opportunityAdminList'); const count=document.getElementById('oppAdminCount'); const msg=document.getElementById('opportunityAdminMessage'); if(!list || typeof db==='undefined') return; list.innerHTML='
Loading...
'; try{ const filter=document.getElementById('oppAdminFilter')?.value||'all'; let query=db.from('opportunities').select('*').order('created_at',{ascending:false}); if(filter!=='all') query=query.eq('approval_status',filter); const {data,error}=await query; if(error) throw error; const rows=data||[]; const today=new Date(); today.setHours(0,0,0,0); // Mark expired approved listings inactive. This runs only in the authenticated admin panel. const expired=rows.filter(o=>o.is_active===true && o.approval_status==='approved' && o.deadline && String(o.deadline).slice(0,10)db.from('opportunities').update({is_active:false,status:'Expired',published:false}).eq('id',o.id))); expired.forEach(o=>{o.is_active=false;o.status='Expired';o.published=false;}); } if(count) count.textContent=rows.length+' listing'+(rows.length===1?'':'s'); if(!rows.length){list.innerHTML='
No listings in this filter.
';return;} list.innerHTML=rows.map(o=>{ const status=o.approval_status||'pending'; const promo=o.promotion_status||'none'; const active=o.is_active===true && o.published===true && status==='approved'; const expired=o.deadline && String(o.deadline).slice(0,10)
${oppEsc(o.category||'opportunity')}

${oppEsc(o.title||'Untitled')}

Provider: ${oppEsc(o.provider||'')}

${oppEsc(status)}${active?'published':expired?'expired':oppEsc(o.status||'draft')}${o.featured?'⭐ featured':''}

${oppEsc(o.description||'')}

Location: ${oppEsc(o.location||'Not specified')}   Deadline: ${oppEsc(o.deadline||'Not specified')}

Official source: ${oppEsc(o.source||o.provider||'Not supplied')}

${url?`

πŸ”— Open source / application page β†’

`:''}
${status!=='approved'?``:''} ${status!=='rejected'?``:''} ${status==='approved'&&active?``:''} ${status==='approved'&&!o.featured&&!expired?``:''} ${status==='approved'&&o.featured?``:''} ${status==='rejected'?``:''}
`; }).join(''); }catch(err){ if(count) count.textContent='Connection error'; list.innerHTML='
Could not load submissions: '+oppEsc(err?.message||'Unknown error')+'
'; } } async function addOfficialOpportunity(e){ e.preventDefault(); const msg=document.getElementById('opportunityAdminMessage'), btn=document.getElementById('adminOppSave'); if(btn)btn.disabled=true; if(msg){msg.style.display='block';msg.className='notice';msg.textContent='Saving verified opportunity...';} const url=document.getElementById('adminOppUrl').value.trim(); if(!/^https:\/\//i.test(url)){if(msg){msg.className='notice error';msg.textContent='❌ Use the official HTTPS application/source URL.';}if(btn)btn.disabled=false;return;} const row={ title:document.getElementById('adminOppTitle').value.trim(), provider:document.getElementById('adminOppProvider').value.trim(), category:document.getElementById('adminOppCategory').value, location:document.getElementById('adminOppLocation').value.trim(), deadline:document.getElementById('adminOppDeadline').value||null, application_url:url, source:document.getElementById('adminOppSource').value.trim(), description:document.getElementById('adminOppDescription').value.trim(), featured:document.getElementById('adminOppFeatured').checked, is_active:true, approval_status:'approved', status:'Active', published:true, promotion_status:document.getElementById('adminOppFeatured').checked?'active':'none' }; try{ const {error}=await db.from('opportunities').insert(row); if(error)throw error; if(msg){msg.className='notice';msg.textContent='βœ… Verified opportunity added and published.';} document.getElementById('verifiedAdminForm').reset(); await loadOpportunityAdmin(); await loadVerifiedDatabaseOpportunities(true); }catch(err){ if(msg){msg.className='notice error';msg.textContent='❌ Save failed: '+(err?.message||'Unknown error');} }finally{if(btn)btn.disabled=false;} } function deactivateOpportunity(id){ opportunityAdminUpdate(id,{is_active:false,status:'Inactive',published:false},'Listing unpublished.'); } async function opportunityAdminUpdate(id, patch, successText){ const msg=document.getElementById('opportunityAdminMessage'); try{ const {error}=await db.from('opportunities').update(patch).eq('id',id); if(error) throw error; if(msg){msg.style.display='block';msg.className='notice';msg.textContent='βœ… '+successText;} await loadOpportunityAdmin(); }catch(err){ if(msg){msg.style.display='block';msg.className='notice error';msg.textContent='❌ '+(err?.message||'Update failed');} } } function approveOpportunity(id){ opportunityAdminUpdate( id, {approval_status:'approved',is_active:true,status:'Active',published:true}, 'Listing approved and published.' ); } function rejectOpportunity(id){ opportunityAdminUpdate( id, {approval_status:'rejected',is_active:false,status:'Rejected',published:false}, 'Listing rejected.' ); } function featureOpportunity(id){ opportunityAdminUpdate(id,{featured:true,promotion_status:'active',promotion_start:new Date().toISOString()},'Listing marked as featured.'); } function unfeatureOpportunity(id){ opportunityAdminUpdate(id,{featured:false,promotion_status:'none',promotion_start:null,promotion_end:null},'Featured placement removed.'); } async function deleteOpportunity(id){ if(!confirm('Delete this opportunity permanently?')) return; try{ const {error}=await db.from('opportunities').delete().eq('id',id); if(error) throw error; await loadOpportunityAdmin(); }catch(err){ const msg=document.getElementById('opportunityAdminMessage'); if(msg){msg.style.display='block';msg.className='notice error';msg.textContent='❌ '+(err?.message||'Delete failed');} } } async function removeIfekaTestOpportunities(){ if(!confirm('Remove the two IfekaHub test opportunities: Administrative Officer and Marketing & Business Development Opportunity?'))return; const msg=document.getElementById('opportunityAdminMessage'); if(msg){msg.style.display='block';msg.className='notice';msg.textContent='Removing the two test opportunities...';} try{ const {data:sd}=await db.auth.getSession(); if(!sd?.session)throw new Error('Please log in as the IfekaHub administrator first.'); const r=await fetch('/api/remove-test-opportunities',{method:'POST',headers:{Authorization:`Bearer ${sd.session.access_token}`}}); const data=await r.json().catch(()=>({})); if(!r.ok||!data.ok)throw new Error(data.error||`Request failed (${r.status})`); if(msg){msg.className='notice';msg.textContent=`βœ… Removed ${data.deleted||0} test opportunit${data.deleted===1?'y':'ies'}.`;} await loadOpportunityAdmin(); await loadVerifiedDatabaseOpportunities(true); }catch(err){ if(msg){msg.className='notice error';msg.textContent='❌ '+(err?.message||'Could not remove the test opportunities');} } } function goToAdminLogin(){ const target=document.getElementById('adminBox')||document.getElementById('loginBox'); if(target){target.scrollIntoView({behavior:'smooth',block:'start'});} else{alert('Please use the IfekaHub Admin Login section.');} } async function secureOpportunityAdmin(){ const panel=document.getElementById('opportunityAdminPanel'); const gate=document.getElementById('opportunityAdminGate'); if(!panel || typeof db==='undefined') return; try{ const {data}=await db.auth.getSession(); const session=data?.session; panel.classList.toggle('admin-authorized',!!session); if(gate) gate.style.display=session?'none':'block'; if(session && typeof loadOpportunityAdmin==='function') loadOpportunityAdmin(); }catch(err){ panel.classList.remove('admin-authorized'); if(gate)gate.style.display='block'; } } document.addEventListener('DOMContentLoaded',()=>{secureOpportunityAdmin();}); document.addEventListener('DOMContentLoaded',()=>{ loadBlogPosts(); checkSession(); renderOpportunityPlugins('jobs'); loadDynamicOpportunities(); }); document.addEventListener('DOMContentLoaded',()=>{loadBlogPosts();checkSession();renderOpportunityPlugins('jobs');}); /* IFEKAHUB AUTO CONTENT V1 β€” database-connected News, Jobs & Opportunities */ async function loadAutoNewsPosts(){ try{ const [blogRes, autoRes]=await Promise.all([ db.from('blog_posts').select('id,title,content,image_url,video_url,category,author,published,created_at,source_name,source_url').eq('published',true).order('created_at',{ascending:false}), db.from('incoming_news').select('*').eq('verified',true).order('published_at',{ascending:false}).order('created_at',{ascending:false}).limit(100) ]); if(blogRes.error) throw blogRes.error; const base=blogRes.data||[]; const extra=(autoRes.error?[]:(autoRes.data||[])).map(n=>{ const media=extractNewsMedia(n.summary||n.description||n.excerpt||''); return { id:'incoming-news-'+n.id, title:n.title||'Untitled news', content:media.text, image_url:n.image_url||n.image||n.thumbnail_url||'', video_url:media.video_url||'', category:n.category||'Nigeria', author:'Ifeka', published:true, created_at:n.published_at||n.created_at, source_name:n.source_name||'External source', source_url:n.source_url||n.link||n.article_url||n.website_url||n.url||'' };}); const seen=new Set(); allNewsPosts=[...base,...extra].filter(p=>{ const key=String(p.title||'').trim().toLowerCase(); if(!key||seen.has(key)) return false; seen.add(key); return true; }).sort((a,b)=>new Date(b.created_at||0)-new Date(a.created_at||0)); renderHomeNewsPreview(allNewsPosts); if(!allNewsPosts.length){renderNews([]);renderFeatured([]);renderVideoNews([]);setText('breakingText','No verified news yet.');} else{setText('breakingText',allNewsPosts[0].title);filterNews();openArticleFromUrl();} return {blog:base.length,auto:extra.length}; }catch(err){ console.error('Auto news load failed:',err); return {blog:0,auto:0,error:err}; } } async function loadBlogPosts(){ const box=el('blogPosts'); if(box) box.innerHTML='

Loading published news...

'; const result=await loadAutoNewsPosts(); if(result.error && box) box.innerHTML='

Unable to load news.

'; } function renderLiveJob(j){ const key='job-'+String(j.id); ifekaOpportunityDetails[key]=j; const deadline=j.deadline?new Date(j.deadline):null; const deadlineText=deadline && !isNaN(deadline)?deadline.toLocaleDateString():'No deadline listed'; const apply=j.application_url||j.source_url||j.apply_url||''; const provider=j.company||j.provider||j.source_name||'Not specified'; return `
${esc(j.category||'JOB')}

${esc(j.title||'Job vacancy')}

Provider: ${esc(provider)}

Location: ${esc(j.location||'Not specified')}

${j.employment_type?`

Employment: ${esc(j.employment_type)}

`:''} ${j.work_mode?`

Work mode: ${esc(j.work_mode)}

`:''} ${j.salary?`

Salary: ${esc(j.salary)}

`:''} ${j.eligibility?`

Eligibility: ${esc(j.eligibility)}

`:''} ${j.description?`

${esc(String(j.description).slice(0,260))}${String(j.description).length>260?'…':''}

`:''}

Deadline: ${esc(deadlineText)}

βœ“ Source: ifekahub.com
`; } async function loadLiveJobs(){ const grid=el('liveJobsGrid'), status=el('liveJobsStatus'); if(!grid)return; grid.innerHTML='
Loading approved jobs...
'; try{ let query=db.from('opportunities').select('*') .eq('is_active',true) .eq('approval_status','approved') .eq('status','Active') .eq('published',true) .ilike('category','%job%') .order('featured',{ascending:false}) .order('created_at',{ascending:false}) .limit(12); const q=(el('oppSearch')?.value||'').trim(); const loc=(el('oppLocation')?.value||'').trim(); if(q){ const safeQ=q.replace(/[,()]/g,' ').replace(/\s+/g,' ').trim(); if(safeQ) query=query.or(`title.ilike.%${safeQ}%,description.ilike.%${safeQ}%,provider.ilike.%${safeQ}%`); } if(loc && !['Any location',''].includes(loc)) query=query.ilike('location','%'+loc+'%'); const {data,error}=await query; if(error) throw error; const now=new Date(); const testOppTitles=new Set(['administrative officer','marketing & business development opportunity']); const visible=(data||[]).filter(j=>!testOppTitles.has(String(j.title||'').trim().toLowerCase()) && (!j.deadline || String(j.deadline).slice(0,10)>=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}`)); if(!visible.length){grid.innerHTML='
No approved jobs match this search yet.
';if(status)status.textContent='No matching jobs.';return;} grid.innerHTML=visible.map(renderLiveJob).join(''); if(status)status.textContent=`Showing ${visible.length} approved IfekaHub job${visible.length===1?'':'s'}.`; }catch(err){ console.error('Live jobs load failed:',err); grid.innerHTML='
Jobs database is not ready yet. Add and approve job listings in Supabase.
'; if(status)status.textContent='Jobs database connection error.'; } } async function loadVerifiedDatabaseOpportunities(manual=false){ const grid=document.getElementById('verifiedLiveGrid'); const status=document.getElementById('verifiedLiveStatus'); if(!grid) return; if(manual && status) status.textContent='Refreshing verified opportunities…'; try{ if(typeof db==='undefined') throw new Error('Supabase client is not loaded.'); const {data,error}=await db.from('opportunities').select('*') .eq('is_active',true).eq('approval_status','approved').eq('status','Active').eq('published',true) .order('featured',{ascending:false}).order('created_at',{ascending:false}).limit(100); if(error) throw error; const today=new Date(); today.setHours(0,0,0,0); const rows=(data||[]).filter(o=>{ if(!o.title) return false; if(o.deadline){ const d=new Date(String(o.deadline).slice(0,10)+'T00:00:00'); if(!isNaN(d) && dx.textContent.trim().toLowerCase())); const testOppTitles=new Set(['administrative officer','marketing & business development opportunity']); const unique=rows.filter(o=>!editorialTitles.has(String(o.title).trim().toLowerCase())&&!testOppTitles.has(String(o.title||'').trim().toLowerCase())); if(!unique.length){ grid.innerHTML=''; if(status) status.textContent=`Database checked ${new Date().toLocaleString()}. No additional approved listings yet.`; return; } grid.innerHTML=unique.map(o=>{ const deadline=o.deadline?String(o.deadline).slice(0,10):''; const deadlineDate=deadline?new Date(deadline+'T00:00:00'):null; const days=deadlineDate&&!isNaN(deadlineDate)?Math.ceil((deadlineDate-today)/86400000):99999; const urgent=days<=10; const url=o.application_url||o.application_link||o.source||'#'; const scope=/international|global|world|china|usa|uk|europe|africa/i.test(String(o.location||''))?'international':'nigeria'; const cat=String(o.category||'opportunity').toLowerCase(); return `
${urgent?'πŸ”΄ URGENT':'🟒 ACTIVE'} Β· IFEKAHUB VERIFIED

${esc(o.title)}

Provider: ${esc(o.provider||'Not specified')}

Location: ${esc(o.location||'Not specified')}

${o.eligibility?`

Eligibility: ${esc(o.eligibility)}

`:''} ${o.salary?`

Value: ${esc(o.salary)}

`:''}

${esc(o.description||'')}

${deadline?'Deadline: '+esc(new Date(deadline+'T00:00:00').toLocaleDateString()):'No deadline listed'}

βœ“ Approved & active${scope==='international'?'🌍 International':'πŸ‡³πŸ‡¬ Nigeria'}
Apply / Details β†’

Reviewed in the IfekaHub opportunities database

`; }).join(''); if(status) status.textContent=`Database checked ${new Date().toLocaleString()}. ${unique.length} additional approved listing${unique.length===1?'':'s'} shown.`; }catch(err){ console.warn('Verified database opportunities unavailable:',err); if(status) status.textContent='Database unavailable; the hand-verified listings remain available above.'; grid.innerHTML=''; } } function filterVerifiedOpportunities(){ const q=(document.getElementById('verifiedSearch')?.value||'').trim().toLowerCase(); const cat=(document.getElementById('verifiedCategory')?.value||'').toLowerCase(); const scope=(document.getElementById('verifiedScope')?.value||'').toLowerCase(); const grid=document.getElementById('verifiedOppGrid'); if(!grid) return; const cards=[...grid.querySelectorAll('.verified-opp-card')]; cards.sort((a,b)=>(a.dataset.deadline||'9999').localeCompare(b.dataset.deadline||'9999')); cards.forEach(c=>grid.appendChild(c)); let shown=0; cards.forEach(card=>{ const text=card.textContent.toLowerCase(); const okQ=!q||text.includes(q); const okCat=!cat||card.dataset.category===cat; const okScope=!scope||card.dataset.scope===scope; const show=okQ&&okCat&&okScope; card.style.display=show?'':'none'; if(show) shown++; }); const summary=document.getElementById('verifiedSummary'); if(summary) summary.innerHTML=`Showing ${shown} active verified opportunit${shown===1?'y':'ies'}πŸ”΄ Urgent deadlines firstβœ“ Official links`; } function resetVerifiedFilters(){ ['verifiedSearch','verifiedCategory','verifiedScope'].forEach(id=>{const e=document.getElementById(id); if(e)e.value='';}); filterVerifiedOpportunities(); } async function loadDynamicOpportunities(){ const grid=el('dynamicOppGrid'), status=el('oppStatus'); if(!grid)return; grid.innerHTML='
Loading approved opportunities...
'; try{ const now = new Date(); const todayIso = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}`; let query=db.from('opportunities').select('*') .eq('is_active',true) .eq('approval_status','approved') .eq('status','Active') .eq('published',true) .order('featured',{ascending:false}) .order('created_at',{ascending:false}) .limit(100); const type=el('oppType')?.value; const categoryMap={jobs:'job',grants:'grant',scholarships:'scholarship',funding:'funding',training:'training',sports:'sports',entertainment:'entertainment',business:'business'}; if(type && categoryMap[type]) query=query.ilike('category','%'+categoryMap[type]+'%'); const q=(el('oppSearch')?.value||'').trim(); if(q){ const safeQ=q.replace(/[,()]/g,' ').replace(/\s+/g,' ').trim(); if(safeQ) query=query.or(`title.ilike.%${safeQ}%,description.ilike.%${safeQ}%,provider.ilike.%${safeQ}%`); } const loc=(el('oppLocation')?.value||'').trim(); if(loc && loc!=='Any location') query=query.ilike('location','%'+loc+'%'); const {data,error}=await query; if(error) throw error; const testOppTitles=new Set(['administrative officer','marketing & business development opportunity']); const visibleData=(data||[]).filter(o=>{ if(testOppTitles.has(String(o.title||'').trim().toLowerCase())) return false; if(!o.deadline)return true; return String(o.deadline).slice(0,10) >= todayIso; }); if(!visibleData.length){grid.innerHTML='
No approved opportunities match this search yet.
';if(status)status.textContent='No matching opportunities.';return;} grid.innerHTML=visibleData.map(renderDynamicOpportunity).join(''); if(status)status.textContent=`Showing ${visibleData.length} approved IfekaHub opportunit${visibleData.length===1?'y':'ies'}.`; }catch(err){ console.error('Dynamic opportunities load failed:',err); grid.innerHTML='
The opportunities database is not ready yet. Check the Supabase table and policies.
'; if(status){status.className='opp-status notice error';status.textContent='Database connection error.';} } } async function refreshAutoContent(){ const s=el('autoContentStatus'); if(s)s.textContent='Refreshing verified News, Jobs and Opportunities...'; const news=await loadAutoNewsPosts(); await Promise.all([loadLiveJobs(),loadDynamicOpportunities()]); if(s)s.textContent=`Updated ${new Date().toLocaleString()}. News: ${news.blog+news.auto} β€’ Jobs and Opportunities refreshed.`; } document.addEventListener('DOMContentLoaded',()=>{ setTimeout(()=>{ loadAutoNewsPosts(); loadLiveJobs(); loadDynamicOpportunities(); },100); }); function setNewsCategory(category){ const select=document.getElementById('newsCategoryFilter'); if(select){ const option=[...select.options].find(o=>o.value===category || o.textContent===category); if(option) select.value=option.value; } if(typeof filterNews==='function') setTimeout(()=>filterNews(),50); } let liveNewsCategory='all'; function setLiveNewsCategory(category, button){ liveNewsCategory=category; document.querySelectorAll('.live-news-tabs button').forEach(b=>b.classList.remove('active')); if(button) button.classList.add('active'); loadLiveNews(); } function renderLiveNewsCard(n){ const cat=n.category||'Nigeria'; const source='ifekahub.com'; const date=n.published_at||n.created_at; const dateText=date ? new Date(date).toLocaleDateString() : ''; const url=n.source_url||n.link||n.article_url||n.website_url||n.url||''; const media=extractNewsMedia(n.summary||n.description||n.excerpt||''); const image=n.image_url||''; const mediaHtml=image?`${esc(n.title||'News')}`:(media.video_url?`
πŸŽ₯ Video available in full story
`:''); return `
${esc(cat)} ${mediaHtml}

${esc(n.title||'News story')}

${esc(media.text.slice(0,260))}${media.text.length>260?'…':''}

Source: ifekahub.com${dateText?' β€’ '+esc(dateText):''}

`; } async function loadLiveNews(){ const grid=document.getElementById('liveNewsGrid'); const status=document.getElementById('liveNewsStatus'); if(!grid || typeof db==='undefined') return; grid.innerHTML='
Loading latest approved stories...
'; try{ let q=db.from('incoming_news') .select('*') .eq('verified',true) .order('published_at',{ascending:false}) .order('created_at',{ascending:false}) .limit(30); if(liveNewsCategory!=='all'){ q=q.ilike('category',liveNewsCategory); } const {data,error}=await q; if(error) throw error; if(!data?.length){ grid.innerHTML='
No approved stories found in this category yet.
'; if(status) status.textContent='No matching approved stories.'; return; } grid.innerHTML=data.map(renderLiveNewsCard).join(''); if(status) status.textContent=`Showing ${data.length} approved ${liveNewsCategory==='all'?'news':' '+liveNewsCategory+' news'} stories.`; }catch(err){ console.error('Live news load failed:',err); grid.innerHTML='
Live news could not be loaded. Check the Supabase incoming_news table and policies.
'; if(status) status.textContent='News database connection error.'; } } document.addEventListener('DOMContentLoaded',()=>{ setTimeout(()=>loadLiveNews(),150); }); /* IFEKAHUB EXTERNAL SOURCE MONITOR */ const IFEKA_EXTERNAL_SEEN_KEY='ifeka_external_seen_v1'; const IFEKA_EXTERNAL_KNOWN_KEY='ifeka_external_known_v1'; let externalItems=[]; function externalIds(key){try{return new Set(JSON.parse(localStorage.getItem(key)||'[]').map(String));}catch(e){return new Set();}} function saveExternalIds(key,set){localStorage.setItem(key,JSON.stringify([...set].slice(-1500)));} function externalCategoryOrder(){return ['News','Sports','Entertainment','Business','Jobs','Grants & Funding'];} function renderExternalItems(items){ const box=el('externalSourceItems'); if(!box)return; const list=Array.isArray(items)?items:[]; if(!list.length){box.innerHTML='
No external items are available right now. Tap Check External Sources to refresh.
';return;} const groups={}; list.forEach(x=>{const c=x.category||'News';(groups[c]||(groups[c]=[])).push(x);}); const ordered=[...externalCategoryOrder(),...Object.keys(groups).filter(c=>!externalCategoryOrder().includes(c))]; box.innerHTML=ordered.filter(c=>groups[c]?.length).map(c=>{ const label=c==='Grants & Funding'?'πŸŽ“ Grants & Funding':c==='Sports'?'⚽ Sports':c==='Entertainment'?'🎬 Entertainment':c==='Jobs'?'πŸ’Ό Jobs':c==='Business'?'πŸ’° Business':'πŸ“° News'; return `

${label} ${groups[c].length}

${groups[c].slice(0,6).map(x=>`
${esc(x.title)}${esc(x.type||'News')} β€’ ${esc(x.source_name||'External source')}${x.published_at?' β€’ '+esc(new Date(x.published_at).toLocaleString()):''}Open Original Source β†’
`).join('')}
`; }).join(''); } function renderExternalFeedStatus(feedStatus){ const box=el('externalSourceFeedStatus'); if(!box)return; const list=Array.isArray(feedStatus)?feedStatus:[]; if(!list.length){box.innerHTML='';return;} box.innerHTML='
Source connection details'+list.map(f=>`
${f.ok?'βœ…':'⚠️'} ${esc(f.name)} β€” ${f.ok?f.count+' items':esc(f.error||'unavailable')}
`).join('')+'
'; } async function checkExternalSources(manual=false){ const status=el('externalSourceStatus'); if(status)status.textContent='Checking external sources...'; try{ const r=await fetch('/api/external-content?persist=1&ts='+Date.now(),{cache:'no-store'}); if(!r.ok) throw new Error('External source monitor returned HTTP '+r.status); const payload=await r.json(); const items=Array.isArray(payload.items)?payload.items:[]; const known=externalIds(IFEKA_EXTERNAL_KNOWN_KEY); const fresh=items.filter(x=>x.id&&!known.has(x.id)); fresh.forEach(x=>known.add(x.id)); saveExternalIds(IFEKA_EXTERNAL_KNOWN_KEY,known); /* Always show the latest external content. Newness is used only for alerts. */ externalItems=items; renderExternalItems(externalItems); renderExternalFeedStatus(payload.feed_status); const counts={}; items.forEach(x=>{const c=x.category||'News';counts[c]=(counts[c]||0)+1;}); const summary=Object.entries(counts).map(([c,n])=>`${c}: ${n}`).join(' β€’ '); const feedStatus=Array.isArray(payload.feed_status)?payload.feed_status:[]; const failedFeeds=feedStatus.filter(f=>!f.ok); if(status)status.textContent=`Checked ${payload.feeds?.length||0} external feeds at ${new Date(payload.checked_at||Date.now()).toLocaleString()}. ${items.length} item${items.length===1?'':'s'} found; ${fresh.length} new. ${failedFeeds.length?failedFeeds.length+' feed'+(failedFeeds.length===1?'':'s')+' failed. ':''}${summary?'Latest: '+summary+'.':''}`; const persist=payload.persist||{}; if(persist.enabled){ if(status) status.textContent += ` Server review queue: ${persist.saved||0} saved${persist.skipped?` β€’ ${persist.skipped} already existed`:''}${persist.errors?.length?` β€’ ${persist.errors.length} save errors`:''}.`; if(persist.errors?.length){ const realErrors=(persist.errors||[]).filter(e=>!(/HTTP 409|duplicate key|already exists|incoming_news_source_url_key/i.test(String(e)))); const duplicateCount=(persist.errors||[]).length-realErrors.length; if(status && duplicateCount) status.textContent += ` β€’ ${duplicateCount} duplicate item${duplicateCount===1?'':'s'} skipped`; if(realErrors.length){ console.warn('Server persistence errors:',realErrors); const detail=el('externalSourceFeedStatus'); if(detail){ detail.innerHTML=(detail.innerHTML||'')+`
Database save diagnostics
${esc(realErrors.slice(0,3).join(' | '))}
`; } } } }else{ if(status) status.textContent += ' Server persistence is not configured; review queue was not changed.'; } await loadExternalReviewQueue(); if(fresh.length){ const alertRows=fresh.map(x=>({id:'external:'+x.id,type:x.type==='Job'?'Job':x.type==='Opportunity'?'Opportunity':'News',title:x.title,category:x.category,time:x.published_at||new Date().toISOString()})); ifekaAlertItems=[...alertRows,...ifekaAlertItems].slice(0,50); ifekaRenderAlerts(); const notified=ifekaReadIds(IFEKA_NOTIFIED_KEY); const unnotified=fresh.filter(x=>!notified.has('external:'+x.id)); if(unnotified.length && 'Notification' in window && Notification.permission==='granted' && 'serviceWorker' in navigator){ try{const reg=await navigator.serviceWorker.ready; await reg.showNotification('IfekaHub: New External Content',{body:`${unnotified.length} new ${unnotified.length===1?'item':'items'} found from external sources.`,tag:'ifekahub-external',renotify:true,icon:'/favicon.ico'});}catch(e){console.warn('External phone notification failed',e);} unnotified.forEach(x=>notified.add('external:'+x.id)); saveExternalIds(IFEKA_NOTIFIED_KEY,notified); } } }catch(e){console.error(e);if(status)status.textContent='External source connection error: '+(e.message||e)+'. Check that the current Cloudflare deployment includes _worker.js.';} finally{loadExternalReviewQueue();} } async function saveExternalItemsToReview(items){ if(!Array.isArray(items)||!items.length||typeof db==='undefined') return {saved:0,errors:[]}; let saved=0; const errors=[]; for(const x of items){ try{ const type=x.type||'News'; if(type==='Job'||type==='Opportunity'){ const category=type==='Job'?'Jobs':'Grants & Funding'; const row={title:x.title,provider:'ifekahub.com',category,location:'Nigeria',deadline:null,application_url:x.source_url||'',source:'ifekahub.com',description:x.summary||'External opportunity collected for admin review.',featured:false,is_active:false,approval_status:'pending',status:'Pending',published:false}; const q=await db.from('opportunities').select('id').eq('title',x.title).eq('source',row.source).limit(1); if(q.error) throw q.error; if(!(q.data||[]).length){const ins=await db.from('opportunities').insert(row);if(ins.error)throw ins.error;saved++;} }else{ const row={title:x.title,category:x.category||'Nigeria',source_name:'ifekahub.com',source_url:x.source_url||'',published_at:x.published_at||new Date().toISOString(),verified:false}; const q=await db.from('incoming_news').select('id').eq('source_url',row.source_url).limit(1); if(q.error) throw q.error; if(!(q.data||[]).length){const ins=await db.from('incoming_news').insert(row);if(ins.error)throw ins.error;saved++;} } }catch(err){errors.push((x.title||'External item')+': '+(err?.message||err));} } return {saved,errors}; } let ifekaExternalReviewTab='news'; function setExternalReviewTab(tab){ ifekaExternalReviewTab=tab==='opportunity'?'opportunity':'news'; document.querySelectorAll('.review-tab').forEach(b=>b.classList.toggle('active',b.dataset.reviewTab===ifekaExternalReviewTab)); loadExternalReviewQueue(); } async function loadExternalReviewQueue(){ const box=el('externalReviewItems'),status=el('externalReviewStatus'); if(!box||typeof db==='undefined')return; try{ const {data:sd}=await db.auth.getSession(); const token=sd?.session?.access_token; if(!token){ if(status)status.textContent='Admin login required to view unpublished drafts.'; box.innerHTML='
πŸ” Please log in as the IfekaHub administrator to review unpublished drafts.
'; return; } const r=await fetch('/api/review-queue',{headers:{Authorization:'Bearer '+token},cache:'no-store'}); const payload=await r.json().catch(()=>({})); if(!r.ok||payload.ok===false) throw new Error(payload.error||('Review queue HTTP '+r.status)); const news=(payload.news||[]).map(x=>({kind:'news',id:x.id,title:x.title,summary:x.summary||'',category:x.category||'News',source:x.source_name||'External source',url:x.source_url||'',time:x.published_at||x.created_at})); const opportunities=(payload.opportunities||[]).map(x=>({kind:'opportunity',id:x.id,title:x.title,category:x.category||'Opportunity',source:x.provider||x.source||'External source',url:x.application_url||x.application_link||'',time:x.created_at})); const rows=(ifekaExternalReviewTab==='opportunity'?opportunities:news).sort((a,b)=>new Date(b.time||0)-new Date(a.time||0)); const totalNews=news.length,totalOpp=opportunities.length; const repairCount=(payload.repair?.movedToOpportunities||0)+(payload.repair?.movedToNews||0); const repairNote=repairCount?` β€’ ${payload.repair.movedToOpportunities||0} moved to Opportunities, ${payload.repair.movedToNews||0} moved to News`:''; const nc=document.getElementById('reviewNewsCount'),oc=document.getElementById('reviewOpportunityCount'); if(nc)nc.textContent=totalNews; if(oc)oc.textContent=totalOpp; if(status)status.textContent=`News: ${totalNews} pending β€’ Opportunities: ${totalOpp} pending${repairNote}`; if(!rows.length){box.innerHTML=`
No ${ifekaExternalReviewTab==='opportunity'?'opportunity':'news'} drafts are waiting for review.
`;return;} box.innerHTML=rows.slice(0,40).map(x=>`
${esc(x.title)}${x.kind==='news'?'πŸ“° NEWS':'πŸ’Ό OPPORTUNITY'} β€’ ${esc(x.category)} β€’ ${esc(x.source)}${x.time?' β€’ '+esc(new Date(x.time).toLocaleString()):''}${x.url?`Open Original Source β†’`:''}
`).join(''); }catch(err){console.error('External review queue failed:',err);if(status)status.textContent='Review queue error: '+(err?.message||err);box.innerHTML='
Could not load the review queue. Please log in and try again.
';} } async function reviewActionViaWorker(kind,id,action,summary='',media={}){ const {data:sd}=await db.auth.getSession(); const token=sd?.session?.access_token; if(!token){alert('Please log in as the IfekaHub administrator first.');return false;} const r=await fetch('/api/review-action',{method:'POST',headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},body:JSON.stringify({kind,id,action,summary,image_url:media.image_url||'',video_url:media.video_url||'',article_images:Array.isArray(media.article_images)?media.article_images:[],category:media.category||'',source_note:media.source_note||'',tags:Array.isArray(media.tags)?media.tags:[],editor_notes:media.editor_notes||'',seo_description:media.seo_description||'',media_source:media.media_source||'',media_rights_status:media.media_rights_status||'',originality_checked:media.originality_checked===true})}); const payload=await r.json().catch(()=>({})); if(!r.ok||payload.ok===false){alert((action==='approve'?'Approval':'Rejection')+' failed: '+(payload.error||('HTTP '+r.status)));return false;} return true; } let ifekaPendingNewsApproval=null; let ifekaSummaryPreviewOpen=false; function closeIfekaSummaryModal(){ const m=document.getElementById('ifekaSummaryModal'); if(m)m.classList.remove('open'); const hh=document.getElementById('ifekaSummaryHeadline'); if(hh)hh.textContent=''; ifekaPendingNewsApproval=null; } function updateIfekaSummaryStats(){ const t=document.getElementById('ifekaSummaryText'); if(!t)return; const value=t.value.trim(); const chars=value.length, words=value?value.split(/\s+/).length:0, sentences=value?value.split(/[.!?]+/).filter(x=>x.trim()).length:0; const c=document.getElementById('ifekaSummaryChars'),w=document.getElementById('ifekaSummaryWords'),s=document.getElementById('ifekaSummarySentences'); if(c){c.textContent=`${chars}/4000 characters`;c.className='ifeka-summary-stat '+(chars>=300?'good':'bad');} const target=getIfekaTargetWords(); if(w){w.textContent=`${words} words / target ${target}`;w.className='ifeka-summary-stat '+(words>=Math.max(60,Math.round(target*.8))?'good':'bad');} if(s){s.textContent=`${sentences} sentence${sentences===1?'':'s'}`;s.className='ifeka-summary-stat '+(sentences>=8?'good':'bad');} const checks=document.getElementById('ifekaSummaryChecks'); if(checks){ const checksList=[ [chars>=300,'At least 300 characters'], [words>=20,'Enough detail to be useful'], [sentences>=8,'Well-developed article with multiple sentences'], [/[.!?]$/.test(value),'Ends with proper punctuation'], [!/(https?:\/\/|www\.)/i.test(value),'No unnecessary links in the article body'] ]; checks.innerHTML=checksList.map(([ok,label])=>`
${ok?'βœ…':'⬜'} ${label}
`).join(''); } } function openIfekaSummaryModal(id,title,source,sourceSummary='',sourceUrl=''){ const m=document.getElementById('ifekaSummaryModal'),t=document.getElementById('ifekaSummaryText'),s=document.getElementById('ifekaSummarySource'); if(!m||!t)return false; ifekaPendingNewsApproval={id:String(id),title:String(title||''),source:String(source||''),sourceSummary:String(sourceSummary||''),sourceUrl:String(sourceUrl||''),imageUrl:'',videoUrl:'',articleImages:[]}; const h=document.getElementById('ifekaSummaryTitle'); if(h)h.textContent='IfekaHub Editorial Quality Editor v6.8.9'; const he=document.getElementById('ifekaSummaryHeadlineEdit'); if(he)he.value=ifekaPendingNewsApproval.title||''; const cat=document.getElementById('ifekaSummaryCategory'); if(cat){const c=String(ifekaPendingNewsApproval.category||'News'); if([...cat.options].some(o=>o.value===c))cat.value=c;} const sn=document.getElementById('ifekaSummarySourceNote'); if(sn)sn.value=ifekaPendingNewsApproval.source?`Original source: ${ifekaPendingNewsApproval.source}`:''; const tags=document.getElementById('ifekaSummaryTags');if(tags)tags.value=''; const seo=document.getElementById('ifekaSummarySeo');if(seo)seo.value=''; const notes=document.getElementById('ifekaSummaryEditorNotes');if(notes)notes.value=''; document.querySelectorAll('#ifekaEditorialChecklist input[data-editor-check]').forEach(x=>x.checked=false); const mediaSource=document.getElementById('ifekaSummaryMediaSource');if(mediaSource)mediaSource.value=''; if(s)s.textContent=ifekaPendingNewsApproval.source?`Source: ${ifekaPendingNewsApproval.source}`:''; const hh=document.getElementById('ifekaSummaryHeadline'); if(hh)hh.textContent=ifekaPendingNewsApproval.title||''; const savedDraft=localStorage.getItem('ifeka_summary_draft_'+String(id))||''; try{const d=JSON.parse(savedDraft);if(d&&typeof d==='object'){t.value=d.text||'';if(document.getElementById('ifekaSummaryHeadlineEdit'))document.getElementById('ifekaSummaryHeadlineEdit').value=d.headline||ifekaPendingNewsApproval.title||'';if(document.getElementById('ifekaSummaryCategory')&&d.category)document.getElementById('ifekaSummaryCategory').value=d.category;if(document.getElementById('ifekaSummarySourceNote'))document.getElementById('ifekaSummarySourceNote').value=d.sourceNote || (ifekaPendingNewsApproval.source?`Original source: ${ifekaPendingNewsApproval.source}`:'');if(document.getElementById('ifekaSummaryTags'))document.getElementById('ifekaSummaryTags').value=d.tags||'';if(document.getElementById('ifekaSummarySeo'))document.getElementById('ifekaSummarySeo').value=d.seo||'';if(document.getElementById('ifekaSummaryEditorNotes'))document.getElementById('ifekaSummaryEditorNotes').value=d.notes||'';if(document.getElementById('ifekaSummaryMediaSource'))document.getElementById('ifekaSummaryMediaSource').value=d.mediaSource||'';if(d.targetWords)setIfekaTargetWords(d.targetWords);}else t.value=savedDraft;}catch(e){t.value=savedDraft;} const sm=document.getElementById('ifekaSummarySourceMaterial'); if(sm)sm.value=ifekaPendingNewsApproval.sourceSummary||''; ['ifekaSummaryImageUrl','ifekaSummaryVideoUrl','ifekaSummaryArticleImageUrls'].forEach(k=>{const e=document.getElementById(k);if(e)e.value='';}); ['ifekaSummaryImageFile','ifekaSummaryVideoFile','ifekaSummaryArticleImageFiles'].forEach(k=>{const e=document.getElementById(k);if(e)e.value='';}); const mm=document.getElementById('ifekaSummaryMediaMessage');if(mm)mm.style.display='none'; const rights=document.getElementById('ifekaSummaryMediaRights');if(rights)rights.checked=false; updateIfekaMediaPreview(); updateIfekaSummaryStats(); m.classList.add('open'); setTimeout(()=>t.focus(),50); return true; } function getIfekaSourceMaterial(){ const el=document.getElementById('ifekaSummarySourceMaterial'); return (el?.value||ifekaPendingNewsApproval?.sourceSummary||'').replace(/\s+/g,' ').trim(); } async function fetchIfekaSourceFacts(){ if(!ifekaPendingNewsApproval)return; const url=String(ifekaPendingNewsApproval.sourceUrl||'').trim(); const box=document.getElementById('ifekaSummarySourceMaterial'); const status=document.getElementById('ifekaSummarySourceStatus'); if(!url){alert('This story has no original source URL. Paste the source facts manually.');return;} if(status)status.textContent='Fetching source facts…'; try{ const {data:sd}=await db.auth.getSession(); const token=sd?.session?.access_token; if(!token) throw new Error('Please log in as the IfekaHub administrator first.'); const fallback=String(ifekaPendingNewsApproval.sourceSummary||'').trim(); const r=await fetch('/api/source-facts',{method:'POST',headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},body:JSON.stringify({url,fallbackText:fallback})}); const payload=await r.json().catch(()=>({})); if(!r.ok||payload.ok===false) throw new Error(payload.error||('HTTP '+r.status)); if(box)box.value=String(payload.facts||'').slice(0,12000); if(status)status.textContent=payload.partial?`⚠️ ${payload.paragraphs||0} source paragraphs loaded β€” source returned limited text`:`βœ“ ${payload.paragraphs||0} source paragraphs loaded`; }catch(e){if(status)status.textContent='Could not fetch source facts';alert('Source facts could not be fetched: '+(e?.message||e)+'\n\nYou can still paste the key facts from the original source.');} } function editorialCleanFact(x){ return String(x||'').replace(/\s+/g,' ').replace(/^[-β€’\d.)]+\s*/,'').trim(); } function sentenceFacts(src){ const raw=String(src||'').replace(/https?:\/\/\S+/gi,' ').split(/(?<=[.!?])\s+|\n+/).map(editorialCleanFact).filter(x=>x.length>45); const out=[],seen=new Set(); for(const x of raw){ const key=x.toLowerCase().replace(/[^a-z0-9\s]/g,' ').replace(/\s+/g,' ').trim(); if(seen.has(key))continue; seen.add(key); out.push(x); } return out; } function mediaUrlIsEmbeddableVideo(u){return /(?:youtube\.com|youtu\.be|vimeo\.com|facebook\.com)\//i.test(String(u||''));} function updateIfekaMediaPreview(){ const wrap=document.getElementById('ifekaSummaryMediaPreview'); const iu=(document.getElementById('ifekaSummaryImageUrl')?.value||'').trim(); const vu=(document.getElementById('ifekaSummaryVideoUrl')?.value||'').trim(); const imageFile=document.getElementById('ifekaSummaryImageFile')?.files?.[0]||null; const videoFile=document.getElementById('ifekaSummaryVideoFile')?.files?.[0]||null; const ip=document.getElementById('ifekaSummaryImagePreview'); const vp=document.getElementById('ifekaSummaryVideoPreview'); const imageSrc=imageFile?URL.createObjectURL(imageFile):iu; const videoSrc=videoFile?URL.createObjectURL(videoFile):vu; if(ip)ip.innerHTML=imageSrc?`Featured image previewImage could not be previewed'">`:`
No image selected
`; if(vp){ if(!videoSrc) vp.innerHTML='
No video selected
'; else if(!videoFile && mediaUrlIsEmbeddableVideo(videoSrc)) vp.innerHTML=`
Official video link detected.
It will be embedded where supported.
`; else vp.innerHTML=``; } if(wrap)wrap.style.display=(imageSrc||videoSrc)?'grid':'none'; } function escapeHtmlAttr(v){return String(v||'').replace(/&/g,'&').replace(/"/g,'"').replace(//g,'>');} async function fetchIfekaSourceMedia(){ if(!ifekaPendingNewsApproval)return; const url=String(ifekaPendingNewsApproval.sourceUrl||'').trim(); const msg=document.getElementById('ifekaSummaryMediaMessage'); if(!url){if(msg){msg.style.display='block';msg.className='notice error';msg.textContent='This story has no original source URL.';}return;} if(msg){msg.style.display='block';msg.className='notice';msg.textContent='Fetching available media from the original source…';} try{ const {data:sd}=await db.auth.getSession(); const token=sd?.session?.access_token; if(!token) throw new Error('Please log in as the IfekaHub administrator first.'); const r=await fetch('/api/source-media',{method:'POST',headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},body:JSON.stringify({url})}); const payload=await r.json().catch(()=>({})); if(!r.ok||payload.ok===false)throw new Error(payload.error||('HTTP '+r.status)); const image=String(payload.images?.[0]||''); const video=String(payload.videos?.[0]||''); const iu=document.getElementById('ifekaSummaryImageUrl'),vu=document.getElementById('ifekaSummaryVideoUrl'); if(iu&&image)iu.value=image; if(vu&&video)vu.value=video; const extra=(payload.images||[]).slice(1,7).join('\n'); const ai=document.getElementById('ifekaSummaryArticleImageUrls'); if(ai&&extra)ai.value=extra; updateIfekaMediaPreview(); const rights=document.getElementById('ifekaSummaryMediaRights'); if(rights)rights.checked=false; if(msg){msg.className=image||video?'notice':'notice error';msg.textContent=`${image?'βœ“ Featured image found.':'⚠️ No image found.'} ${video?'βœ“ Video/embed found.':'No video/embed found.'} ${((payload.images||[]).length>1)?` ${Math.min((payload.images||[]).length,7)-1} additional image${Math.min((payload.images||[]).length,7)-1===1?'':'s'} found.`:''} Review the preview and confirm you have rights or embedding permission before publishing.`;} }catch(e){if(msg){msg.style.display='block';msg.className='notice error';msg.textContent='Media could not be fetched: '+(e?.message||e);} } } function getIfekaTargetWords(){ const n=parseInt(document.getElementById('ifekaSummaryTargetWords')?.value||'150',10); return [100,150,250,400,600].includes(n)?n:150; } function setIfekaTargetWords(n){ const sel=document.getElementById('ifekaSummaryTargetWords'); if(sel)sel.value=String([100,150,250,400,600].includes(Number(n))?Number(n):150); } function paraphraseEditorialSentence(s){ let x=String(s||'').replace(/\s+/g,' ').trim(); x=x.replace(/^According to [^,]+,\s*/i,''); const swaps=[ [/\bhas challenged\b/gi,'has called on'],[/\bhas urged\b/gi,'has appealed to'],[/\bhas vowed\b/gi,'has said it will'], [/\bdisclosed this in a statement made available to journalists\b/gi,'said this in a statement issued to journalists'], [/\bmade available to journalists\b/gi,'issued to journalists'],[/\bongoing\b/gi,'current'],[/\bat the moment\b/gi,'currently'], [/\bas the nation prepares for\b/gi,'ahead of'],[/\bin an ongoing\b/gi,'during the current'],[/\baccording to him\b/gi,'he said'], [/\bthe report says that\b/gi,'the report states that'],[/\bthe report also states that\b/gi,'the report further notes that'], [/\bstated that\b/gi,'said that'],[/\binformed students\b/gi,'told students'],[/\bstrongly committed to ensuring\b/gi,'committed to ensuring'], [/\bcurrently on strike\b/gi,'on strike at present'] ]; swaps.forEach(([a,b])=>{x=x.replace(a,b);}); x=x.replace(/\bThis is because\b/gi,'The reason given is that').replace(/\bIt is important to note that\b/gi,'The report notes that'); x=x.replace(/\s+([,.!?;:])/g,'$1').trim(); return x; } function sentenceFacts(src){ const raw=String(src||'').replace(/https?:\/\/\S+/gi,' ').split(/(?<=[.!?])\s+|\n+/).map(editorialCleanFact).filter(x=>x.length>45); const out=[],seen=new Set(); for(const x of raw){const key=x.toLowerCase().replace(/[^a-z0-9\s]/g,' ').replace(/\s+/g,' ').trim();if(seen.has(key))continue;seen.add(key);out.push(x);} return out; } function normalizeEditorialText(s){ return String(s||'').replace(/\u00a0/g,' ').replace(/\s+/g,' ').trim(); } function compressEditorialSentence(s){ let x=normalizeEditorialText(s); x=x.replace(/^(According to|In a statement|The report says that|The report states that)\s+/i,''); x=x.replace(/\bmade available to journalists\b/gi,'issued to journalists'); x=x.replace(/\bhas challenged\b/gi,'has called on'); x=x.replace(/\bhas urged\b/gi,'has appealed to'); x=x.replace(/\bhas vowed\b/gi,'has said it will'); x=x.replace(/\bcurrently\b/gi,'now'); x=x.replace(/\bongoing\b/gi,'current'); x=x.replace(/\bas the nation prepares for\b/gi,'ahead of'); x=x.replace(/\baccording to him\b/gi,'he said'); x=x.replace(/\bstated that\b/gi,'said that'); x=x.replace(/\binformed students\b/gi,'told students'); x=x.replace(/\s+([,.!?;:])/g,'$1'); return x; } function scoreEditorialFact(s,title){ const x=s.toLowerCase(), t=String(title||'').toLowerCase(); let score=0; ['said','announced','urged','called','disclosed','confirmed','according','statement'].forEach(k=>{if(x.includes(k))score+=2;}); ['date','saturday','sunday','monday','tuesday','wednesday','thursday','friday','2026','2027'].forEach(k=>{if(x.includes(k))score+=1;}); ['because','after','during','while','however','but'].forEach(k=>{if(x.includes(k))score+=1;}); const titleWords=new Set(t.replace(/[^a-z0-9 ]/g,' ').split(/\s+/).filter(w=>w.length>4)); for(const w of titleWords)if(x.includes(w))score+=1; return score; } function rewriteEditorialSentence(sentence,index){ let x=normalizeEditorialText(sentence).replace(/\s+/g,' ').trim(); if(!x)return ''; x=x.replace(/^According to (the|a|an)\s+/i,'The source reports that '); x=x.replace(/^According to [^,]+,\s*/i,'The report says that '); x=x.replace(/\bwas diverted to\b/gi,'was redirected to'); x=x.replace(/\btravelling from\b/gi,'flying from'); x=x.replace(/\btraveling from\b/gi,'flying from'); x=x.replace(/\bafter\b/gi,'following'); x=x.replace(/\bhas challenged\b/gi,'has called on'); x=x.replace(/\bhas urged\b/gi,'has appealed to'); x=x.replace(/\bhas vowed\b/gi,'has said it will'); x=x.replace(/\bsaid\b/gi,'stated'); x=x.replace(/\bdisclosed\b/gi,'revealed'); x=x.replace(/\bannounced\b/gi,'confirmed'); x=x.replace(/\bstated\b/gi,'said'); x=x.replace(/\bcurrently\b/gi,'at present'); x=x.replace(/\bongoing\b/gi,'current'); x=x.replace(/\binformed\b/gi,'told'); x=x.replace(/\baccording to him\b/gi,'he said'); x=x.replace(/\bmade available to journalists\b/gi,'issued to journalists'); x=x.replace(/\s+([,.!?;:])/g,'$1').trim(); // Rebuild common long news constructions so the output is not a sentence-for-sentence copy. const m=x.match(/^(.+?)\s+was redirected to\s+(.+?)\s+following\s+(.+)$/i); if(m && /flight|airline|airways/i.test(m[1])){ x=`A ${m[1].replace(/^A\s+/i,'').replace(/^An\s+/i,'')} was sent to ${m[2]} following ${m[3]}`; } const n=x.match(/^(.+?)\s+has called on\s+(.+?)\s+to\s+(.+)$/i); if(n){x=`${n[1]} is urging ${n[2]} to ${n[3]}`;} // Rotate a small set of safe reporting terms to create independent wording. const swaps=[ [/\bdevelopment\b/gi,'turn of events'],[/\bincident\b/gi,'episode'],[/\breport\b/gi,'account'], [/\bsaid that\b/gi,'explained that'],[/\bnoted that\b/gi,'pointed out that'],[/\bpeople\b/gi,'individuals'], [/\bofficials\b/gi,'authorities'],[/\bdetails\b/gi,'information'] ]; if(index%2===1) swaps.slice(0,4).forEach(([a,b])=>x=x.replace(a,b)); x=x.replace(/\bexplained that\s+([^,.;!?]+)\s+said\b/gi,'explained that $1 stated'); return x.trim().replace(/^[a-z]/,c=>c.toUpperCase()).replace(/([.!?])\s*$/,'$1'); } function makeOriginalEditorialDraft(title,src,target=getIfekaTargetWords()){ const facts=sentenceFacts(src).map(normalizeEditorialText).filter(x=>x.length>45); if(!facts.length)return ''; const ranked=[...facts].sort((a,b)=>scoreEditorialFact(b,title)-scoreEditorialFact(a,title)); const cleanTitle=normalizeEditorialText(title||'This development').replace(/[.!?]+$/,''); const chosen=[]; const seen=new Set(); const sourceWords=src.toLowerCase().replace(/[^a-z0-9\s]/g,' ').split(/\s+/).filter(Boolean); const sourceSet=new Set(sourceWords); for(let i=0;i24 && sourceWords.join(' ').includes(phrase)){overlap++;break;}} if(overlap){ x=`The source account adds that ${x.replace(/^[A-Z][^,]{2,70},\s*/,'')}`; } const key=x.toLowerCase(); if(seen.has(key))continue;seen.add(key);chosen.push(x); } if(!chosen.length)return ''; let lead=`IfekaHub has reviewed the available report on ${cleanTitle}.`; let draft=[lead,...chosen].join('\n\n'); // Never allow the source material to become the final article by itself. draft=draft.replace(/^#+\s.*$/gm,'').replace(/^\s*[β€’*-]\s*/gm,'').replace(/PAY ATTENTION:[\s\S]*?(?=\.|$)/gi,'').replace(/Additional details\.?/gi,'').trim(); const words=draft.split(/\s+/).filter(Boolean); const maxWords=Math.max(100,target+20); if(words.length>maxWords)draft=words.slice(0,maxWords).join(' ').replace(/\s+([,.!?])/g,'$1'); return draft; } async function generateIfekaSummaryStarter(){ const t=document.getElementById('ifekaSummaryText'); if(!t||!ifekaPendingNewsApproval)return; const title=(document.getElementById('ifekaSummaryHeadlineEdit')?.value||ifekaPendingNewsApproval.title||'This development').trim(); let src=getIfekaSourceMaterial(); if(src.length<350 && ifekaPendingNewsApproval.sourceUrl){ await fetchIfekaSourceFacts(); src=getIfekaSourceMaterial(); } if(!src){alert('Fetch the source facts first, or paste the verified key facts from the original source.');return;} const target=getIfekaTargetWords(); const {data:{session}}=await db.auth.getSession(); if(!session){ alert('Please log in again before using AI rewriting.'); return; } const aiResponse=await fetch('/api/ai-rewrite-news',{ method:'POST', headers:{ 'Content-Type':'application/json', 'Authorization':`Bearer ${session.access_token}` }, body:JSON.stringify({ title, facts:src, targetWords:target }) }); const aiResult=await aiResponse.json().catch(()=>({})); if(!aiResponse.ok||!aiResult.ok){ alert(aiResult.error||'AI rewriting failed. Please try again.'); return; } const draft=String(aiResult.article||'').trim(); if(!draft){alert('Not enough factual material was found to build a draft.');return;} t.value=draft; t.focus(); updateIfekaSummaryStats(); runIfekaEditorialQualityCheck(); } function expandIfekaSummaryDraft(){ const t=document.getElementById('ifekaSummaryText'); if(!t||!ifekaPendingNewsApproval)return; const src=getIfekaSourceMaterial(); if(!src){alert('Fetch the source facts first, or paste verified key facts from the original source.');return;} const current=t.value.trim(); const title=(document.getElementById('ifekaSummaryHeadlineEdit')?.value||ifekaPendingNewsApproval.title||'This development').trim(); const target=Math.min(600,Math.max(getIfekaTargetWords()+100,250)); setIfekaTargetWords(target); const extra=makeOriginalEditorialDraft(title,src,target); const parts=extra.split(/\n\s*\n/).filter(Boolean); let draft=current; for(const part of parts){const clean=part.trim();if(clean && !draft.toLowerCase().includes(clean.toLowerCase().slice(0,90)) && (draft+'\n\n'+clean).length<=4000)draft+=(draft?'\n\n':'')+clean;} t.value=draft.slice(0,4000).trim(); t.focus(); updateIfekaSummaryStats(); runIfekaEditorialQualityCheck(); } function previewIfekaSummary(){ const t=document.getElementById('ifekaSummaryText'); if(!t)return; const p=document.getElementById('ifekaSummaryPreview'); if(!p)return; const value=t.value.trim(); p.innerHTML=value?`Preview
${esc(value)}
`:'Preview
Nothing to preview yet.
'; p.classList.toggle('open',!p.classList.contains('open')); ifekaSummaryPreviewOpen=p.classList.contains('open'); } function resetIfekaSummaryPreview(){ const p=document.getElementById('ifekaSummaryPreview'); if(p){p.classList.remove('open');ifekaSummaryPreviewOpen=false;} } function insertIfekaSummaryStructure(style){ const map={short:100,standard:250,detailed:400}; setIfekaTargetWords(map[style]||150); generateIfekaSummaryStarter(); } function getCheckedEditorialItems(){ return [...document.querySelectorAll('#ifekaEditorialChecklist input[data-editor-check]:checked')].map(x=>({source:'Original source opened and checked',names:'Names, organisations and titles verified',dates:'Dates and time references verified',figures:'Figures, numbers and statistics verified',claims:'Key claims and important details verified',headline:'IfekaHub headline rewritten independently',followup:'Follow-up or conflicting information reviewed'}[x.dataset.editorCheck])).filter(Boolean); } function addCheckedEditorialNotes(){ const notes=document.getElementById('ifekaSummaryEditorNotes'); if(!notes)return; const items=getCheckedEditorialItems(); if(!items.length){alert('Check the verification items first.');return;} const prefix=notes.value.trim(); const block=items.map(x=>'βœ“ '+x).join('\n'); notes.value=prefix ? prefix+'\n'+block : block; notes.focus(); } function bindEditorialChecklist(){ document.querySelectorAll('#ifekaEditorialChecklist input[data-editor-check]').forEach(x=>x.addEventListener('change',()=>{ const notes=document.getElementById('ifekaSummaryEditorNotes'); if(notes) notes.dataset.checklistDirty='1'; })); const b=document.getElementById('ifekaSummaryAddCheckedNotes'); if(b)b.addEventListener('click',addCheckedEditorialNotes); } function saveIfekaSummaryDraft(){ const t=document.getElementById('ifekaSummaryText'); if(!t||!ifekaPendingNewsApproval)return; localStorage.setItem('ifeka_summary_draft_'+ifekaPendingNewsApproval.id,JSON.stringify({text:t.value,headline:document.getElementById('ifekaSummaryHeadlineEdit')?.value||'',category:document.getElementById('ifekaSummaryCategory')?.value||'',sourceNote:document.getElementById('ifekaSummarySourceNote')?.value||'',tags:document.getElementById('ifekaSummaryTags')?.value||'',seo:document.getElementById('ifekaSummarySeo')?.value||'',notes:document.getElementById('ifekaSummaryEditorNotes')?.value||'',mediaSource:document.getElementById('ifekaSummaryMediaSource')?.value||'',targetWords:getIfekaTargetWords()})); const b=document.getElementById('ifekaSummarySave'); if(b){const old=b.textContent;b.textContent='βœ“ Saved';setTimeout(()=>b.textContent=old,1200);} } function clearIfekaSummaryDraft(){ const t=document.getElementById('ifekaSummaryText'); if(t)t.value=''; if(ifekaPendingNewsApproval)localStorage.removeItem('ifeka_summary_draft_'+ifekaPendingNewsApproval.id); updateIfekaSummaryStats(); if(t)t.focus(); } function runIfekaEditorialQualityCheck(){ const t=document.getElementById('ifekaSummaryText'); if(!t)return false; const text=t.value.trim(), src=getIfekaSourceMaterial(), title=(document.getElementById('ifekaSummaryHeadlineEdit')?.value||ifekaPendingNewsApproval?.title||'').trim(); const lower=text.toLowerCase(), words=text?text.split(/\s+/).length:0; const sentences=text?text.split(/[.!?]+/).filter(x=>x.trim()).length:0; const paragraphs=text?text.split(/\n\s*\n/).filter(x=>x.trim()).length:0; const clickbait=/sad reason|shocking|you won't believe|must see|what happened next|bombshell|exposed|finally revealed/i.test(title+' '+text); const certainty=/\b(guilty|confirmed as guilty|definitely|certainly|proved)\b/i.test(lower); const hasSource=src.length>=120; const hasAttribution=!!(document.getElementById('ifekaSummarySourceNote')?.value||'').trim(); const copied=src.length>200 && text.length>120 && (()=>{const a=src.toLowerCase().replace(/[^a-z0-9\s]/g,' ').split(/\s+/).filter(Boolean);const b=lower.replace(/[^a-z0-9\s]/g,' ').split(/\s+/).filter(Boolean);const set=new Set(b);let hit=0,total=0;for(let i=0;i3&&hit/total>.45;})(); const target=getIfekaTargetWords(); const useful=words>=Math.max(60,Math.round(target*.8)), structured=sentences>=Math.max(4,Math.ceil(target/45)) || paragraphs>=4, punctuation=/[.!?]$/.test(text); const hasEditorNote=/\[EDITOR NOTE:/i.test(text); const draftScaffold=/^###\s+(What we know|Important context|What to watch next)/mi.test(text) || /(^|\n)β€’\s+/.test(text); const items=[ [useful,'good',`Useful article length (target ${target} words)`],[structured,'good','Clear structure / multiple points'],[hasSource,'good','Grounded in source facts'],[hasAttribution,'good','Source attribution recorded'],[!clickbait,'good','Headline avoids obvious clickbait'],[!certainty,'good','No unsupported certainty'],[!copied&&!hasEditorNote&&!draftScaffold,'good','No source-scaffold left in final article'],[punctuation&&!hasEditorNote&&!draftScaffold,'good','Final article is ready-formatted'] ]; let score=items.reduce((n,x)=>n+(x[0]?12.5:0),0); score=Math.round(score); const grid=document.getElementById('ifekaQualityGrid'); if(grid)grid.innerHTML=items.map(([ok,_,label])=>`
${ok?'βœ…':'⚠️'} ${label}
`).join(''); const qs=document.getElementById('ifekaQualityScore'); if(qs){qs.textContent=`Editorial quality score: ${score}/100`;qs.className='ifeka-quality-score';} const note=document.getElementById('ifekaQualityNote'); if(note){const warnings=[];if(words=75; } async function submitIfekaSummaryApproval(){ const pending=ifekaPendingNewsApproval,t=document.getElementById('ifekaSummaryText'); if(!pending||!t)return; const summary=t.value.trim(); if(summary.lengthx.trim()).filter(Boolean).slice(0,20); const seo_description=String(document.getElementById('ifekaSummarySeo')?.value||'').trim() || summary.replace(/\s+/g,' ').slice(0,155); const editor_notes=String(document.getElementById('ifekaSummaryEditorNotes')?.value||'').trim(); const media_source=String(document.getElementById('ifekaSummaryMediaSource')?.value||'').trim(); const media_rights_status=(image_url||video_url||imageFile||videoFile||extraUrls.length||extraFiles.length)?(mediaRights?'Confirmed':'Not Checked'):'Not Applicable'; if(!await reviewActionViaWorker('news',pending.id,'approve',summary,{image_url,video_url,article_images,category:document.getElementById('ifekaSummaryCategory')?.value||'News',source_note:sourceNote,tags,editor_notes,seo_description,media_source,media_rights_status,originality_checked:qualityOk}))return; localStorage.removeItem('ifeka_summary_draft_'+pending.id); closeIfekaSummaryModal(); await loadExternalReviewQueue(); if(typeof loadLiveNews==='function')await loadLiveNews(); if(typeof loadBlogPosts==='function')await loadBlogPosts(); }catch(err){alert(err?.message||'Publishing failed.');} finally{ if(btn){btn.disabled=false;btn.textContent='βœ… Publish News';} } } async function approveExternalDraft(kind,id){ if(kind==='news'){ // Use an on-page editor instead of the browser prompt, which is unreliable on some Android browsers. const button=[...document.querySelectorAll('button[data-review-action="approve"]')].find(b=>b.dataset.kind==='news'&&String(b.dataset.id)===String(id)); const title=button?.dataset.title||'News story'; const source=button?.dataset.source||''; const sourceSummary=button?.dataset.summary||''; const sourceUrl=button?.dataset.sourceUrl||''; if(!openIfekaSummaryModal(id,title,source,sourceSummary,sourceUrl))alert('Could not open the summary editor. Please refresh the page and try again.'); return; }else{ const card=[...document.querySelectorAll('button[data-review-action=\"approve\"]')].find(b=>b.dataset.kind==='opportunity'&&String(b.dataset.id)===String(id))?.closest('.review-card'); const label=String(card?.querySelector('small')?.textContent||'').toLowerCase().includes('jobs')?'job':'opportunity'; if(!confirm(`Approve this ${label} and publish it on IfekaHub?`))return; if(!await reviewActionViaWorker(kind,id,'approve'))return; await loadExternalReviewQueue(); if(typeof loadDynamicOpportunities==='function')await loadDynamicOpportunities(); if(typeof loadLiveJobs==='function')await loadLiveJobs(); } } async function rejectExternalDraft(kind,id){ if(!confirm('Reject and remove this external draft?'))return; if(!await reviewActionViaWorker(kind,id,'reject'))return; await loadExternalReviewQueue(); } document.addEventListener('click',e=>{ const b=e.target.closest?.('button[data-review-action]'); if(!b)return; const kind=b.dataset.kind||'', id=b.dataset.id||'', action=b.dataset.reviewAction||''; if(!id)return; if(action==='approve')approveExternalDraft(kind,id); else if(action==='reject')rejectExternalDraft(kind,id); }); document.addEventListener('DOMContentLoaded',()=>{ const cancel=document.getElementById('ifekaSummaryCancel'); const publish=document.getElementById('ifekaSummaryPublish'); const modal=document.getElementById('ifekaSummaryModal'); const text=document.getElementById('ifekaSummaryText'); const clearBtn=document.getElementById('ifekaSummaryClear'),saveBtn=document.getElementById('ifekaSummarySave'); if(cancel)cancel.addEventListener('click',closeIfekaSummaryModal); if(publish)publish.addEventListener('click',submitIfekaSummaryApproval); if(text)text.addEventListener('input',updateIfekaSummaryStats); if(clearBtn)clearBtn.addEventListener('click',clearIfekaSummaryDraft); if(saveBtn)saveBtn.addEventListener('click',saveIfekaSummaryDraft); if(modal)modal.addEventListener('click',e=>{if(e.target===modal)closeIfekaSummaryModal();}); document.addEventListener('keydown',e=>{if(e.key==='Escape')closeIfekaSummaryModal();}); }); function toggleManualNewsPublisher(){ const wrap=document.getElementById('manualNewsFormWrap'),btn=document.getElementById('manualNewsToggle'); if(!wrap)return; const opening=wrap.classList.contains('hidden'); wrap.classList.toggle('hidden',!opening); if(btn)btn.textContent=opening?'Close Publisher':'Open Publisher'; } function extractManualImageUrls(raw){ return String(raw||'').split(/\r?\n/).map(x=>x.trim()).filter(x=>/^https?:\/\//i.test(x)).slice(0,12); } function extractArticleImages(content){ const m=String(content||'').match(/\n?\n?\[IFEKA_ARTICLE_IMAGES\]([\s\S]*?)\[\/IFEKA_ARTICLE_IMAGES\]/i); const urls=m?m[1].split('\n').map(x=>x.trim()).filter(x=>/^https?:\/\//i.test(x)):[]; return {text:String(content||'').replace(/\n?\n?\[IFEKA_ARTICLE_IMAGES\][\s\S]*?\[\/IFEKA_ARTICLE_IMAGES\]/i,'').trim(),images:urls}; } function articleImagesMarkup(content){ const data=extractArticleImages(content); if(!data.images.length)return ''; return `
${data.images.map((u,i)=>`Article image ${i+1}`).join('')}
`; } function extractNewsMedia(content){ const raw=String(content||''); const imgs=extractArticleImages(raw); const vm=imgs.text.match(/\n?\n?\[IFEKA_VIDEO\]([\s\S]*?)\[\/IFEKA_VIDEO\]/i); const video=vm?String(vm[1]).trim():''; return {text:imgs.text.replace(/\n?\n?\[IFEKA_VIDEO\][\s\S]*?\[\/IFEKA_VIDEO\]/i,'').trim(),images:imgs.images,video_url:video}; } function cleanArticleText(content){ return extractNewsMedia(content).text; } function youtubeEmbedUrl(url){ try{const u=new URL(url); if(/(^|\.)youtube\.com$/i.test(u.hostname)){const id=u.searchParams.get('v'); if(id)return `https://www.youtube.com/embed/${encodeURIComponent(id)}`; const m=u.pathname.match(/\/(?:shorts|embed)\/([^/?]+)/); if(m)return `https://www.youtube.com/embed/${encodeURIComponent(m[1])}`;} if(/youtu\.be$/i.test(u.hostname)){const id=u.pathname.split('/').filter(Boolean)[0]; if(id)return `https://www.youtube.com/embed/${encodeURIComponent(id)}`;} }catch(e){} return ''; } function facebookEmbedUrl(url){ try{const u=new URL(url); if(/(^|\.)facebook\.com$/i.test(u.hostname)||/(^|\.)fb\.watch$/i.test(u.hostname)){return `https://www.facebook.com/plugins/video.php?href=${encodeURIComponent(url)}&show_text=false&width=560`;}}catch(e){} return ''; } function videoMarkup(p){ const u=String(p.video_url||''); const y=youtubeEmbedUrl(u); if(y)return ``; const f=facebookEmbedUrl(u); if(f)return ``; return ``; } async function uploadManualFile(file,bucket,session,prefix,maxBytes,label){ if(!file)return ''; if(file.size>maxBytes)throw new Error(`${label} is too large. Maximum is ${formatBytes(maxBytes)}.`); const safe=file.name.replace(/[^a-zA-Z0-9._-]/g,'_'); const path=`${session.user.id}/${Date.now()}-${prefix}-${Math.random().toString(36).slice(2,8)}-${safe}`; const up=await db.storage.from(bucket).upload(path,file,{upsert:false,contentType:file.type,cacheControl:'3600'}); if(up.error)throw new Error(`${label} upload failed: ${storageErrorText(up.error,bucket)}`); const pub=db.storage.from(bucket).getPublicUrl(path); if(pub.error||!pub.data?.publicUrl)throw new Error(`${label} uploaded but its public URL could not be created. Make "${bucket}" public in Supabase Storage.`); return pub.data.publicUrl; } async function manualPublishNews(event){ event.preventDefault(); const m=document.getElementById('manualNewsMessage'),b=document.getElementById('manualNewsPublish'); const title=(document.getElementById('manualNewsTitle')?.value||'').trim(); const category=document.getElementById('manualNewsCategory')?.value||'Trending News'; const source=(document.getElementById('manualNewsSource')?.value||'').trim(); const sourceUrl=(document.getElementById('manualNewsUrl')?.value||'').trim(); let content=(document.getElementById('manualNewsContent')?.value||'').trim(); const imageUrl=(document.getElementById('manualNewsImageUrl')?.value||'').trim(); const videoUrl=(document.getElementById('manualNewsVideoUrl')?.value||'').trim(); const imageFile=document.getElementById('manualNewsImageFile')?.files?.[0]||null; const videoFile=document.getElementById('manualNewsVideoFile')?.files?.[0]||null; const extraUrls=extractManualImageUrls(document.getElementById('manualNewsArticleImageUrls')?.value||''); const extraFiles=[...(document.getElementById('manualNewsArticleImageFiles')?.files||[])].slice(0,10); if(!title||content.length<20){if(m){m.style.display='block';m.className='notice error';m.textContent='Please enter a headline and meaningful news content.';}return;} for(const u of [sourceUrl,imageUrl,videoUrl]) if(u && !/^https?:\/\//i.test(u)){if(m){m.style.display='block';m.className='notice error';m.textContent='Links must start with https:// or http://';}return;} const {data:sd}=await db.auth.getSession(); if(!sd?.session){if(m){m.style.display='block';m.className='notice error';m.textContent='Please log in as the IfekaHub administrator first.';}return;} if(m){m.style.display='block';m.className='notice';m.textContent='Preparing your news...';} if(b){b.disabled=true;b.textContent='Publishing…';} try{ let image_url=imageUrl||''; let video_url=videoUrl||''; if(imageFile){m.textContent='Uploading featured image...'; image_url=await uploadManualFile(imageFile,BUCKET,sd.session,'manual-image',10*1024*1024,'Featured image');} if(videoFile){m.textContent='Uploading video...'; video_url=await uploadManualFile(videoFile,VIDEO_BUCKET,sd.session,'manual-video',100*1024*1024,'Video');} const allImages=[...extraUrls]; for(const file of extraFiles){m.textContent=`Uploading article image ${allImages.length+1}...`; allImages.push(await uploadManualFile(file,BUCKET,sd.session,'article-image',10*1024*1024,'Article image'));} if(allImages.length) content += `\n\n[IFEKA_ARTICLE_IMAGES]\n${allImages.join('\n')}\n[/IFEKA_ARTICLE_IMAGES]`; if(m)m.textContent='Saving news to Supabase...'; const ins=await db.from('blog_posts').insert({title,content,image_url:image_url||null,video_url:video_url||null,category,author:'Ifeka',published:true}); if(ins.error)throw new Error(ins.error.message); if(m){m.className='notice';m.textContent='βœ… News published successfully with the selected media.';} document.getElementById('manualNewsForm')?.reset(); const cat=document.getElementById('manualNewsCategory');if(cat)cat.value=category; try{await loadBlogPosts();}catch(e){console.warn('Manual news refresh warning:',e);} try{await loadAdminPosts();}catch(e){console.warn('Manual admin refresh warning:',e);} }catch(err){ console.error(err); if(m){m.className='notice error';m.textContent='❌ News publishing failed: '+(err?.message||err);} }finally{ if(b){b.disabled=false;b.textContent='πŸ“° Publish News';} } } document.addEventListener('DOMContentLoaded',()=>{ const t=document.getElementById('manualNewsToggle'); const f=document.getElementById('manualNewsForm'); if(t)t.addEventListener('click',toggleManualNewsPublisher); if(f)f.addEventListener('submit',manualPublishNews); }); document.addEventListener('DOMContentLoaded',()=>{ const text=document.getElementById('ifekaSummaryText'); if(text)text.addEventListener('input',()=>{updateIfekaSummaryStats(); if(ifekaSummaryPreviewOpen)previewIfekaSummary();}); const bind=(id,fn)=>{const b=document.getElementById(id);if(b)b.addEventListener('click',fn);}; bind('ifekaSummaryClear',clearIfekaSummaryDraft); bind('ifekaSummarySave',saveIfekaSummaryDraft); bind('ifekaSummaryGenerate',generateIfekaSummaryStarter); const targetSel=document.getElementById('ifekaSummaryTargetWords'); if(targetSel)targetSel.addEventListener('change',()=>{updateIfekaSummaryStats();runIfekaEditorialQualityCheck();}); bind('ifekaSummaryExpand',expandIfekaSummaryDraft); bind('ifekaSummaryFetchSource',fetchIfekaSourceFacts); bind('ifekaSummaryFetchMedia',fetchIfekaSourceMedia); ['ifekaSummaryImageUrl','ifekaSummaryVideoUrl','ifekaSummaryImageFile','ifekaSummaryVideoFile'].forEach(k=>{const e=document.getElementById(k);if(e)e.addEventListener('input',updateIfekaMediaPreview);if(e)e.addEventListener('change',updateIfekaMediaPreview);}); bind('ifekaSummaryPreviewBtn',previewIfekaSummary); bind('ifekaSummaryCancel',()=>{resetIfekaSummaryPreview();closeIfekaSummaryModal();}); bind('ifekaSummaryPublish',submitIfekaSummaryApproval); bindEditorialChecklist(); }); function startExternalSourceMonitor(){ checkExternalSources(false); setInterval(()=>checkExternalSources(false),10*60*1000); } document.addEventListener('DOMContentLoaded',()=>setTimeout(()=>{loadExternalReviewQueue();startExternalSourceMonitor();},800));