import {
  Document, Packer, Paragraph, TextRun, HeadingLevel,
  Table, TableRow, TableCell, WidthType, AlignmentType,
  PageBreak, Header, Footer, PageOrientation,
  ShadingType, BorderStyle, TabStopPosition, TabStopType
} from 'docx';

const GOLD = 'C9A84C';
const NAVY = '070A0D';
const EMERALD = '2ECC71';
const BODY_COLOR = '333333';

const FONT_TITLE = 'Georgia';
const FONT_BODY = 'Calibri';
const FONT_MONO = 'Consolas';

function goldText(text, size = 24, bold = true) {
  return new TextRun({ text, font: FONT_TITLE, size: size * 2, bold, color: GOLD });
}

function bodyText(text, opts = {}) {
  return new TextRun({
    text,
    font: FONT_BODY,
    size: (opts.size || 11) * 2,
    bold: opts.bold || false,
    color: opts.color || BODY_COLOR,
    italics: opts.italics || false,
  });
}

function sectionHeading(text) {
  return new Paragraph({
    children: [goldText(text, 16)],
    heading: HeadingLevel.HEADING_2,
    spacing: { before: 400, after: 200 },
    border: { bottom: { color: GOLD, size: 1, style: BorderStyle.SINGLE, space: 4 } },
  });
}

function subHeading(text) {
  return new Paragraph({
    children: [new TextRun({ text, font: FONT_BODY, size: 24, bold: true, color: EMERALD })],
    spacing: { before: 300, after: 120 },
  });
}

function para(parts, opts = {}) {
  return new Paragraph({
    children: Array.isArray(parts) ? parts : [bodyText(parts)],
    spacing: { after: opts.after || 160, before: opts.before || 0 },
    alignment: opts.alignment || AlignmentType.JUSTIFIED,
  });
}

function bullet(parts) {
  return [new Paragraph({
    children: Array.isArray(parts) ? parts : [bodyText(parts)],
    spacing: { after: 80 },
    bullet: { level: 0 },
  })];
}

function tableRow(cells, isHeader = false) {
  return new TableRow({
    tableHeader: isHeader,
    children: cells.map(c => new TableCell({
      children: [new Paragraph({
        children: [new TextRun({
          text: c,
          font: FONT_BODY,
          size: isHeader ? 20 : 18,
          bold: isHeader,
          color: isHeader ? 'FFFFFF' : BODY_COLOR,
        })],
        spacing: { before: 40, after: 40 },
      })],
      width: { size: 100 / cells.length, type: WidthType.PERCENTAGE },
      shading: isHeader ? { type: ShadingType.CLEAR, color: NAVY, fill: NAVY } : undefined,
    })),
  });
}

function infoTable(rows, colWidths) {
  return [new Table({
    rows: rows.map(([label, value], i) => new TableRow({
      children: [
        new TableCell({
          children: [new Paragraph({ children: [bodyText(label, { bold: true, size: 10 })] })],
          width: colWidths ? { size: colWidths[0], type: WidthType.PERCENTAGE } : { size: 30, type: WidthType.PERCENTAGE },
          shading: i % 2 === 0 ? { type: ShadingType.CLEAR, color: 'F5F3EE', fill: 'F5F3EE' } : undefined,
        }),
        new TableCell({
          children: [new Paragraph({ children: [bodyText(value, { size: 10 })] })],
          width: colWidths ? { size: colWidths[1], type: WidthType.PERCENTAGE } : { size: 70, type: WidthType.PERCENTAGE },
          shading: i % 2 === 0 ? { type: ShadingType.CLEAR, color: 'F5F3EE', fill: 'F5F3EE' } : undefined,
        }),
      ],
    })),
  })];
}

const doc = new Document({
  title: 'Nur Falah — App Store Listing',
  description: 'Complete App Store Connect submission for Nur Falah Muslim Companion',
  styles: {
    default: {
      document: {
        run: { font: FONT_BODY, size: 22 },
        paragraph: { spacing: { after: 120 } },
      },
    },
  },
  sections: [{
    properties: {
      page: {
        size: { width: 12240, height: 15840 },
        margin: { top: 1440, bottom: 1440, left: 1440, right: 1440 },
      },
    },
    headers: {
      default: new Header({
        children: [new Paragraph({
          children: [new TextRun({ text: 'Nur Falah — Muslim Companion', font: FONT_BODY, size: 16, color: '999999' })],
          alignment: AlignmentType.RIGHT,
          border: { bottom: { color: GOLD, size: 1, style: BorderStyle.SINGLE, space: 4 } },
        })],
      }),
    },
    footers: {
      default: new Footer({
        children: [new Paragraph({
          children: [new TextRun({
            text: 'Confidential — App Store Connect Submission',
            font: FONT_BODY, size: 16, color: '999999', italics: true,
          })],
          alignment: AlignmentType.CENTER,
        })],
      }),
    },
    children: [
      // ===== TITLE PAGE =====
      new Paragraph({ spacing: { before: 3000 } }),
      new Paragraph({
        children: [new TextRun({ text: 'Nur Falah', font: FONT_TITLE, size: 56, bold: true, color: NAVY })],
        alignment: AlignmentType.CENTER,
      }),
      new Paragraph({
        children: [new TextRun({ text: 'Muslim Companion', font: FONT_TITLE, size: 36, color: GOLD })],
        alignment: AlignmentType.CENTER,
        spacing: { after: 200 },
      }),
      new Paragraph({
        children: [new TextRun({ text: 'App Store Connect Submission', font: FONT_BODY, size: 24, color: '666666' })],
        alignment: AlignmentType.CENTER,
        spacing: { after: 600 },
      }),
      new Paragraph({
        children: [new TextRun({ text: 'Prepared: August 2026', font: FONT_BODY, size: 20, color: '999999' })],
        alignment: AlignmentType.CENTER,
      }),
      new Paragraph({
        children: [new TextRun({ text: 'Falah Consultancy Ltd', font: FONT_BODY, size: 20, color: '999999' })],
        alignment: AlignmentType.CENTER,
      }),

      // ===== TABLE OF CONTENTS =====
      new Paragraph({ children: [new PageBreak()] }),
      new Paragraph({ children: [goldText('Table of Contents', 20)], spacing: { after: 300 } }),
      ...['1. Basic Information', '2. App Description', '3. What\'s New', '4. Keywords', '5. Support & Marketing URLs', '6. Category & Rating', '7. Screenshot Plan', '8. App Preview Storyboard', '9. Privacy Policy', '10. Localization Roadmap', '11. App Store Optimization'].map(
        (t, i) => new Paragraph({
          children: [bodyText(t, { size: 11 })],
          spacing: { after: 80 },
          tabStops: [{ type: TabStopType.RIGHT, position: 9000 }],
        })
      ),

      // ===== SECTION 1: BASIC INFO =====
      new Paragraph({ children: [new PageBreak()] }),
      new Paragraph({ children: [goldText('1. Basic Information', 28)], spacing: { after: 300 } }),
      ...infoTable([
        ['App Name', 'Nur Falah — Muslim Companion'],
        ['Subtitle', 'Prayer Times, Quran, Qibla & Dhikr'],
        ['Primary Language', 'English (UK)'],
        ['Primary Category', 'Lifestyle'],
        ['Secondary Category', 'Reference'],
        ['Age Rating', '4+'],
      ]),

      // ===== SECTION 2: DESCRIPTION =====
      new Paragraph({ children: [new PageBreak()] }),
      sectionHeading('2. App Description'),
      para('Nur Falah is your complete Muslim companion — a beautiful, free, and private app that brings everything you need for your daily Islamic practice into one place. No ads. No tracking. No account required.'),

      subHeading('🕌 Prayer Times'),
      para('Get accurate prayer times based on your location. View today\'s full schedule with Fajr, Sunrise, Dhuhr, Asr, Maghrib, and Isha — always with the next prayer prominently highlighted so you never miss a salah. Choose from five trusted calculation methods: Muslim World League, ISNA (North America), Umm al-Qura, Egyptian General Authority, and Karachi University. Enable optional push notifications so your device reminds you when it\'s time to pray.'),

      subHeading('🧭 Qibla Finder'),
      para('Find the exact direction of the Kaaba from anywhere in the world. The built-in compass calibrates to your device\'s sensors and shows your bearing toward Al-Masjid Al-Haram (21.42° N, 39.83° E) with precision. Simply move your device to calibrate — no internet needed once loaded.'),

      subHeading('📖 Holy Quran'),
      para('Read the complete Holy Quran with all 114 surahs. Each surah is presented with its Arabic name, English transliteration, and ayah count. The clean, distraction-free reading interface lets you focus on the words of Allah. Browse by surah number or scroll through the full list.'),

      subHeading('📅 Hijri Calendar'),
      para('Stay connected to the Islamic calendar. View today\'s complete Hijri date with day, month name in Arabic (e.g., 27 Ṣafar 1448 AH), and the corresponding Gregorian date. See the day of the week in Arabic, the month number, total days in the current Islamic month, and the AH (Anno Hegirae) designation — all on one screen.'),

      subHeading('📿 Tasbih Counter'),
      para('Remember Allah with the digital tasbih counter. Tap the large circular counter or press the Space bar on your keyboard to increment. Set your target to 33, 99, 100, or 500 — the classic counts for Subhanallah, Alhamdulillah, and Allahu Akbar after each prayer. Track your total count for the day and reset when you wish.'),

      subHeading('💚 99 Names of Allah'),
      para('Study and reflect on the 99 Beautiful Names of Allah (Asma-ul-Husna). Each name is displayed with its Arabic calligraphy and English transliteration in order. Use the search function to quickly find any name. Tap any name to view it in detail.'),

      subHeading('✨ Why Nur Falah?'),
      ...bullet('100% Free — no subscriptions, no in-app purchases, no hidden costs'),
      ...bullet('Works offline for Qibla and Tasbih after initial load'),
      ...bullet('Progressive Web App — installs to your home screen like a native app'),
      ...bullet('Lightweight and fast — under 1 MB'),
      ...bullet('Privacy-first: we collect no personal data'),
      ...bullet('Beautiful, modern design optimized for both phone and tablet'),
      ...bullet('Built with Falah OS — sovereign digital economy infrastructure'),

      para('Whether you\'re at home, at work, travelling, or at the masjid, Nur Falah is the only Muslim companion you need. Download now and make every moment count.'),

      // ===== SECTION 3: WHAT'S NEW =====
      new Paragraph({ children: [new PageBreak()] }),
      sectionHeading('3. What\'s New'),
      subHeading('Version 1.0.0'),
      ...bullet('Initial release'),
      ...bullet('Prayer Times with 5 calculation methods and notification support'),
      ...bullet('Qibla Finder with live compass'),
      ...bullet('Complete Holy Quran with all 114 surahs'),
      ...bullet('Hijri Calendar with Gregorian conversion'),
      ...bullet('Tasbih Counter with configurable targets (33/99/100/500)'),
      ...bullet('99 Names of Allah with search'),

      // ===== SECTION 4: KEYWORDS =====
      new Paragraph({ children: [new PageBreak()] }),
      sectionHeading('4. Keywords (100 characters max)'),
      para('Islam, Muslim, Quran, prayer times, qibla, salah, tasbih, dhikr, hijri, islamic calendar, 99 names of allah, asmaul husna, adhan, fajr, dhuhr, asr, maghrib, isha, ramadan, muslim app, islamic app, mecca, kaaba'),
      para([bodyText('Character count: ', { bold: true }), bodyText('~95 characters (comma-separated)')]),

      // ===== SECTION 5: URLs =====
      new Paragraph({ children: [new PageBreak()] }),
      sectionHeading('5. Support & Marketing URLs'),
      ...infoTable([
        ['Support URL', 'https://moslem.falahos.my'],
        ['Marketing URL', 'https://moslem.falahos.my'],
        ['Privacy Policy URL', 'https://moslem.falahos.my/privacy'],
      ]),

      // ===== SECTION 6: CATEGORY & RATING =====
      sectionHeading('6. Category & Rating'),
      ...infoTable([
        ['Primary Category', 'Lifestyle'],
        ['Secondary Category', 'Reference'],
        ['Age Rating', '4+'],
        ['Content Rights', 'No copyrighted content — public domain Quran, independently developed'],
      ]),

      // ===== SECTION 7: SCREENSHOT PLAN =====
      new Paragraph({ children: [new PageBreak()] }),
      sectionHeading('7. Screenshot Plan'),

      subHeading('iPhone (6.7" / 6.5" / 5.5")'),
      new Table({
        rows: [
          tableRow(['#', 'Screen', 'Caption'], true),
          ...[
            ['1', 'Prayer Times — Home with schedule & next prayer highlighted', 'Accurate prayer times with 5 calculation methods'],
            ['2', 'Qibla Finder — Compass showing Kaaba direction & bearing', 'Find the Qibla from anywhere in the world'],
            ['3', 'Holy Quran — Surah list with Arabic names & ayah counts', 'The complete Holy Quran — all 114 surahs'],
            ['4', '99 Names of Allah — Grid with Arabic & transliteration', 'Study and reflect on the 99 Beautiful Names'],
            ['5', 'Tasbih Counter — Circular counter with target dropdown', 'Digital tasbih — tap to remember Allah'],
            ['6', 'Hijri Calendar — Full Islamic date & Gregorian conversion', 'Stay connected to the Islamic calendar'],
          ].map((r, i) => tableRow(r, false)),
        ],
      }),

      subHeading('iPad (12.9" / 11" / 10.5")'),
      new Table({
        rows: [
          tableRow(['#', 'Screen', 'Caption'], true),
          ...[
            ['1', 'Prayer Times (landscape) — Full schedule with next prayer banner', 'Beautifully designed for iPad'],
            ['2', 'Holy Quran (landscape) — Surah list in two-column view', 'Read and browse the Quran on a bigger screen'],
            ['3', '99 Names of Allah (iPad) — Multiple rows of Asma-ul-Husna', 'Search and explore all 99 names'],
          ].map((r, i) => tableRow(r, false)),
        ],
      }),

      // ===== SECTION 8: APP PREVIEW =====
      sectionHeading('8. App Preview (15-30 second video)'),
      para('Storyboard:'),
      ...bullet('0-5s — Launch into Prayer Times, show schedule, tap notification toggle'),
      ...bullet('5-10s — Swipe to Qibla, show compass calibration and bearing'),
      ...bullet('10-15s — Quick scroll through Quran surahs, tap into 99 Names'),
      ...bullet('15-20s — Show Tasbih counter in use, Hijri calendar details'),
      para([bodyText('Note: ', { bold: true, size: 10, color: EMERALD }), bodyText('Use device frame overlay for a polished look. Export at 1080×1920 (iPhone portrait) or 2160×3840 for Retina.', { size: 10 })]),

      // ===== SECTION 9: PRIVACY POLICY =====
      new Paragraph({ children: [new PageBreak()] }),
      sectionHeading('9. Privacy Policy'),
      para('The following privacy policy is published at https://moslem.falahos.my/privacy and meets Apple\'s requirement for all apps:'),

      subHeading('Nur Falah Privacy Policy'),
      para('Last updated: August 2026'),
      para('Nur Falah ("we", "our", "us") does not collect, store, or transmit any personal data.'),

      subHeading('Information We Do NOT Collect:'),
      ...bullet('No account registration required'),
      ...bullet('No location data stored — prayer times use device GPS only, never transmitted'),
      ...bullet('No usage analytics or tracking'),
      ...bullet('No cookies or persistent identifiers'),
      ...bullet('No advertising identifiers (IDFA)'),

      subHeading('Device Permissions:'),
      ...bullet('Location: Used only on-device to calculate accurate prayer times and Qibla direction. Data never leaves your device.'),
      ...bullet('Notifications: Used solely for prayer time reminders. Configurable and opt-in.'),

      subHeading('Third-Party Services:'),
      ...bullet('Nur Falah does not integrate any third-party analytics, advertising, or tracking SDKs.'),
      ...bullet('Quran text and calculation algorithms are open-source and processed entirely on your device.'),

      subHeading('Data Deletion:'),
      para('Since we store no data, there is nothing to delete. Uninstalling the app removes all local data.'),

      subHeading('Contact:'),
      para('For questions: wanjauhari@gmail.com'),

      // ===== SECTION 10: LOCALIZATION =====
      new Paragraph({ children: [new PageBreak()] }),
      sectionHeading('10. Localization Roadmap'),
      new Table({
        rows: [
          tableRow(['Language', 'Priority', 'Notes'], true),
          ...[
            ['Arabic', 'High', 'Full RTL support, Quran Arabic already present'],
            ['Malay', 'High', 'Primary SEA market — Malaysia & Indonesia'],
            ['Urdu', 'Medium', 'Pakistan & India — RTL support'],
            ['Turkish', 'Medium', 'Growing digital Muslim market'],
            ['French', 'Medium', 'Large European Muslim population'],
            ['German', 'Low', 'Growing German Muslim demographic'],
          ].map((r, i) => tableRow(r, false)),
        ],
      }),

      // ===== SECTION 11: ASO =====
      sectionHeading('11. App Store Optimization'),
      new Table({
        rows: [
          tableRow(['Factor', 'Recommendation'], true),
          ...[
            ['Title Keywords', 'Include: "Muslim Companion — Prayer Times Quran Qibla"'],
            ['App Icon', 'Green/emerald bg with crescent or "نور" calligraphy — stands out from blue/white competitors'],
            ['Rating Prompt', 'Request review after 5th app open (non-obtrusive)'],
            ['Competitors', 'Muslim Pro, Athan (IslamicFinder), Quran Pro, Pillars, NamazApp'],
            ['Differentiator', 'Zero ads, zero tracking, zero accounts — pure Islamic experience'],
            ['Promotional Text', 'Your free Muslim companion: Prayer times, Qibla compass, complete Quran, Hijri calendar, tasbih counter & 99 Names. No ads. No tracking.'],
          ].map((r, i) => tableRow(r, false)),
        ],
      }),

      // ===== CLOSING =====
      new Paragraph({ spacing: { before: 600 } }),
      new Paragraph({
        children: [new TextRun({ text: '— End of Submission —', font: FONT_BODY, size: 20, color: GOLD, italics: true })],
        alignment: AlignmentType.CENTER,
      }),
      new Paragraph({
        children: [new TextRun({ text: 'Prepared for App Store Connect. All fields verified against Apple Developer Guidelines.', font: FONT_BODY, size: 18, color: '999999', italics: true })],
        alignment: AlignmentType.CENTER,
        spacing: { before: 200 },
      }),
    ],
  }],
});

// Write to file
const buffer = await Packer.toBuffer(doc);
import { writeFile } from 'fs';
writeFile('Nur-Falah-App-Store-Submission.docx', buffer, () => {
  console.log('✅ DOCX written: Nur-Falah-App-Store-Submission.docx');
});
